/* Minification failed. Returning unminified contents.
(2184,27-28): run-time error JS1195: Expected expression: >
(2184,60-61): run-time error JS1195: Expected expression: )
(2187,27-28): run-time error JS1195: Expected expression: >
(2187,90-91): run-time error JS1195: Expected expression: )
(2583,13-14): run-time error JS1014: Invalid character: `
(2583,14-15): run-time error JS1195: Expected expression: <
(2583,36-37): run-time error JS1195: Expected expression: <
(2583,42-43): run-time error JS1014: Invalid character: `
(2586,8-9): run-time error JS1004: Expected ';': :
(2588,5-16): run-time error JS1197: Too many errors. The file might not be a JavaScript file: destination
 */
/*!
 * Bootstrap v3.3.5 (http://getbootstrap.com)
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under the MIT license
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.5",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.5",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.5",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.5",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.5",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",c).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.5",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){d.$element.one("mouseup.dismiss.bs.modal",function(b){a(b.target).is(d.$element)&&(d.ignoreBackdropClick=!0)})}),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in"),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$dialog.one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+e).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth<a,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",a,b)};c.VERSION="3.3.5",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-m<o.top?"bottom":"right"==h&&k.right+l>o.width?"left":"left"==h&&k.left-l<o.left?"right":h,f.removeClass(n).addClass(h)}var p=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(p,h);var q=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",q).emulateTransitionEnd(c.TRANSITION_DURATION):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top+=g,b.left+=h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=a(this.$tip),g=a.Event("hide.bs."+this.type);return this.$element.trigger(g),g.isDefaultPrevented()?void 0:(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=d?{top:0,left:0}:b.offset(),g={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},h=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,g,h,f)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.5",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.5",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(void 0===e[a+1]||b<e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),
d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.5",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.5",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);;
/**
 * bootbox.js v4.3.0
 *
 * http://bootboxjs.com/license.txt
 * 
 * CCB Dev Note:
 * This file has been modified from the original to add an aria label to the input file for the prompt to be ADA compliant.
 * If this file is to be replaced, verifiy that the new solution will add aria label support for prompt inputs
 * 
 * 
 */
!function (a, b) { "use strict"; "function" == typeof define && define.amd ? define(["jquery"], b) : "object" == typeof exports ? module.exports = b(require("jquery")) : a.bootbox = b(a.jQuery) }(this, function a(b, c) { "use strict"; function d(a) { var b = q[o.locale]; return b ? b[a] : q.en[a] } function e(a, c, d) { a.stopPropagation(), a.preventDefault(); var e = b.isFunction(d) && d(a) === !1; e || c.modal("hide") } function f(a) { var b, c = 0; for (b in a) c++; return c } function g(a, c) { var d = 0; b.each(a, function (a, b) { c(a, b, d++) }) } function h(a) { var c, d; if ("object" != typeof a) throw new Error("Please supply an object of options"); if (!a.message) throw new Error("Please specify a message"); return a = b.extend({}, o, a), a.buttons || (a.buttons = {}), a.backdrop = a.backdrop ? "static" : !1, c = a.buttons, d = f(c), g(c, function (a, e, f) { if (b.isFunction(e) && (e = c[a] = { callback: e }), "object" !== b.type(e)) throw new Error("button with key " + a + " must be an object"); e.label || (e.label = a), e.className || (e.className = 2 >= d && f === d - 1 ? "btn-primary" : "btn-default") }), a } function i(a, b) { var c = a.length, d = {}; if (1 > c || c > 2) throw new Error("Invalid argument length"); return 2 === c || "string" == typeof a[0] ? (d[b[0]] = a[0], d[b[1]] = a[1]) : d = a[0], d } function j(a, c, d) { return b.extend(!0, {}, a, i(c, d)) } function k(a, b, c, d) { var e = { className: "bootbox-" + a, buttons: l.apply(null, b) }; return m(j(e, d, c), b) } function l() { for (var a = {}, b = 0, c = arguments.length; c > b; b++){ var e = arguments[b], f = e.toLowerCase(), g = e.toUpperCase(); a[f] = { label: d(g) } } return a } function m(a, b) { var d = {}; return g(b, function (a, b) { d[b] = !0 }), g(a.buttons, function (a) { if (d[a] === c) throw new Error("button key " + a + " is not allowed (options are " + b.join("\n") + ")") }), a } var n = { dialog: "<div class='bootbox modal' tabindex='-1' role='dialog'><div class='modal-dialog'><div class='modal-content'><div class='modal-body'><div class='bootbox-body'></div></div></div></div></div>", header: "<div class='modal-header'><h4 class='modal-title'></h4></div>", footer: "<div class='modal-footer'></div>", closeButton: "<button type='button' class='bootbox-close-button close' data-dismiss='modal' aria-hidden='true'>&times;</button>", form: "<form class='bootbox-form'></form>", inputs: { text: "<input aria-label='Search Name' class='bootbox-input bootbox-input-text form-control' autocomplete=off type=text />", textarea: "<textarea class='bootbox-input bootbox-input-textarea form-control'></textarea>", email: "<input class='bootbox-input bootbox-input-email form-control' autocomplete='off' type='email' />", select: "<select class='bootbox-input bootbox-input-select form-control'></select>", checkbox: "<div class='checkbox'><label><input class='bootbox-input bootbox-input-checkbox' type='checkbox' /></label></div>", date: "<input class='bootbox-input bootbox-input-date form-control' autocomplete=off type='date' />", time: "<input class='bootbox-input bootbox-input-time form-control' autocomplete=off type='time' />", number: "<input class='bootbox-input bootbox-input-number form-control' autocomplete=off type='number' />", password: "<input class='bootbox-input bootbox-input-password form-control' autocomplete='off' type='password' />" } }, o = { locale: "en", backdrop: !0, animate: !0, className: null, closeButton: !0, show: !0, container: "body" }, p = {}; p.alert = function () { var a; if (a = k("alert", ["ok"], ["message", "callback"], arguments), a.callback && !b.isFunction(a.callback)) throw new Error("alert requires callback property to be a function when provided"); return a.buttons.ok.callback = a.onEscape = function () { return b.isFunction(a.callback) ? a.callback() : !0 }, p.dialog(a) }, p.confirm = function () { var a; if (a = k("confirm", ["cancel", "confirm"], ["message", "callback"], arguments), a.buttons.cancel.callback = a.onEscape = function () { return a.callback(!1) }, a.buttons.confirm.callback = function () { return a.callback(!0) }, !b.isFunction(a.callback)) throw new Error("confirm requires a callback"); return p.dialog(a) }, p.prompt = function () { var a, d, e, f, h, i, k; if (f = b(n.form), d = { className: "bootbox-prompt", buttons: l("cancel", "confirm"), value: "", inputType: "text" }, a = m(j(d, arguments, ["title", "callback"]), ["cancel", "confirm"]), i = a.show === c ? !0 : a.show, a.message = f, a.buttons.cancel.callback = a.onEscape = function () { return a.callback(null) }, a.buttons.confirm.callback = function () { var c; switch (a.inputType) { case "text": case "textarea": case "email": case "select": case "date": case "time": case "number": case "password": c = h.val(); break; case "checkbox": var d = h.find("input:checked"); c = [], g(d, function (a, d) { c.push(b(d).val()) }) }return a.callback(c) }, a.show = !1, !a.title) throw new Error("prompt requires a title"); if (!b.isFunction(a.callback)) throw new Error("prompt requires a callback"); if (!n.inputs[a.inputType]) throw new Error("invalid prompt type"); switch (h = b(n.inputs[a.inputType]), a.inputType) { case "text": case "textarea": case "email": case "date": case "time": case "number": case "password": h.val(a.value); break; case "select": var o = {}; if (k = a.inputOptions || [], !k.length) throw new Error("prompt with select requires options"); g(k, function (a, d) { var e = h; if (d.value === c || d.text === c) throw new Error("given options in wrong format"); d.group && (o[d.group] || (o[d.group] = b("<optgroup/>").attr("label", d.group)), e = o[d.group]), e.append("<option value='" + d.value + "'>" + d.text + "</option>") }), g(o, function (a, b) { h.append(b) }), h.val(a.value); break; case "checkbox": var q = b.isArray(a.value) ? a.value : [a.value]; if (k = a.inputOptions || [], !k.length) throw new Error("prompt with checkbox requires options"); if (!k[0].value || !k[0].text) throw new Error("given options in wrong format"); h = b("<div/>"), g(k, function (c, d) { var e = b(n.inputs[a.inputType]); e.find("input").attr("value", d.value), e.find("label").append(d.text), g(q, function (a, b) { b === d.value && e.find("input").prop("checked", !0) }), h.append(e) }) }return a.placeholder && h.attr("placeholder", a.placeholder), a.pattern && h.attr("pattern", a.pattern), f.append(h), f.on("submit", function (a) { a.preventDefault(), a.stopPropagation(), e.find(".btn-primary").click() }), e = p.dialog(a), e.off("shown.bs.modal"), e.on("shown.bs.modal", function () { h.focus() }), i === !0 && e.modal("show"), e }, p.dialog = function (a) { a = h(a); var c = b(n.dialog), d = c.find(".modal-dialog"), f = c.find(".modal-body"), i = a.buttons, j = "", k = { onEscape: a.onEscape }; if (g(i, function (a, b) { j += "<button data-bb-handler='" + a + "' type='button' class='btn " + b.className + "'>" + b.label + "</button>", k[a] = b.callback }), f.find(".bootbox-body").html(a.message), a.animate === !0 && c.addClass("fade"), a.className && c.addClass(a.className), "large" === a.size && d.addClass("modal-lg"), "small" === a.size && d.addClass("modal-sm"), a.title && f.before(n.header), a.closeButton) { var l = b(n.closeButton); a.title ? c.find(".modal-header").prepend(l) : l.css("margin-top", "-10px").prependTo(f) } return a.title && c.find(".modal-title").html(a.title), j.length && (f.after(n.footer), c.find(".modal-footer").html(j)), c.on("hidden.bs.modal", function (a) { a.target === this && c.remove() }), c.on("shown.bs.modal", function () { c.find(".btn-primary:first").focus() }), c.on("escape.close.bb", function (a) { k.onEscape && e(a, c, k.onEscape) }), c.on("click", ".modal-footer button", function (a) { var d = b(this).data("bb-handler"); e(a, c, k[d]) }), c.on("click", ".bootbox-close-button", function (a) { e(a, c, k.onEscape) }), c.on("keyup", function (a) { 27 === a.which && c.trigger("escape.close.bb") }), b(a.container).append(c), c.modal({ backdrop: a.backdrop, keyboard: !1, show: !1 }), a.show && c.modal("show"), c }, p.setDefaults = function () { var a = {}; 2 === arguments.length ? a[arguments[0]] = arguments[1] : a = arguments[0], b.extend(o, a) }, p.hideAll = function () { return b(".bootbox").modal("hide"), p }; var q = { br: { OK: "OK", CANCEL: "Cancelar", CONFIRM: "Sim" }, cs: { OK: "OK", CANCEL: "Zrušit", CONFIRM: "Potvrdit" }, da: { OK: "OK", CANCEL: "Annuller", CONFIRM: "Accepter" }, de: { OK: "OK", CANCEL: "Abbrechen", CONFIRM: "Akzeptieren" }, el: { OK: "Εντάξει", CANCEL: "Ακύρωση", CONFIRM: "Επιβεβαίωση" }, en: { OK: "OK", CANCEL: "Cancel", CONFIRM: "OK" }, es: { OK: "OK", CANCEL: "Cancelar", CONFIRM: "Aceptar" }, et: { OK: "OK", CANCEL: "Katkesta", CONFIRM: "OK" }, fi: { OK: "OK", CANCEL: "Peruuta", CONFIRM: "OK" }, fr: { OK: "OK", CANCEL: "Annuler", CONFIRM: "D'accord" }, he: { OK: "אישור", CANCEL: "ביטול", CONFIRM: "אישור" }, id: { OK: "OK", CANCEL: "Batal", CONFIRM: "OK" }, it: { OK: "OK", CANCEL: "Annulla", CONFIRM: "Conferma" }, ja: { OK: "OK", CANCEL: "キャンセル", CONFIRM: "確認" }, lt: { OK: "Gerai", CANCEL: "Atšaukti", CONFIRM: "Patvirtinti" }, lv: { OK: "Labi", CANCEL: "Atcelt", CONFIRM: "Apstiprināt" }, nl: { OK: "OK", CANCEL: "Annuleren", CONFIRM: "Accepteren" }, no: { OK: "OK", CANCEL: "Avbryt", CONFIRM: "OK" }, pl: { OK: "OK", CANCEL: "Anuluj", CONFIRM: "Potwierdź" }, pt: { OK: "OK", CANCEL: "Cancelar", CONFIRM: "Confirmar" }, ru: { OK: "OK", CANCEL: "Отмена", CONFIRM: "Применить" }, sv: { OK: "OK", CANCEL: "Avbryt", CONFIRM: "OK" }, tr: { OK: "Tamam", CANCEL: "İptal", CONFIRM: "Onayla" }, zh_CN: { OK: "OK", CANCEL: "取消", CONFIRM: "确认" }, zh_TW: { OK: "OK", CANCEL: "取消", CONFIRM: "確認" } }; return p.init = function (c) { return a(c || b) }, p });;
/* Modernizr 2.6.2 (Custom Build) | MIT & BSD
 * Build: http://modernizr.com/download/#-cssanimations-csstransitions-touch-shiv-cssclasses-prefixed-teststyles-testprop-testallprops-prefixes-domprefixes-load
 */
;window.Modernizr=function(a,b,c){function z(a){j.cssText=a}function A(a,b){return z(m.join(a+";")+(b||""))}function B(a,b){return typeof a===b}function C(a,b){return!!~(""+a).indexOf(b)}function D(a,b){for(var d in a){var e=a[d];if(!C(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function E(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:B(f,"function")?f.bind(d||b):f}return!1}function F(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+o.join(d+" ")+d).split(" ");return B(b,"string")||B(b,"undefined")?D(e,b):(e=(a+" "+p.join(d+" ")+d).split(" "),E(e,b,c))}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m=" -webkit- -moz- -o- -ms- ".split(" "),n="Webkit Moz O ms",o=n.split(" "),p=n.toLowerCase().split(" "),q={},r={},s={},t=[],u=t.slice,v,w=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["&#173;",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},x={}.hasOwnProperty,y;!B(x,"undefined")&&!B(x.call,"undefined")?y=function(a,b){return x.call(a,b)}:y=function(a,b){return b in a&&B(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=u.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(u.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(u.call(arguments)))};return e}),q.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:w(["@media (",m.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},q.cssanimations=function(){return F("animationName")},q.csstransitions=function(){return F("transition")};for(var G in q)y(q,G)&&(v=G.toLowerCase(),e[v]=q[G](),t.push((e[v]?"":"no-")+v));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)y(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},z(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=m,e._domPrefixes=p,e._cssomPrefixes=o,e.testProp=function(a){return D([a])},e.testAllProps=F,e.testStyles=w,e.prefixed=function(a,b,c){return b?F(a,b,c):F(a,"pfx")},g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+t.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};;
/**
 * jquery.dlmenu.js v1.0.1
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Copyright 2013, Codrops
 * http://www.codrops.com
 */
;( function( $, window, undefined ) {

	'use strict';

	// global
	var Modernizr = window.Modernizr, $body = $( 'body' );

	$.DLMenu = function( options, element ) {
		this.$el = $( element );
		this._init( options );
	};

	// the options
	$.DLMenu.defaults = {
		// classes for the animation effects
		animationClasses : { classin : 'dl-animate-in-2', classout : 'dl-animate-out-2' },
		// callback: click a link that has a sub menu
		// el is the link element (li); name is the level name
		onLevelClick : function( el, name ) { return false; },
		// callback: click a link that does not have a sub menu
		// el is the link element (li); ev is the event obj
		onLinkClick : function( el, ev ) { return false; }
	};

	$.DLMenu.prototype = {
		_init : function( options ) {

			// options
			this.options = $.extend( true, {}, $.DLMenu.defaults, options );
			// cache some elements and initialize some variables
			this._config();
			
			var animEndEventNames = {
					'WebkitAnimation' : 'webkitAnimationEnd',
					'OAnimation' : 'oAnimationEnd',
					'msAnimation' : 'MSAnimationEnd',
					'animation' : 'animationend'
				},
				transEndEventNames = {
					'WebkitTransition' : 'webkitTransitionEnd',
					'MozTransition' : 'transitionend',
					'OTransition' : 'oTransitionEnd',
					'msTransition' : 'MSTransitionEnd',
					'transition' : 'transitionend'
				};
			// animation end event name
			this.animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ] + '.dlmenu';
			// transition end event name
			this.transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ] + '.dlmenu',
			// support for css animations and css transitions
			this.supportAnimations = Modernizr.cssanimations,
			this.supportTransitions = Modernizr.csstransitions;

			this._initEvents();

		},
		_config : function() {
			this.open = false;
			this.$trigger = this.$el.find('.dl-trigger' );
			this.$menu = $('#' + this.$el.attr('data-dl-items')).children('ul.dl-menu');
			this.$menuitems = this.$menu.find('li:not(.dl-menu-ignore)');
			if (this.$el.find('ul.dl-submenu li.dl-back').length == 0) {
				this.$el.find('ul.dl-submenu').prepend('<li class="dl-back"><a href="#">back</a></li>');
			}
			this.$back = this.$menu.find('li.dl-back');
		},
		_initEvents : function() {

			var self = this;

			this.$trigger.on('click.dlmenu', function () {

				self.$menu = $('#' + $(this).attr('data-dl-item'));
				self.$menuitems = self.$menu.find('li:not(.dl-menu-ignore)');
				if (self.$el.find('ul.dl-submenu li.dl-back').length == 0) {
					self.$el.find('ul.dl-submenu').prepend('<li class="dl-back"><a href="#">back</a></li>');
				}
				self.$back = self.$menu.find('li.dl-back');

				if ($('.dl-menuopen').length != 0 && $('.dl-menuopen').attr('id') != self.$menu.attr('id')) {
					self._openMenu();
				}
				else if ($('.dl-menuopen').length == 0) {
					self._openMenu();
				}
				else {
					self._closeMenu();
				}
				return false;

			} );

			this.$menuitems.on( 'click.dlmenu', function( event ) {
				
				event.stopPropagation();

				var $item = $(this),
					$submenu = $item.children( 'ul.dl-submenu' );

				if( $submenu.length > 0 ) {

					var $flyin = $submenu.clone().css( 'opacity', 0 ).insertAfter( self.$menu ),
						onAnimationEndFn = function() {
							self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classout ).addClass( 'dl-subview' );
							$item.addClass( 'dl-subviewopen' ).parents( '.dl-subviewopen:first' ).removeClass( 'dl-subviewopen' ).addClass( 'dl-subview' );
							$flyin.remove();
						};

					setTimeout( function() {
						$flyin.addClass( self.options.animationClasses.classin );
						self.$menu.addClass( self.options.animationClasses.classout );
						if( self.supportAnimations ) {
							self.$menu.on( self.animEndEventName, onAnimationEndFn );
						}
						else {
							onAnimationEndFn.call();
						}

						self.options.onLevelClick( $item, $item.children( 'a:first' ).text() );
					} );

					return false;

				}
				else {
					self.options.onLinkClick( $item, event );
				}

			} );

			this.$back.on( 'click.dlmenu', function( event ) {
				
				var $this = $( this ),
					$submenu = $this.parents( 'ul.dl-submenu:first' ),
					$item = $submenu.parent(),

					$flyin = $submenu.clone().insertAfter( self.$menu );

				var onAnimationEndFn = function() {
					self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classin );
					$flyin.remove();
				};

				setTimeout( function() {
					$flyin.addClass( self.options.animationClasses.classout );
					self.$menu.addClass( self.options.animationClasses.classin );
					if( self.supportAnimations ) {
						self.$menu.on( self.animEndEventName, onAnimationEndFn );
					}
					else {
						onAnimationEndFn.call();
					}

					$item.removeClass( 'dl-subviewopen' );
					
					var $subview = $this.parents( '.dl-subview:first' );
					if( $subview.is( 'li' ) ) {
						$subview.addClass( 'dl-subviewopen' );
					}
					$subview.removeClass( 'dl-subview' );
				} );

				return false;

			} );
			
		},
		closeMenu : function() {
			if( this.open ) {
				this._closeMenu();
			}
		},
		_closeMenu: function (menu) {
			var self = this;

			if (!menu) {
				menu = self.$menu;
			}

			var	onTransitionEndFn = function() {
					menu.off( self.transEndEventName );
					self._resetMenu();
				};
			
			menu.removeClass( 'dl-menuopen' );
			menu.addClass( 'dl-menu-toggle' );
			$('.dl-trigger').removeClass( 'dl-active' );
			
			if( self.supportTransitions ) {
				menu.on( self.transEndEventName, onTransitionEndFn );
			}
			else {
				onTransitionEndFn.call();
			}

			self.open = false;
		},
		openMenu : function() {
			if( !this.open ) {
				this._openMenu();
			}
		},
		_openMenu : function() {
			var self = this;

			if ($('.dl-menuopen').length != 0 && $('.dl-menuopen').attr('id') != self.$menu.attr('id')) {
				self._closeMenu($('.dl-menuopen'));
			}

			// clicking somewhere else makes the menu close
			$body.off( 'touchstart click' ).on( 'click.dlmenu', function() {
				self._closeMenu();
			});



			this.$menu.addClass( 'dl-menuopen dl-menu-toggle' ).on( this.transEndEventName, function() {
				$( this ).removeClass( 'dl-menu-toggle' );
			} );
			this.$trigger.addClass( 'dl-active' );
			this.open = true;
		},
		// resets the menu to its original state (first level of options)
		_resetMenu : function() {
			this.$menu.removeClass( 'dl-subview' );
			this.$menuitems.removeClass( 'dl-subview dl-subviewopen' );
		}
	};

	var logError = function( message ) {
		if ( window.console ) {
			window.console.error( message );
		}
	};

	$.fn.dlmenu = function( options ) {
		if ( typeof options === 'string' ) {
			var args = Array.prototype.slice.call( arguments, 1 );
			this.each(function() {
				var instance = $.data( this, 'dlmenu' );
				if ( !instance ) {
					logError( "cannot call methods on dlmenu prior to initialization; " +
					"attempted to call method '" + options + "'" );
					return;
				}
				if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
					logError( "no such method '" + options + "' for dlmenu instance" );
					return;
				}
				instance[ options ].apply( instance, args );
			});
		} 
		else {
			this.each(function() {	
				var instance = $.data( this, 'dlmenu' );
				if ( instance ) {
					instance._init();
				}
				else {
					instance = $.data( this, 'dlmenu', new $.DLMenu( options, this ) );
				}
			});
		}
		return this;
	};

} )( jQuery, window );;
////////////////////
/// File has been customized for this site
////////////////////
(function ($) {
  'use strict';

  // Case insensitive search
  $.expr[':'].icontains = function (obj, index, meta) {
    return icontains($(obj).text(), meta[3]);
  };

  // Case and accent insensitive search
  $.expr[':'].aicontains = function (obj, index, meta) {
    return icontains($(obj).data('normalizedText') || $(obj).text(), meta[3]);
  };

  /**
   * Actual implementation of the case insensitive search.
   * @access private
   * @param {String} haystack
   * @param {String} needle
   * @returns {boolean}
   */
  function icontains(haystack, needle) {
    return haystack.toUpperCase().indexOf(needle.toUpperCase()) > -1;
  }

  /**
   * Remove all diatrics from the given text.
   * @access private
   * @param {String} text
   * @returns {String}
   */
  function normalizeToBase(text) {
    var rExps = [
      {re: /[\xC0-\xC6]/g, ch: "A"},
      {re: /[\xE0-\xE6]/g, ch: "a"},
      {re: /[\xC8-\xCB]/g, ch: "E"},
      {re: /[\xE8-\xEB]/g, ch: "e"},
      {re: /[\xCC-\xCF]/g, ch: "I"},
      {re: /[\xEC-\xEF]/g, ch: "i"},
      {re: /[\xD2-\xD6]/g, ch: "O"},
      {re: /[\xF2-\xF6]/g, ch: "o"},
      {re: /[\xD9-\xDC]/g, ch: "U"},
      {re: /[\xF9-\xFC]/g, ch: "u"},
      {re: /[\xC7-\xE7]/g, ch: "c"},
      {re: /[\xD1]/g, ch: "N"},
      {re: /[\xF1]/g, ch: "n"}
    ];
    $.each(rExps, function () {
      text = text.replace(this.re, this.ch);
    });
    return text;
  }


  function htmlEscape(html) {
    var escapeMap = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#x27;',
      '`': '&#x60;'
    };
    var source = '(?:' + Object.keys(escapeMap).join('|') + ')',
        testRegexp = new RegExp(source),
        replaceRegexp = new RegExp(source, 'g'),
        string = html == null ? '' : '' + html;
    return testRegexp.test(string) ? string.replace(replaceRegexp, function (match) {
      return escapeMap[match];
    }) : string;
  }

  var Selectpicker = function (element, options, e) {
    if (e) {
      e.stopPropagation();
      e.preventDefault();
    }

    this.$element = $(element);
    this.$newElement = null;
    this.$button = null;
    this.$menu = null;
    this.$lis = null;
    this.options = options;

    // If we have no title yet, try to pull it from the html title attribute (jQuery doesnt' pick it up as it's not a
    // data-attribute)
    if (this.options.title === null) {
      this.options.title = this.$element.attr('title');
    }

    //Expose public methods
    this.val = Selectpicker.prototype.val;
    this.render = Selectpicker.prototype.render;
    this.refresh = Selectpicker.prototype.refresh;
    this.setStyle = Selectpicker.prototype.setStyle;
    this.selectAll = Selectpicker.prototype.selectAll;
    this.deselectAll = Selectpicker.prototype.deselectAll;
    this.destroy = Selectpicker.prototype.remove;
    this.remove = Selectpicker.prototype.remove;
    this.show = Selectpicker.prototype.show;
    this.hide = Selectpicker.prototype.hide;

    this.init();
  };

  Selectpicker.VERSION = '1.6.3';

  // part of this is duplicated in i18n/defaults-en_US.js. Make sure to update both.
  Selectpicker.DEFAULTS = {
    noneSelectedText: 'Nothing selected',
    noneResultsText: 'No results match',
    countSelectedText: function (numSelected, numTotal) {
      return (numSelected == 1) ? "{0} item selected" : "{0} items selected";
    },
    maxOptionsText: function (numAll, numGroup) {
      var arr = [];

      arr[0] = (numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)';
      arr[1] = (numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)';

      return arr;
    },
    selectAllText: 'Select All',
    deselectAllText: 'Deselect All',
    multipleSeparator: ', ',
    style: 'btn-default',
    size: 'auto',
    title: null,
    selectedTextFormat: 'values',
    width: false,
    container: false,
    hideDisabled: false,
    showSubtext: false,
    showIcon: true,
    showContent: true,
    dropupAuto: true,
    header: false,
    liveSearch: false,
    actionsBox: false,
    iconBase: 'glyphicon',
    tickIcon: 'glyphicon-ok',
    maxOptions: false,
    mobile: false,
    selectOnTab: false,
    dropdownAlignRight: false,
    searchAccentInsensitive: false
  };

  Selectpicker.prototype = {

    constructor: Selectpicker,

    init: function () {
      var that = this,
          id = this.$element.attr('id');

      this.$element.hide();
      this.multiple = this.$element.prop('multiple');
      this.autofocus = this.$element.prop('autofocus');
      this.$newElement = this.createView();
      this.$element.after(this.$newElement);
      this.$menu = this.$newElement.find('> .dropdown-menu');
      this.$button = this.$newElement.find('> button');
      this.$searchbox = this.$newElement.find('input');

      if (this.options.dropdownAlignRight)
        this.$menu.addClass('dropdown-menu-right');

      if (typeof id !== 'undefined') {
        this.$button.attr('data-id', id);
        $('label[for="' + id + '"]').click(function (e) {
          e.preventDefault();
          that.$button.focus();
        });
      }

      this.checkDisabled();
      this.clickListener();
      if (this.options.liveSearch) this.liveSearchListener();
      this.render();
      this.liHeight();
      this.setStyle();
      this.setWidth();
      if (this.options.container) this.selectPosition();
      this.$menu.data('this', this);
      this.$newElement.data('this', this);
      if (this.options.mobile) this.mobile();
    },

    createDropdown: function () {
      // Options
      // If we are multiple, then add the show-tick class by default
      var multiple = this.multiple ? ' show-tick' : '',
          inputGroup = this.$element.parent().hasClass('input-group') ? ' input-group-btn' : '',
          autofocus = this.autofocus ? ' autofocus' : '',
          btnSize = this.$element.parents().hasClass('form-group-lg') ? ' btn-lg' : (this.$element.parents().hasClass('form-group-sm') ? ' btn-sm' : '');
      // Elements
      var header = this.options.header ? '<div class="popover-title"><button type="button" class="close" aria-hidden="true">&times;</button>' + this.options.header + '</div>' : '';
      var searchbox = this.options.liveSearch ? '<div class="bs-searchbox"><input type="text" class="input-block-level form-control" autocomplete="off" /></div>' : '';
      var actionsbox = this.options.actionsBox ? '<div class="bs-actionsbox">' +
      '<div class="btn-group btn-block">' +
      '<button class="actions-btn bs-select-all btn btn-sm btn-default">' +
      this.options.selectAllText +
      '</button>' +
      '<button class="actions-btn bs-deselect-all btn btn-sm btn-default">' +
      this.options.deselectAllText +
      '</button>' +
      '</div>' +
      '</div>' : '';
      var drop =
          '<div class="btn-group bootstrap-select' + multiple + inputGroup + '">' +
          '<button type="button" class="btn dropdown-toggle selectpicker' + btnSize + '" data-toggle="dropdown"' + autofocus + '>' +
          '<span class="filter-option pull-left"></span>&nbsp;' +
          '<span class="caret"></span>' +
          '</button>' +
          '<div class="dropdown-menu open">' +
          header +
          searchbox +
          actionsbox +
          '<ul class="dropdown-menu inner selectpicker" role="menu">' +
          '</ul>' +
          '</div>' +
          '</div>';

      return $(drop);
    },

    createView: function () {
      var $drop = this.createDropdown();
      var $li = this.createLi();
      $drop.find('ul').append($li);
      return $drop;
    },

    reloadLi: function () {
      //Remove all children.
      this.destroyLi();
      //Re build
      var $li = this.createLi();
      this.$menu.find('ul').append($li);
    },

    destroyLi: function () {
      this.$menu.find('li').remove();
    },

    createLi: function () {
      var that = this,
          _li = [],
          optID = 0;

      // Helper functions
      /**
       * @param content
       * @param [index]
       * @param [classes]
       * @returns {string}
       */
      var generateLI = function (content, index, classes) {
          return '<li role="menuitem"' +
        (typeof classes !== 'undefined' ? ' class="' + classes + '"' : '') +
        (typeof index !== 'undefined' | null === index ? ' data-original-index="' + index + '"' : '') +
        '>' + content + '</li>';
      };

      /**
       * @param text
       * @param [classes]
       * @param [inline]
       * @param [optgroup]
       * @returns {string}
       */
      var generateA = function (text, classes, inline, optgroup) {
        var normText = normalizeToBase(htmlEscape(text));
        return '<a tabindex="0"' +
        (typeof classes !== 'undefined' ? ' class="' + classes + '"' : '') +
        (typeof inline !== 'undefined' ? ' style="' + inline + '"' : '') +
        (typeof optgroup !== 'undefined' ? 'data-optgroup="' + optgroup + '"' : '') +
        ' data-normalized-text="' + normText + '"' +
        '>' + text +
        '<span class="' + that.options.iconBase + ' ' + that.options.tickIcon + ' check-mark"></span>' +
        '</a>';
      };

      this.$element.find('option').each(function () {
        var $this = $(this);

        // Get the class and text for the option
        var optionClass = $this.attr('class') || '',
            inline = $this.attr('style'),
            text = $this.data('content') ? $this.data('content') : $this.html(),
            subtext = typeof $this.data('subtext') !== 'undefined' ? '<small class="muted text-muted">' + $this.data('subtext') + '</small>' : '',
            icon = typeof $this.data('icon') !== 'undefined' ? '<span class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></span> ' : '',
            isDisabled = $this.is(':disabled') || $this.parent().is(':disabled'),
            index = $this[0].index;
        if (icon !== '' && isDisabled) {
          icon = '<span>' + icon + '</span>';
        }

        if (!$this.data('content')) {
          // Prepend any icon and append any subtext to the main text.
          text = icon + '<span class="text">' + text + subtext + '</span>';
        }

        if (that.options.hideDisabled && isDisabled) {
          return;
        }

        if ($this.parent().is('optgroup') && $this.data('divider') !== true) {
          if ($this.index() === 0) { // Is it the first option of the optgroup?
            optID += 1;

            // Get the opt group label
            var label = $this.parent().attr('label');
            var labelSubtext = typeof $this.parent().data('subtext') !== 'undefined' ? '<small class="muted text-muted">' + $this.parent().data('subtext') + '</small>' : '';
            var labelIcon = $this.parent().data('icon') ? '<span class="' + that.options.iconBase + ' ' + $this.parent().data('icon') + '"></span> ' : '';
            label = labelIcon + '<span class="text">' + label + labelSubtext + '</span>';

            if (index !== 0 && _li.length > 0) { // Is it NOT the first option of the select && are there elements in the dropdown?
              _li.push(generateLI('', null, 'divider'));
            }

            _li.push(generateLI(label, null, 'dropdown-header'));
          }

          _li.push(generateLI(generateA(text, 'opt ' + optionClass, inline, optID), index));
        } else if ($this.data('divider') === true) {
          _li.push(generateLI('', index, 'divider'));
        } else if ($this.data('hidden') === true) {
          _li.push(generateLI(generateA(text, optionClass, inline), index, 'hide is-hidden'));
        } else {
          _li.push(generateLI(generateA(text, optionClass, inline), index));
        }
      });

      //If we are not multiple, we don't have a selected item, and we don't have a title, select the first element so something is set in the button
      if (!this.multiple && this.$element.find('option:selected').length === 0 && !this.options.title) {
        this.$element.find('option').eq(0).prop('selected', true).attr('selected', 'selected');
      }

      return $(_li.join(''));
    },

    findLis: function () {
      if (this.$lis == null) this.$lis = this.$menu.find('li');
      return this.$lis;
    },

    /**
     * @param [updateLi] defaults to true
     */
    render: function (updateLi) {
      var that = this;

      //Update the LI to match the SELECT
      if (updateLi !== false) {
        this.$element.find('option').each(function (index) {
          that.setDisabled(index, $(this).is(':disabled') || $(this).parent().is(':disabled'));
          that.setSelected(index, $(this).is(':selected'));
        });
      }

      this.tabIndex();
      var notDisabled = this.options.hideDisabled ? ':not([disabled])' : '';
      var selectedItems = this.$element.find('option:selected' + notDisabled).map(function () {
        var $this = $(this);
        var icon = $this.data('icon') && that.options.showIcon ? '<i class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></i> ' : '';
        var subtext;
        if (that.options.showSubtext && $this.attr('data-subtext') && !that.multiple) {
          subtext = ' <small class="muted text-muted">' + $this.data('subtext') + '</small>';
        } else {
          subtext = '';
        }
        if ($this.data('content') && that.options.showContent) {
          return $this.data('content');
        } else if (typeof $this.attr('title') !== 'undefined') {
          return $this.attr('title');
        } else {
          return icon + $this.html() + subtext;
        }
      }).toArray();

      //Fixes issue in IE10 occurring when no default option is selected and at least one option is disabled
      //Convert all the values into a comma delimited string
      var title = !this.multiple ? selectedItems[0] : selectedItems.join(this.options.multipleSeparator);

      //If this is multi select, and the selectText type is count, the show 1 of 2 selected etc..
      if (this.multiple && this.options.selectedTextFormat.indexOf('count') > -1) {
        var max = this.options.selectedTextFormat.split('>');
        if ((max.length > 1 && selectedItems.length > max[1]) || (max.length == 1 && selectedItems.length >= 2)) {
          notDisabled = this.options.hideDisabled ? ', [disabled]' : '';
          var totalCount = this.$element.find('option').not('[data-divider="true"], [data-hidden="true"]' + notDisabled).length,
              tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedItems.length, totalCount) : this.options.countSelectedText;
          title = tr8nText.replace('{0}', selectedItems.length.toString()).replace('{1}', totalCount.toString());
        }
      }

      this.options.title = this.$element.attr('title');

      if (this.options.selectedTextFormat == 'static') {
        title = this.options.title;
      }

      //If we dont have a title, then use the default, or if nothing is set at all, use the not selected text
      if (!title) {
        title = typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText;
      }

      this.$button.attr('title', htmlEscape(title));
      this.$newElement.find('.filter-option').html(title);
    },

    /**
     * @param [style]
     * @param [status]
     */
    setStyle: function (style, status) {
      if (this.$element.attr('class')) {
        this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|validate\[.*\]/gi, ''));
      }

      var buttonClass = style ? style : this.options.style;

      if (status == 'add') {
        this.$button.addClass(buttonClass);
      } else if (status == 'remove') {
        this.$button.removeClass(buttonClass);
      } else {
        this.$button.removeClass(this.options.style);
        this.$button.addClass(buttonClass);
      }
    },

    liHeight: function () {
      if (this.options.size === false) return;

      var $selectClone = this.$menu.parent().clone().find('> .dropdown-toggle').prop('autofocus', false).end().appendTo('body'),
          $menuClone = $selectClone.addClass('open').find('> .dropdown-menu'),
          liHeight = $menuClone.find('li').not('.divider').not('.dropdown-header').filter(':visible').children('a').outerHeight(),
          headerHeight = this.options.header ? $menuClone.find('.popover-title').outerHeight() : 0,
          searchHeight = this.options.liveSearch ? $menuClone.find('.bs-searchbox').outerHeight() : 0,
          actionsHeight = this.options.actionsBox ? $menuClone.find('.bs-actionsbox').outerHeight() : 0;

      $selectClone.remove();

      this.$newElement
          .data('liHeight', liHeight)
          .data('headerHeight', headerHeight)
          .data('searchHeight', searchHeight)
          .data('actionsHeight', actionsHeight);
    },

    setSize: function () {
      this.findLis();
      var that = this,
          menu = this.$menu,
          menuInner = menu.find('.inner'),
          selectHeight = this.$newElement.outerHeight(),
          liHeight = this.$newElement.data('liHeight'),
          headerHeight = this.$newElement.data('headerHeight'),
          searchHeight = this.$newElement.data('searchHeight'),
          actionsHeight = this.$newElement.data('actionsHeight'),
          divHeight = this.$lis.filter('.divider').outerHeight(true),
          menuPadding = parseInt(menu.css('padding-top')) +
              parseInt(menu.css('padding-bottom')) +
              parseInt(menu.css('border-top-width')) +
              parseInt(menu.css('border-bottom-width')),
          notDisabled = this.options.hideDisabled ? ', .disabled' : '',
          $window = $(window),
          menuExtras = menuPadding + parseInt(menu.css('margin-top')) + parseInt(menu.css('margin-bottom')) + 2,
          menuHeight,
          selectOffsetTop,
          selectOffsetBot,
          posVert = function () {
            // JQuery defines a scrollTop function, but in pure JS it's a property
            //noinspection JSValidateTypes
            selectOffsetTop = that.$newElement.offset().top - $window.scrollTop();
            selectOffsetBot = $window.height() - selectOffsetTop - selectHeight;
          };
      posVert();
      if (this.options.header) menu.css('padding-top', 0);

      if (this.options.size == 'auto') {
        var getSize = function () {
          var minHeight,
              lisVis = that.$lis.not('.hide');

          posVert();
          menuHeight = selectOffsetBot - menuExtras;

          if (that.options.dropupAuto) {
            that.$newElement.toggleClass('dropup', (selectOffsetTop > selectOffsetBot) && ((menuHeight - menuExtras) < menu.height()));
          }
          if (that.$newElement.hasClass('dropup')) {
            menuHeight = selectOffsetTop - menuExtras;
          }

          if ((lisVis.length + lisVis.filter('.dropdown-header').length) > 3) {
            minHeight = liHeight * 3 + menuExtras - 2;
          } else {
            minHeight = 0;
          }

          menu.css({
            'max-height': menuHeight + 'px',
            'overflow': 'hidden',
            'min-height': minHeight + headerHeight + searchHeight + actionsHeight + 'px'
          });
          menuInner.css({
            'max-height': menuHeight - headerHeight - searchHeight - actionsHeight - menuPadding + 'px',
            'overflow-y': 'auto',
            'min-height': Math.max(minHeight - menuPadding, 0) + 'px'
          });
        };
        getSize();
        this.$searchbox.off('input.getSize propertychange.getSize').on('input.getSize propertychange.getSize', getSize);
        $(window).off('resize.getSize').on('resize.getSize', getSize);
        $(window).off('scroll.getSize').on('scroll.getSize', getSize);
      } else if (this.options.size && this.options.size != 'auto' && menu.find('li' + notDisabled).length > this.options.size) {
        var optIndex = this.$lis.not('.divider' + notDisabled).find(' > *').slice(0, this.options.size).last().parent().index();
        var divLength = this.$lis.slice(0, optIndex + 1).filter('.divider').length;
        menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding;
        if (that.options.dropupAuto) {
          //noinspection JSUnusedAssignment
          this.$newElement.toggleClass('dropup', (selectOffsetTop > selectOffsetBot) && (menuHeight < menu.height()));
        }
        menu.css({'max-height': menuHeight + headerHeight + searchHeight + actionsHeight + 'px', 'overflow': 'hidden'});
        menuInner.css({'max-height': menuHeight - menuPadding + 'px', 'overflow-y': 'auto'});
      }
    },

    setWidth: function () {
      if (this.options.width == 'auto') {
        this.$menu.css('min-width', '0');

        // Get correct width if element hidden
        var selectClone = this.$newElement.clone().appendTo('body');
        var ulWidth = selectClone.find('> .dropdown-menu').css('width');
        var btnWidth = selectClone.css('width', 'auto').find('> button').css('width');
        selectClone.remove();

        // Set width to whatever's larger, button title or longest option
        this.$newElement.css('width', Math.max(parseInt(ulWidth), parseInt(btnWidth)) + 'px');
      } else if (this.options.width == 'fit') {
        // Remove inline min-width so width can be changed from 'auto'
        this.$menu.css('min-width', '');
        this.$newElement.css('width', '').addClass('fit-width');
      } else if (this.options.width) {
        // Remove inline min-width so width can be changed from 'auto'
        this.$menu.css('min-width', '');
        this.$newElement.css('width', this.options.width);
      } else {
        // Remove inline min-width/width so width can be changed
        this.$menu.css('min-width', '');
        this.$newElement.css('width', '');
      }
      // Remove fit-width class if width is changed programmatically
      if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
        this.$newElement.removeClass('fit-width');
      }
    },

    selectPosition: function () {
      var that = this,
          drop = '<div />',
          $drop = $(drop),
          pos,
          actualHeight,
          getPlacement = function ($element) {
            $drop.addClass($element.attr('class').replace(/form-control/gi, '')).toggleClass('dropup', $element.hasClass('dropup'));
            pos = $element.offset();
            actualHeight = $element.hasClass('dropup') ? 0 : $element[0].offsetHeight;
            $drop.css({
              'top': pos.top + actualHeight,
              'left': pos.left,
              'width': $element[0].offsetWidth,
              'position': 'absolute'
            });
          };
      this.$newElement.on('click', function () {
        if (that.isDisabled()) {
          return;
        }
        getPlacement($(this));
        $drop.appendTo(that.options.container);
        $drop.toggleClass('open', !$(this).hasClass('open'));
        $drop.append(that.$menu);
      });
      $(window).resize(function () {
        getPlacement(that.$newElement);
      });
      $(window).on('scroll', function () {
        getPlacement(that.$newElement);
      });
      $('html').on('click', function (e) {
        if ($(e.target).closest(that.$newElement).length < 1) {
          $drop.removeClass('open');
        }
      });
    },

    setSelected: function (index, selected) {
      this.findLis();
      this.$lis.filter('[data-original-index="' + index + '"]').toggleClass('selected', selected);
    },

    setDisabled: function (index, disabled) {
      this.findLis();
      if (disabled) {
        this.$lis.filter('[data-original-index="' + index + '"]').addClass('disabled').find('a').attr('href', '#').attr('tabindex', -1);
      } else {
        this.$lis.filter('[data-original-index="' + index + '"]').removeClass('disabled').find('a').removeAttr('href').attr('tabindex', 0);
      }
    },

    isDisabled: function () {
      return this.$element.is(':disabled');
    },

    checkDisabled: function () {
      var that = this;

      if (this.isDisabled()) {
        this.$button.addClass('disabled').attr('tabindex', -1);
      } else {
        if (this.$button.hasClass('disabled')) {
          this.$button.removeClass('disabled');
        }

        if (this.$button.attr('tabindex') == -1) {
          if (!this.$element.data('tabindex')) this.$button.removeAttr('tabindex');
        }
      }

      this.$button.click(function () {
        return !that.isDisabled();
      });
    },

    tabIndex: function () {
      if (this.$element.is('[tabindex]')) {
        this.$element.data('tabindex', this.$element.attr('tabindex'));
        this.$button.attr('tabindex', this.$element.data('tabindex'));
      }
    },

    clickListener: function () {
      var that = this;

      this.$newElement.on('touchstart.dropdown', '.dropdown-menu', function (e) {
        e.stopPropagation();
      });

      this.$newElement.on('click', function () {
        that.setSize();
        if (!that.options.liveSearch && !that.multiple) {
          setTimeout(function () {
            that.$menu.find('.selected a').focus();
          }, 10);
        }
      });

      this.$menu.on('click', 'li a', function (e) {
        var $this = $(this),
            clickedIndex = $this.parent().data('originalIndex'),
            prevValue = that.$element.val(),
            prevIndex = that.$element.prop('selectedIndex');

        // Don't close on multi choice menu
        if (that.multiple) {
          e.stopPropagation();
        }

        e.preventDefault();

        //Don't run if we have been disabled
        if (!that.isDisabled() && !$this.parent().hasClass('disabled')) {
          var $options = that.$element.find('option'),
              $option = $options.eq(clickedIndex),
              state = $option.prop('selected'),
              $optgroup = $option.parent('optgroup'),
              maxOptions = that.options.maxOptions,
              maxOptionsGrp = $optgroup.data('maxOptions') || false;

          if (!that.multiple) { // Deselect all others if not multi select box
            $options.prop('selected', false);
            $option.prop('selected', true);
            that.$menu.find('.selected').removeClass('selected');
            that.setSelected(clickedIndex, true);
          } else { // Toggle the one we have chosen if we are multi select.
            $option.prop('selected', !state);
            that.setSelected(clickedIndex, !state);
            $this.blur();

            if ((maxOptions !== false) || (maxOptionsGrp !== false)) {
              var maxReached = maxOptions < $options.filter(':selected').length,
                  maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length;

              if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) {
                if (maxOptions && maxOptions == 1) {
                  $options.prop('selected', false);
                  $option.prop('selected', true);
                  that.$menu.find('.selected').removeClass('selected');
                  that.setSelected(clickedIndex, true);
                } else if (maxOptionsGrp && maxOptionsGrp == 1) {
                  $optgroup.find('option:selected').prop('selected', false);
                  $option.prop('selected', true);
                  var optgroupID = $this.data('optgroup');

                  that.$menu.find('.selected').has('a[data-optgroup="' + optgroupID + '"]').removeClass('selected');

                  that.setSelected(clickedIndex, true);
                } else {
                  var maxOptionsArr = (typeof that.options.maxOptionsText === 'function') ?
                          that.options.maxOptionsText(maxOptions, maxOptionsGrp) : that.options.maxOptionsText,
                      maxTxt = maxOptionsArr[0].replace('{n}', maxOptions),
                      maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp),
                      $notify = $('<div class="notify"></div>');
                  // If {var} is set in array, replace it
                  /** @deprecated */
                  if (maxOptionsArr[2]) {
                    maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]);
                    maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]);
                  }

                  $option.prop('selected', false);

                  that.$menu.append($notify);

                  if (maxOptions && maxReached) {
                    $notify.append($('<div>' + maxTxt + '</div>'));
                    that.$element.trigger('maxReached.bs.select');
                  }

                  if (maxOptionsGrp && maxReachedGrp) {
                    $notify.append($('<div>' + maxTxtGrp + '</div>'));
                    that.$element.trigger('maxReachedGrp.bs.select');
                  }

                  setTimeout(function () {
                    that.setSelected(clickedIndex, false);
                  }, 10);

                  $notify.delay(750).fadeOut(300, function () {
                    $(this).remove();
                  });
                }
              }
            }
          }

          if (!that.multiple) {
            that.$button.focus();
          } else if (that.options.liveSearch) {
            that.$searchbox.focus();
          }

          // Trigger select 'change'
          if ((prevValue != that.$element.val() && that.multiple) || (prevIndex != that.$element.prop('selectedIndex') && !that.multiple)) {
            that.$element.change();
          }
        }
      });

      this.$menu.on('click', 'li.disabled a, .popover-title, .popover-title :not(.close)', function (e) {
        if (e.target == this) {
          e.preventDefault();
          e.stopPropagation();
          if (!that.options.liveSearch) {
            that.$button.focus();
          } else {
            that.$searchbox.focus();
          }
        }
      });

      this.$menu.on('click', 'li.divider, li.dropdown-header', function (e) {
        e.preventDefault();
        e.stopPropagation();
        if (!that.options.liveSearch) {
          that.$button.focus();
        } else {
          that.$searchbox.focus();
        }
      });

      this.$menu.on('click', '.popover-title .close', function () {
        that.$button.focus();
      });

      this.$searchbox.on('click', function (e) {
        e.stopPropagation();
      });


      this.$menu.on('click', '.actions-btn', function (e) {
        if (that.options.liveSearch) {
          that.$searchbox.focus();
        } else {
          that.$button.focus();
        }

        e.preventDefault();
        e.stopPropagation();

        if ($(this).is('.bs-select-all')) {
          that.selectAll();
        } else {
          that.deselectAll();
        }
        that.$element.change();
      });

      this.$element.change(function () {
        that.render(false);
      });
    },

    liveSearchListener: function () {
      var that = this,
          no_results = $('<li class="no-results"></li>');

      this.$newElement.on('click.dropdown.data-api touchstart.dropdown.data-api', function () {
        that.$menu.find('.active').removeClass('active');
        if (!!that.$searchbox.val()) {
          that.$searchbox.val('');
          that.$lis.not('.is-hidden').removeClass('hide');
          if (!!no_results.parent().length) no_results.remove();
        }
        if (!that.multiple) that.$menu.find('.selected').addClass('active');
        setTimeout(function () {
          that.$searchbox.focus();
        }, 10);
      });

      this.$searchbox.on('click.dropdown.data-api focus.dropdown.data-api touchend.dropdown.data-api', function (e) {
        e.stopPropagation();
      });

      this.$searchbox.on('input propertychange', function () {
        if (that.$searchbox.val()) {

          if (that.options.searchAccentInsensitive) {
            that.$lis.not('.is-hidden').removeClass('hide').find('a').not(':aicontains(' + normalizeToBase(that.$searchbox.val()) + ')').parent().addClass('hide');
          } else {
            that.$lis.not('.is-hidden').removeClass('hide').find('a').not(':icontains(' + that.$searchbox.val() + ')').parent().addClass('hide');
          }

          if (!that.$menu.find('li').filter(':visible:not(.no-results)').length) {
            if (!!no_results.parent().length) no_results.remove();
            no_results.html(that.options.noneResultsText + ' "' + htmlEscape(that.$searchbox.val()) + '"').show();
            that.$menu.find('li').last().after(no_results);
          } else if (!!no_results.parent().length) {
            no_results.remove();
          }

        } else {
          that.$lis.not('.is-hidden').removeClass('hide');
          if (!!no_results.parent().length) no_results.remove();
        }

        that.$menu.find('li.active').removeClass('active');
        that.$menu.find('li').filter(':visible:not(.divider)').eq(0).addClass('active').find('a').focus();
        $(this).focus();
      });
    },

    val: function (value) {
      if (typeof value !== 'undefined') {
        this.$element.val(value);
        this.render();

        return this.$element;
      } else {
        return this.$element.val();
      }
    },

    selectAll: function () {
      this.findLis();
      this.$lis.not('.divider').not('.disabled').not('.selected').filter(':visible').find('a').click();
    },

    deselectAll: function () {
      this.findLis();
      this.$lis.not('.divider').not('.disabled').filter('.selected').filter(':visible').find('a').click();
    },

    keydown: function (e) {
      var $this = $(this),
          $parent = ($this.is('input')) ? $this.parent().parent() : $this.parent(),
          $items,
          that = $parent.data('this'),
          index,
          next,
          first,
          last,
          prev,
          nextPrev,
          prevIndex,
          isActive,
          keyCodeMap = {
            32: ' ',
            48: '0',
            49: '1',
            50: '2',
            51: '3',
            52: '4',
            53: '5',
            54: '6',
            55: '7',
            56: '8',
            57: '9',
            59: ';',
            65: 'a',
            66: 'b',
            67: 'c',
            68: 'd',
            69: 'e',
            70: 'f',
            71: 'g',
            72: 'h',
            73: 'i',
            74: 'j',
            75: 'k',
            76: 'l',
            77: 'm',
            78: 'n',
            79: 'o',
            80: 'p',
            81: 'q',
            82: 'r',
            83: 's',
            84: 't',
            85: 'u',
            86: 'v',
            87: 'w',
            88: 'x',
            89: 'y',
            90: 'z',
            96: '0',
            97: '1',
            98: '2',
            99: '3',
            100: '4',
            101: '5',
            102: '6',
            103: '7',
            104: '8',
            105: '9'
          };

      if (that.options.liveSearch) $parent = $this.parent().parent();

      if (that.options.container) $parent = that.$menu;

      $items = $('[role=menu] li a', $parent);

      isActive = that.$menu.parent().hasClass('open');

      if (!isActive && /([0-9]|[A-z])/.test(String.fromCharCode(e.keyCode))) {
        if (!that.options.container) {
          that.setSize();
          that.$menu.parent().addClass('open');
          isActive = true;
        } else {
          that.$newElement.trigger('click');
        }
        that.$searchbox.focus();
      }

      if (that.options.liveSearch) {
        if (/(^9$|27)/.test(e.keyCode.toString(10)) && isActive && that.$menu.find('.active').length === 0) {
          e.preventDefault();
          that.$menu.parent().removeClass('open');
          that.$button.focus();
        }
        $items = $('[role=menu] li:not(.divider):not(.dropdown-header):visible', $parent);
        if (!$this.val() && !/(38|40)/.test(e.keyCode.toString(10))) {
          if ($items.filter('.active').length === 0) {
            if (that.options.searchAccentInsensitive) {
              $items = that.$newElement.find('li').filter(':aicontains(' + normalizeToBase(keyCodeMap[e.keyCode]) + ')');
            } else {
              $items = that.$newElement.find('li').filter(':icontains(' + keyCodeMap[e.keyCode] + ')');
            }
          }
        }
      }

      if (!$items.length) return;

      if (/(38|40)/.test(e.keyCode.toString(10))) {
        index = $items.index($items.filter(':focus'));
        first = $items.parent(':not(.disabled):visible').first().index();
        last = $items.parent(':not(.disabled):visible').last().index();
        next = $items.eq(index).parent().nextAll(':not(.disabled):visible').eq(0).index();
        prev = $items.eq(index).parent().prevAll(':not(.disabled):visible').eq(0).index();
        nextPrev = $items.eq(next).parent().prevAll(':not(.disabled):visible').eq(0).index();

        if (that.options.liveSearch) {
          $items.each(function (i) {
            if ($(this).is(':not(.disabled)')) {
              $(this).data('index', i);
            }
          });
          index = $items.index($items.filter('.active'));
          first = $items.filter(':not(.disabled):visible').first().data('index');
          last = $items.filter(':not(.disabled):visible').last().data('index');
          next = $items.eq(index).nextAll(':not(.disabled):visible').eq(0).data('index');
          prev = $items.eq(index).prevAll(':not(.disabled):visible').eq(0).data('index');
          nextPrev = $items.eq(next).prevAll(':not(.disabled):visible').eq(0).data('index');
        }

        prevIndex = $this.data('prevIndex');

        if (e.keyCode == 38) {
          if (that.options.liveSearch) index -= 1;
          if (index != nextPrev && index > prev) index = prev;
          if (index < first) index = first;
          if (index == prevIndex) index = last;
        }

        if (e.keyCode == 40) {
          if (that.options.liveSearch) index += 1;
          if (index == -1) index = 0;
          if (index != nextPrev && index < next) index = next;
          if (index > last) index = last;
          if (index == prevIndex) index = first;
        }

        $this.data('prevIndex', index);

        if (!that.options.liveSearch) {
          $items.eq(index).focus();
        } else {
          e.preventDefault();
          if (!$this.is('.dropdown-toggle')) {
            $items.removeClass('active');
            $items.eq(index).addClass('active').find('a').focus();
            $this.focus();
          }
        }

      } else if (!$this.is('input')) {
        var keyIndex = [],
            count,
            prevKey;

        $items.each(function () {
          if ($(this).parent().is(':not(.disabled)')) {
            if ($.trim($(this).text().toLowerCase()).substring(0, 1) == keyCodeMap[e.keyCode]) {
              keyIndex.push($(this).parent().index());
            }
          }
        });

        count = $(document).data('keycount');
        count++;
        $(document).data('keycount', count);

        prevKey = $.trim($(':focus').text().toLowerCase()).substring(0, 1);

        if (prevKey != keyCodeMap[e.keyCode]) {
          count = 1;
          $(document).data('keycount', count);
        } else if (count >= keyIndex.length) {
          $(document).data('keycount', 0);
          if (count > keyIndex.length) count = 1;
        }

        $items.eq(keyIndex[count - 1]).focus();
      }

      // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu.
      if ((/(13|32)/.test(e.keyCode.toString(10)) || (/(^9$)/.test(e.keyCode.toString(10)) && that.options.selectOnTab)) && isActive) {
        if (!/(32)/.test(e.keyCode.toString(10))) e.preventDefault();
        if (!that.options.liveSearch) {
          $(':focus').click();
        } else if (!/(32)/.test(e.keyCode.toString(10))) {
          that.$menu.find('.active a').click();
          $this.focus();
        }
        $(document).data('keycount', 0);
      }

      if ((/(^9$|27)/.test(e.keyCode.toString(10)) && isActive && (that.multiple || that.options.liveSearch)) || (/(27)/.test(e.keyCode.toString(10)) && !isActive)) {
        that.$menu.parent().removeClass('open');
        that.$button.focus();
      }
    },

    mobile: function () {
      this.$element.addClass('mobile-device').appendTo(this.$newElement);
      if (this.options.container) this.$menu.hide();
    },

    refresh: function () {
      this.$lis = null;
      this.reloadLi();
      this.render();
      this.setWidth();
      this.setStyle();
      this.checkDisabled();
      this.liHeight();
    },

    update: function () {
      this.reloadLi();
      this.setWidth();
      this.setStyle();
      this.checkDisabled();
      this.liHeight();
    },

    hide: function () {
      this.$newElement.hide();
    },

    show: function () {
      this.$newElement.show();
    },

    remove: function () {
      this.$newElement.remove();
      this.$element.remove();
    }
  };

  // SELECTPICKER PLUGIN DEFINITION
  // ==============================
  function Plugin(option, event) {
    // get the args of the outer function..
    var args = arguments;
    // The arguments of the function are explicitly re-defined from the argument list, because the shift causes them
    // to get lost
    //noinspection JSDuplicatedDeclaration
    var _option = option,
        option = args[0],
        event = args[1];
    [].shift.apply(args);

    // This fixes a bug in the js implementation on android 2.3 #715
    if (typeof option == 'undefined') {
      option = _option;
    }

    var value;
    var chain = this.each(function () {
      var $this = $(this);
      if ($this.is('select')) {
        var data = $this.data('selectpicker'),
            options = typeof option == 'object' && option;

        if (!data) {
          var config = $.extend({}, Selectpicker.DEFAULTS, $.fn.selectpicker.defaults || {}, $this.data(), options);
          $this.data('selectpicker', (data = new Selectpicker(this, config, event)));
        } else if (options) {
          for (var i in options) {
            if (options.hasOwnProperty(i)) {
              data.options[i] = options[i];
            }
          }
        }

        if (typeof option == 'string') {
          if (data[option] instanceof Function) {
            value = data[option].apply(data, args);
          } else {
            value = data.options[option];
          }
        }
      }
    });

    if (typeof value !== 'undefined') {
      //noinspection JSUnusedAssignment
      return value;
    } else {
      return chain;
    }
  }

  var old = $.fn.selectpicker;
  $.fn.selectpicker = Plugin;
  $.fn.selectpicker.Constructor = Selectpicker;

  // SELECTPICKER NO CONFLICT
  // ========================
  $.fn.selectpicker.noConflict = function () {
    $.fn.selectpicker = old;
    return this;
  };

  $(document)
      .data('keycount', 0)
      .on('keydown', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role=menu], .bs-searchbox input', Selectpicker.prototype.keydown)
      .on('focusin.modal', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role=menu], .bs-searchbox input', function (e) {
        e.stopPropagation();
      });

  // SELECTPICKER DATA-API
  // =====================
  $(window).on('load.bs.select.data-api', function () {
    $('.selectpicker').each(function () {
      var $selectpicker = $(this);
      Plugin.call($selectpicker, $selectpicker.data());
    })
  });
})(jQuery);
;
/*!
 * JavaScript Cookie v2.0.3
 * https://github.com/js-cookie/js-cookie
 *
 * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
 * Released under the MIT license
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        var _OldCookies = window.Cookies;
        var api = window.Cookies = factory();
        api.noConflict = function () {
            window.Cookies = _OldCookies;
            return api;
        };
    }
}(function () {
    function extend() {
        var i = 0;
        var result = {};
        for (; i < arguments.length; i++) {
            var attributes = arguments[i];
            for (var key in attributes) {
                result[key] = attributes[key];
            }
        }
        return result;
    }

    function init(converter) {
        function api(key, value, attributes) {
            var result;

            // Write

            if (arguments.length > 1) {
                attributes = extend({
                    path: '/'
                }, api.defaults, attributes);

                if (typeof attributes.expires === 'number') {
                    var expires = new Date();
                    expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);
                    attributes.expires = expires;
                }

                try {
                    result = JSON.stringify(value);
                    if (/^[\{\[]/.test(result)) {
                        value = result;
                    }
                } catch (e) { }

                value = encodeURIComponent(String(value));
                value = value.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);

                key = encodeURIComponent(String(key));
                key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent);
                key = key.replace(/[\(\)]/g, escape);

                return (document.cookie = [
					key, '=', value,
					attributes.expires && '; expires=' + attributes.expires.toUTCString(), // use expires attribute, max-age is not supported by IE
					attributes.path && '; path=' + attributes.path,
					attributes.domain && '; domain=' + attributes.domain,
					attributes.secure ? '; secure' : ''
                ].join(''));
            }

            // Read

            if (!key) {
                result = {};
            }

            // To prevent the for loop in the first place assign an empty array
            // in case there are no cookies at all. Also prevents odd result when
            // calling "get()"
            var cookies = document.cookie ? document.cookie.split('; ') : [];
            var rdecode = /(%[0-9A-Z]{2})+/g;
            var i = 0;

            for (; i < cookies.length; i++) {
                var parts = cookies[i].split('=');
                var name = parts[0].replace(rdecode, decodeURIComponent);
                var cookie = parts.slice(1).join('=');

                if (cookie.charAt(0) === '"') {
                    cookie = cookie.slice(1, -1);
                }

                try {
                    cookie = converter && converter(cookie, name) || cookie.replace(rdecode, decodeURIComponent);

                    if (this.json) {
                        try {
                            cookie = JSON.parse(cookie);
                        } catch (e) { }
                    }

                    if (key === name) {
                        result = cookie;
                        break;
                    }

                    if (!key) {
                        result[name] = cookie;
                    }
                } catch (e) { }
            }

            return result;
        }

        api.get = api.set = api;
        api.getJSON = function () {
            return api.apply({
                json: true
            }, [].slice.call(arguments));
        };
        api.defaults = {};

        api.remove = function (key, attributes) {
            api(key, '', extend(attributes, {
                expires: -1
            }));
        };

        api.withConverter = init;

        return api;
    }

    return init();
}));;
/* Get and set GA UTM */

//Event Tracking
function trackEvent(args) {
  if (typeof _gaq !== "undefined" && _gaq != null) {
    _gaq.push(args);
  }
}

function trackPageview(type, page) {
  if (typeof _gaq !== "undefined" && _gaq != null) {
    //console.log([type, page].join(", "));
    _gaq.push([type, page]);
  }
}

var queryStringToJSON = function (url) {
  if (url === "") return "";
  var pairs = (url || location.search).slice(1).split("&");
  var result = {};
  for (var idx in pairs) {
    try {
      var pair = pairs[idx].split("=");
      if (!!pair[0])
        result[pair[0].toLowerCase()] = decodeURIComponent(pair[1] || "");
    } catch (err) {
      continue;
    }
  }
  return result;
};

$(function () {
  $("#dl-menu").dlmenu();

  //redraw navigation on IE to eleminate whitespace left over by wider original font.
  //* might be caused by google fonts not supporting IE
  var ua = window.navigator.userAgent;
  var msie = ua.indexOf("MSIE ");

  if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
    // If Internet Explorer, return version number
    $("#navbar a").focus();
  }
});

$(function () {
  //grab the query string parameters
  var queryParams = queryStringToJSON();

  if (typeof Cookies != "undefined") {
    //grab the cookie string parameters
    var cookieParams = Cookies.getJSON("utm");
    if (cookieParams == null || typeof cookieParams === "undefined") {
      cookieParams = {};
    }

    //if the utm paramters are there save them to a cookie
    var utm = {
      landing:
        cookieParams.landing ||
        location.protocol + "//" + location.host + location.pathname,
      Source:
        queryParams.source || queryParams.utm_source || cookieParams.Source,
      Medium:
        queryParams.medium || queryParams.utm_medium || cookieParams.Medium,
      Campaign:
        queryParams.campaignid ||
        queryParams.utm_campaign ||
        cookieParams.Campaign,
      AdGroup:
        queryParams.adgroupid ||
        queryParams.utm_content ||
        cookieParams.AdGroup,
      Ad: queryParams.utm_ad || cookieParams.Ad,
      Keyword:
        queryParams.keyword || queryParams.utm_term || cookieParams.Keyword,
      Matchtype: queryParams.matchtype || cookieParams.Matchtype,
      Device:
        queryParams.device || queryParams.utm_device || cookieParams.Device,
      CreativeID: queryParams.creative || cookieParams.CreativeID,
      Placement: queryParams.placement || cookieParams.Placement,
    };

    //make sure the cookie has the values no matter what
    Cookies.set("utm", utm);
  }
});
/* End Get and set GA UTM */

$(function () {
  $("a").each(function () {
    var anchorEl = $(this).attr("href");

    if (anchorEl && anchorEl.indexOf("#") == 0) {
      $(anchorEl).addClass("anchor");
    }
  });

  $(document).on("change", "#mobile-related-sites", function () {
    if ($("#mobile-related-sites").val() != "default") {
      var new_val = $("#mobile-related-sites").find("option:selected").val();
      window.open(new_val, "_blank");
    }
  });

  $(window).scroll(function () {
    if ($(this).scrollTop() > 32) {
      $("#main-header").addClass("fixed");
    } else {
      $("#main-header").removeClass("fixed");
    }
  });

  // SITE BAR
  $(".site-trigger").on("click", function (e) {
    $(".site-bar").toggleClass("active");
    e.preventDefault();
  });

  $(".close-site").on("click", function (e) {
    $(".site-bar").removeClass("active");
    e.preventDefault();
  });

  $(".navbar .nav-dropdown").on("mouseleave", function (e) {
    $(".nav-dropdown").hide();
    $(".navbar .trigger-dd").removeClass("active");
  });

  $(".navbar .trigger-dd").on("mouseleave", function (e) {
    if ($(this).hasClass("active")) {
      $(".nav-dropdown").hide();
      $(this).removeClass("active");
    }
  });

  $(".navbar .trigger-dd:not(.active)").on("mouseenter", function (e) {
    var elem = $(this);

    $(".navbar .trigger-dd").removeClass("active");

    elem.addClass("active");
    var toShow = elem.attr("data-id");
    $(".nav-dropdown .sub-dd").hide();

    $(".nav-dropdown").show();
    
    $(".navbar .subnav-dd." + toShow).show();

    //$(".nav-dropdown ." + toShow).show();
    $(".nav-dropdown > ." + toShow).css('display','flex');
    //}
  });

  $(window).scroll();

  $(".LoginForm").each(function () {
    $(this).validate({
      rules: {
        Account_Email: {
          required: true,
          email: true,
        },
        Account_Password: "required",
      },
      messages: {
        Account_Email: "Not a valid email address.",
        Account_Password: "Please enter a password.",
      },
      //submitHandler: function (form) {
      //	$(form).find(".loader").show();
      //	Login(form);
      //	return false;
      //},
      invalidHandler: function () {
        //$("#LoginForm").find(".text-danger").text("");
        //$("#LoginForm").find(".post-message.text-danger").text("");
      },
      errorClass: "text-danger",
    });
  });

  $(document).on("click", ".show-registerlogin", function (e) {
    e.preventDefault();

    if (window.innerWidth < 768) {
      var returnUrl = sessionStorage.getItem("returnUrl");
      if (returnUrl) {
        sessionStorage.removeItem("returnUrl");
        window.location = "/registration/?returnURL=" + returnUrl;
      } else {
        window.location =
          "/registration/?returnURL=" + location.pathname + location.hash;
      }
    } else {
      ShowLoginPopup($(this).hasClass("login")); //show login or register section
    }
  });

  //Register <--> LogIn
  $(".register-login-forms .switch-to-login").click(function () {
    if (window.location.pathname.indexOf("registration") == -1) {
      var callerId = $(this).closest(".register-login-forms").attr("id");
      var speed = callerId == "register-login-page" ? null : "fast";
      switchToLogin(speed);
    }
  });

  $(".register-login-forms .switch-to-register").click(function () {
    var callerId = $(this).closest(".register-login-forms").attr("id");
    var speed = callerId == "register-login-page" ? null : "fast";
    switchToRegister(speed);
  });

  //clear errors on close
  $("#registerlogin-form").on("hidden.bs.modal", function () {
    $(this).find(".text-danger").text("");
  });

  $(".register-login-forms .registerlogin-register .submit").click(function () {
    $(this).closest(".form-group").find(".loader").show(); //todo: replace with ladda?
    window.location =
      "/registration/" +
      "?returnUrl=" +
      window.location.pathname +
      "&referrer=modal";
  });

  //mobile search controls
  $(".search-field-button").click(function () {
    window.location.href = "/sitesearch/?q=" + $("#mobile-global-search").val();
  });

  $("#mobile-global-search").keyup(function () {
    if ($(this).val() == "") {
      $("#mobile-search-cancel").hide();
      $("#mobile-search-mag").show();
    } else {
      $("#mobile-search-mag").hide();
      $("#mobile-search-cancel").show();
    }
  });

  $("#mobile-search-cancel").click(function () {
    $("#mobile-global-search").val("");
    $("#mobile-global-search").trigger("keyup");
  });

  // Login button
  $(".login-button").click(function () {
    $this = $(this);
    ClearSessionCookie();
    $this.SubmitLogin();
  });

  $(".LoginForm").keypress(function (e) {
    if (e.which == 13) {
      $this = $(this);
      $this.SubmitLogin();
    }
  });

  //Notification Bar
    $("#notification-bar").on("touchstart", function () {
        var extend = $(this).find('.has-extended-copy');
        if (extend.length > 0) {
            var windowWidth = $(window).width();
            if (windowWidth < 992) {
                $("#collapseOne").collapse("toggle");
                $("#notification-bar").toggleClass("expanded");
            }
        } 
  });

  $("#notification-bar a").on("touchstart", function (e) {
    e.stopPropagation();
  });

  $(document).click(function (event) {
    var windowWidth = $(window).width();
    if (windowWidth >= 992) {
      var clickover = $(event.target);
      var _opened = $("#notification-bar .panel-collapse").hasClass("in");
      if (_opened === true && clickover.attr("data-toggle") != "collapse") {
        $("#notification-bar a[data-toggle='collapse']").click();
      }
    }
  });

  //End Notification Bar

  //Toggle lock on passwords
  $(document).on("click touchend", ".toggle-password", function (e) {
    e.preventDefault();
    var $this = $(this);

    var target = $this.siblings("input");
    //Reset password page special case
    if (
      location.pathname.toLocaleLowerCase().includes("reset-password") ||
      location.pathname.toLocaleLowerCase().includes("account-settings")
    ) {
      if ($(target).attr("type") == "password") {
        target = $this.closest("form").find("input[type=password]");
      } else {
        target = $this.closest("form").find("input[type=text]");
      }
    }

    //Password -> Text
    var feedbackElem = target.siblings(".form-control-feedback");
    if ($(target).attr("type") == "password") {
      $(target).attr("type", "text");
      feedbackElem
        .find(".fa-lock")
        .addClass("fa-unlock-alt")
        .removeClass("fa-lock");
      feedbackElem.find(".text").text("hide");
    } else {
      // Text -> Password
      $(target).attr("type", "password");
      feedbackElem
        .find(".fa-unlock-alt")
        .addClass("fa-lock")
        .removeClass("fa-unlock-alt");
      feedbackElem.find(".text").text("show");
    }
  });

  //Video trigger
  $("[data-role=video], .video-wrapper").click(function (e) {
    e.preventDefault();
    var vidSrc = $(this).attr("data-url");
    var vidTitle = $(this).attr("data-title");
    var winWidth = $(window).width();
    var smallScreen = winWidth < 768;
    var maxWidth = smallScreen ? winWidth - 60 : 560; // deducting 60 to accomodate margins

    $("#yt-player").html(""); //clear wrapper div

    $("<iframe>", {
      src: vidSrc,
      id: "globalYTembed",
      frameborder: 0,
      allowFullscreen: "true",
      width: maxWidth,
      height: smallScreen ? maxWidth * 0.75 : 315,
      title: vidTitle,
    }).appendTo("#yt-player");

    $("#video-modal").modal("show");
  });

  //reset youtube iframe when closing modal
  $("#video-modal").on("hidden.bs.modal", function () {
    $("#yt-player").html(""); //clear wrapper div
  });

  //** LADDA BUTTONS **
  //Generate button
  $(".ladda-btn")
    .attr("data-style", "slide-left")
    .addClass("ladda-button")
    .each(function () {
      var $this = $(this);
      var span = document.createElement("span");
      $(span).addClass("ladda-label");

      $this.html($(span).append($this.html()).html());
    });

  //Bind button
  $(".ladda-btn.link").ladda("bind");

  //ANALYTICS
  // analytics.trackLink($('.register-link'), 'RegisterClick',
  // 	function (e) {
  // 		var loc = $(e).attr('data-location') || 'other';
  // 		var vialDetails = typeof getDonorVialDetail == 'undefined' ? "na" : getDonorVialDetail();
  // 		return {
  // 			location: loc,
  // 			vial_details: vialDetails
  // 		}
  // 	});

  //BLOCKED alert
  if (typeof toShowLoginAlert != "undefined" && toShowLoginAlert) {
    bootbox.alert({
      title: loginAlertTitle,
      message: loginAlertContent,
      callback: function () {
        $.post("/accountajax/loginalertdisplayed/");
      },
    });
  }

  $("#privacy-web-use-bar .close-btn").click(function () {
    $("#privacy-web-use-bar").hide();
    $.ajax({
      type: "POST",
      url: "/accountajax/update-privacy-web-use/",
      success: function (response) {
        if (response.toLowerCase() == "success") {
          needsPrivacyOrWebUse = false;
        } else {
          console.log("There was an error updating privacy poilicy or webuse");
        }
      },
    });
  });

  $("body").click(function (e) {
    if (
      $(".site-bar.active").length > 0 &&
      !$(e.target).hasClass("site-trigger")
    ) {
      $(".close-site").click();
    }
  });

  //mobile my-account click
  $(".my-account-trigger").click(function () {
    var redirectPath =
      window.location.pathname == "/" ? "/account/" : window.location.pathname;
    window.location = "/login/?returnUrl=" + redirectPath;
  });
}); //END $.function

if (needsPrivacyOrWebUse) {
  $(window).bind("beforeunload", function () {
    //before close/reload browser

    $.ajax({
      type: "POST",
      url: "/accountajax/update-privacy-web-use/",
      async: false,
      success: function (response) {},
    });
  });
}

function ClearSessionCookieAndLogOut(Email) {
	analyticsTrack("Signed Out", {
		email: Email
	}, function () {
    ClearSessionCookie();
    window.location =
      "/accountajax/logout/?returnUrl=" + window.location.pathname;
  });
}

function ClearSessionCookie() {
  var i;
  var cookiesArr;
  var cItem;
  cookiesArr = document.cookie.split("; ");
  for (i = 0; i < cookiesArr.length; i++) {
    cItem = cookiesArr[i].split("=");
    if (
      cItem.length > 0 &&
      (cItem[0].indexOf("ASP.NET_SessionID") == 0 ||
        cItem[0].indexOf("ASP.NET_SessionId") == 0)
    ) {
      deleteCookie(cItem[0]);
    }
  }
  function deleteCookie(name) {
    var expDate = new Date();
    expDate.setTime(expDate.getTime() - 86400000); //-1 day
    var value = "; expires=" + expDate.toGMTString() + ";path=/";
    document.cookie = name + "=" + value;
  }
}

function ShowLoginPopup(showLogin) {
  $(".modal.in").modal("hide"); //Close all open modals
  if (showLogin) {
    switchToLogin("fast");
  } else {
    switchToRegister("fast");
  }
  $("#registerlogin-form").modal("show");
}

function switchToLogin(speed) {
  $(".register-login-forms .registerlogin-register").hide(speed);
  $(".register-login-forms .registerlogin-login").show(speed);
}

function switchToRegister(speed) {
  $(".register-login-forms .registerlogin-login").hide(speed);
  $(".register-login-forms .registerlogin-register").show(speed);
}

///Generic method to show loading spinner
// If spinner exists, show it. otherwise, append to 'this'
function showSpinner(obj) {
  //need to remove
  $this = $(obj);
  var newSpinner = '<i class="fa fa-spinner fa-pulse"></i>';
  //show if spinner exists
  var currentSpinners = $this.find(".fa-spinner");
  if (currentSpinners.length > 0) {
    currentSpinners.show();
  } else {
    $this.append(newSpinner);
    //$this.find(".fa-spinner").show();
  }
}

function pad(n, width, z) {
  z = z || "0";
  n = n + "";
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

// Before segment identify call is made, make sure non-whitelisted traits are not in "ajs_user_traits" local storage item
// This method is duplicated in multiple javascript files
function CheckForWhitelistTraits() {

    var ajstraits = localStorage.getItem("ajs_user_traits");
    var traits = JSON.parse(ajstraits);

    // planned traits for all segment identify calls
    var whitelistedTraits = ["user_id", "city", "state", "country", "zip_code", "age", "created_at", "customer_type", "self_reported_lead_source", "subscription_status", "subscription_code","subscription_start_date", "subscription_end_date", "vial_purchase_count", "subscription_purchase_count"];

    if (traits !== null){
      var keys = Object.keys(traits);

      // if there exists a key that is not on the whitelist
      if (!(keys.every(x => whitelistedTraits.includes(x)))) {

          var blackList = [];
          keys.forEach(x => { if (!whitelistedTraits.includes(x)) { blackList.push(x) } });
          blackList.forEach(x => delete traits[x]);

          // override the local storage item with only whitelist traits
          localStorage.setItem("ajs_user_traits", JSON.stringify(traits));
      }
    }
}

//should only be called from checkout&confirmation page
function Login(form) {
  $this = $(form);
  var url = window.location.origin;

  $.post(
    GetUrl() + "/login/signinajax/",
    {
      email: $this.find("#Account_Email").val(),
      password: $this.find("#Account_Password").val(),
    },
    function (data) {
      if (data.status == "failed") {
        $this.find(".loader").hide();
        $this.find(".text-danger").text(data.message);
      } else if (data.status == "nowebaccount") {
        l.ladda("stop"); //stop spinner
        $form
          .find(".text-danger")
          .html(
            $.parseHTML(
              '<div>Please contact <a href="/about-us/contact-us/email-us/" style="text-decoration: underline;" target="_blank">Client Services</a> to set up your web account.</div>'
            )
          );
        $form.validate().resetForm(); //reset form
      } else {
        //should redirect and not get here
        CheckForWhitelistTraits();
        analytics.identify(data.contactNo);
        analyticsTrack("Signed In", null, function () {
          location.reload(true);
        });

          // Remove local storage item, because if it isn't removed, will pass along this information to subsequent segment calls
          if (localStorage.getItem("ajs_user_traits")) {
              localStorage.removeItem("ajs_user_traits");
          }
      }
    }
  ).fail(function () {
    $this.find(".text-danger").text("an error occured");
  });
}

//clear error message when focusing in form field
$(document).on("focus, click", "input", function () {
  $(".LoginForm .post-message.text-danger").text("");
  clearAlert($(".response-alert"));
});

$.fn.SubmitLogin = function () {
  $this = $(this);
  $form = $this.closest(".LoginForm");

  var returnUrl = "";
  //checking return url if on login page
  if ($this.closest("#register-login-page").length > 0) {
    returnUrl = getQueryStringParameterByName("returnUrl") + location.hash;
  }
  if (sessionStorage.getItem("returnURL") != null) {
    returnUrl = sessionStorage.getItem("returnURL");
  }
  if (new URLSearchParams(window.location.search).has("promo")) {
    returnUrl = window.location.pathname + window.location.search;
  }
  if ($form.valid()) {
    //spinner
    var l = $form.find(".login-button").ladda();
    l.ladda("start");

    var thisEmail = $form.find("#Account_Email").val();

    $.post(
      "/login/signinajax/",
      {
        email: thisEmail,
        password: $form.find("#Account_Password").val(),
        returnUrl: returnUrl,
      },
      function (data) {
        if (data.status == "failed") {
          l.ladda("stop"); //stop spinner
          $form.find(".text-danger").text(data.message);
          $form.validate().resetForm(); //reset form
        } else if (data.status == "nowebaccount") {
          l.ladda("stop"); //stop spinner
          $form
            .find(".text-danger")
            .html(
              $.parseHTML(
                '<div>Please contact <a href="/about-us/contact-us/email-us/" style="text-decoration: underline;" target="_blank">Client Services</a> to set up your web account.</div>'
              )
            );
          $form.validate().resetForm(); //reset form
        } else {
          // HubSpot Identify Call
          var _hsq = (window._hsq = window._hsq || []);
          _hsq.push([
            "identify",
            {
              email: $this.find("#Account_Email").val(), //,
              //import: "Identify"
            },
          ]);
          _hsq.push(["trackPageView"]); // force id through
          setTimeout(function () {
            console.log("HubSpot Id");
          }, 300); // allow call time to process

          //data should have code to redirect/reload
          CheckForWhitelistTraits();
          analytics.identify(data.contactNo, {email: $form.find("#Account_Email").val()});
          analyticsTrack("Signed In", {email: $form.find("#Account_Email").val()}, function () {
            if (data.action == "reload") {
              location.reload(true);
            } else if (data.action == "redirect") {
              window.location = data.redirectUrl;
            }
          });

            // Remove local storage item, because if it isn't removed, will pass along this information to subsequent segment calls
            if (localStorage.getItem("ajs_user_traits")) {
                localStorage.removeItem("ajs_user_traits");
            }
          sessionStorage.removeItem("returnURL");
        }
      }
    ).fail(function () {
      l.ladda("stop");
      $form.find(".text-danger").text("an error occured");
    });
  }
};

if ($(".static-page").length != 0) {
  $(".top-bar").css("background", "#666666");
}

function GetUrl() {
  if (window.location.origin.indexOf("localhost") == -1) {
    return "https://" + window.location.host;
  } else {
    return window.location.origin;
  }
}

//#region ALERTS

//To use with partial _Alert (or similar html)
// status <= {success, alert ...} (bootstrap alert class)
function setAlert(alert, status, msg, errorMsg, form) {
  //assuming alert is a jQuery object
  alert.addClass("alert-" + status);
  alert.find(".msg").html(msg);
  alert.find(".errorMsg").text(errorMsg);

  //display alert
  alert.removeClass("hidden");
  alert.show();

  if (form) form.validate().resetForm();
}

function clearAlert(alert) {
  alert.removeClass("alert-success alert-info alert-warning alert-danger");
  alert.find(".msg").html("");
  alert.find(".errorMsg").text("");
  alert.addClass("hidden");
}
//#endregion

//#region FUNCTIONS

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
  var timeout;
  return function () {
    var context = this,
      args = arguments;
    var later = function () {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
}

//reset size of youtube videos to match page width
function initResetVideos() {
  // Find all YouTube videos
  //$allVideos = $("iframe[src^='https://www.youtube.com']");
  initUpdateAllVideos();

  // The element that is fluid width
  if ($allVideos.length > 0) {
    //target = altFluidEl ? altFluidEl : "div";
    //$fluidEl = $allVideos.first().closest(target);
    $fluidEl = $allVideos.first().closest("div");
  }

  //global aspect ratio- assuming all videos have same ration. used to fix Glide.js issues

  $globalVideoAspectRatio = $allVideos[0].height / $allVideos[0].width;

  // Figure out and save aspect ratio for each video
  $allVideos.each(function () {
    $(this)
      .data("aspectRatio", this.height / this.width)

      // and remove the hard coded width/height
      .removeAttr("height")
      .removeAttr("width");
  });
}
function initUpdateAllVideos() {
  $allVideos = $("iframe[src^='https://www.youtube.com']");
}

function updateFluidEl(altFluidEl) {
  if ($allVideos.length > 0) {
    target = altFluidEl ? altFluidEl : "div";
    $fluidEl = $allVideos.first().closest(target);
  }
}

function resetVideosLimited() {
  resetVideos(true);
}

//when called directly, limitWidth is an event. => must compare to 'true'
function resetVideos(limitWidth) {
  var newWidth = $fluidEl.width();

  if ($fluidEl.hasClass("limit-video") || limitWidth == true) {
    var windowWith = $(window).width();
    if (windowWith >= 1200) {
      newWidth = (newWidth * 6) / 12;
    } else if (windowWith >= 992) {
      newWidth = (newWidth * 7) / 12;
    } else if (windowWith >= 768) {
      newWidth = (newWidth * 8) / 12;
    } else {
      //mobile
      //newWidth = newWidth;
    }
  }

  // Resize all videos according to their own aspect ratio
  $allVideos.each(function () {
    var $el = $(this);

    var ratio = $el.data("aspectRatio")
      ? $el.data("aspectRatio")
      : $globalVideoAspectRatio;
    $el
      .width(newWidth)
      //.height(newWidth * $el.data('aspectRatio'));
      .height(newWidth * ratio);
  });
}

function forceTrailSlash(path) {
  if (path.charAt(path.length - 1) != "/") {
    path += "/";
  }
  return path;
}

//#endregion



//EXPANDING PROTOTYPES
//**********************
String.prototype.capitalizeFirstLetter = function () {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(";");
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == " ") {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function checkCookie() {
  var user = getCookie("username");
  if (user != "") {
    alert("Welcome again " + user);
  } else {
    user = prompt("Please enter your name:", "");
    if (user != "" && user != null) {
      setCookie("username", user, 365);
    }
  }
}

if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, "includes", {
    value: function (searchElement, fromIndex) {
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return (
          x === y ||
          (typeof x === "number" &&
            typeof y === "number" &&
            isNaN(x) &&
            isNaN(y))
        );
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        // c. Increase k by 1.
        k++;
      }

      // 8. Return false
      return false;
    },
  });
}

$(".track-cta").on("click", function (e) {
    let elem = e.currentTarget;

    var ctaType = "";
    var href = elem.href ? elem.href : elem.getAttribute("data-page");
    if ($(elem).hasClass("btn")) {
        ctaType = "Button";
    }
    else {
        ctaType = "Banner";
    }

  let props = {
    text: $(`<div>${$(elem).html()}</div>`)
      .text()
      .trim(),
    url: document.URL,
    type: ctaType,
    destination: href,
    location: elem.getAttribute("data-page") + ": " + elem.getAttribute("data-location"),
  };
  // console.log("CTA Clicked", props);
  analyticsTrack("CTA Clicked", props);
});

$(document).on("click", ".site-search-autofill", function (e) {
  let positionProp = $(this).attr("position")
    ? parseInt($(this).attr("position")) + 1
    : "";
  analyticsTrack("Site Search Result Selected", {
    query: $(".searchbox").val(),
    position: positionProp,
    location: "autofill",
  });
});

// segment analytics
function analyticsTrack(eventName, props = null, callback = null) {
    // if props not null
    if (!!props && Object.keys(props).length > 0) {
        // let num_pattern = /^(?:\d+(?:\.\d*)?|\.\d+)(?:,(?:\d+(?:\.\d*)?|\.\d+))*$/;
        let num_pattern = /^[0-9.,]*$/;
        let doNotConvertToFloatKeys = ["donor_id"];
        // clean props
        for (const [key, value] of Object.entries(props)) {
            let val = value;
            // console.log(`${key} : ${val}`);
            // if null remove value
            if (val == null || val == undefined) {
                // delete props[key];
                props[key] = "";
            }
            // else if numeric convert numeric values to float with two trailing zeros
            else if (
                val != "" &&
                !isNaN(val) &&
                num_pattern.test(val) &&
                !doNotConvertToFloatKeys.includes(key)
            ) {
                val = val.toString();
                val = val.replace(",", "");
                val = val.replace(".", "");
                val = parseFloat(val).toFixed(2);
                props[key] = val;
            }
        }
        
        try {
            // pass callback function
            if (callback != null) {
                analytics.track(eventName, props, callback);
            }
            // no callback function
            else {
                analytics.track(eventName, props);
            }
        } catch (error) {
            //LogProvider.Log(LogProvider.LogLevels.Error, error);
            console.warn("Unable to publish to Segment:" + error.message);
        }
    }
    // no properties
    else {
        try {
            // pass callback function
            if (callback != null) {
                analytics.track(eventName, callback);
            }
            // no callback function
            else {
                analytics.track(eventName);
            }
        } catch (error) {
            //LogProvider.Log(LogProvider.LogLevels.Error, error);
            console.warn("Unable to publish to Segment:" + error.message);
        }
    }
}

/**
 * Function if the page should get extra padding
 * Pages listed in comments
 * Some ID's are established in Ektron
 * @param {number} width
 * @returns {boolean}
 */
function doNotExtendBarHeight(width) {
    return $(".master-container #sticky-header-container").length > 0 // when in donor profile page
    ||     $(".master-container #subscriptionModal").length > 0 // when in donor subscriptions/options
    ||     $(".master-container #locations").length > 0 // when in /about-us/locations/
    ||     $(".master-container #account-page").length > 0 && width <= 768 // when in account page
    ||     $(".master-container #discover-donor").length > 0 // when in DNA Ancestry page
    ||     $(".master-container #donor-reserve-hero").length > 0 // when in donor-reserve-hero
    ||     $(".master-container #cord-blood-banking").length > 0 // when in Cord Blood Banking page
    ||     $(".master-container #lgbtq-families").length > 0 // when in LGBTQ Page
    ||     $(".master-container #expanded-genetic-testing").length > 0 // when in Genetic Services Testing Page
    ||     $(".master-container #search-controller").length > 0 && width < 768 // when in search page/mobile
    ||     $(".master-container .has-hero").length > 0; // when in Location pages w/hero images
}
;
function Countdown(secs, onTick, onEnd)
{
	if (!readCookie('vialTime'))
	{
	    $.post("/cart/removevials/");
		return;
	}
	if(secs > 0)
	{
		var vialCartTime = readCookie("vialTime");
		var secsLeft = 3598 - Math.floor((Date.now() - vialCartTime) / 1000);
		window.setTimeout("Countdown(" + (secsLeft - 1) + ", " + onTick + ", " + onEnd + ")", 1000);
		if (typeof (onTick) == "function") onTick(secsLeft);
		else DefaultOnTick(secsLeft);
	}
	else if (secs <= 0 && secs >= -300 && typeof (onEnd) == "function")
	{
		onEnd();
	} 
	else if (secs <= 0 && secs >= -300)
	{
		 DefaultOnEnd();
	}
	else if (secs < -300) {
		// only if seconds greater than 5 minutes past an hour
		clearTimerRemoveVials();
	}
}

function setCountdown(secsLeft) {
    Countdown(secsLeft, function (secs) {

        if (secs <= 900 && secs > 899)
        {
        	alert("The vials in your cart will be removed in 15 minutes. Please return to checkout to complete your order.");
        	var vialCartTime = readCookie("vialTime");
        	var secsLeft = 3598 - Math.floor((Date.now() - vialCartTime) / 1000); // remove vials if 15 minute alert left open for longer than 15 min
        	if (secsLeft < 0) {
        		alert("The vials in your cart have been released.");
        		clearTimerRemoveVials();
        	}
        }
    },
        function () {
        	alert("The vials in your cart have been released.");
        	clearTimerRemoveVials();
        });
}

function DefaultOnTick(secs)
{
	$.post("/cart/removevials/");
	eraseCookie("vialTime");
	alert("The vials in your cart have been released.");
}

function DefaultOnEnd()
{
	alert("Countdown has ended.");
}

function clearTimerRemoveVials() {
	if (typeof (isCheckoutPage) === "undefined") { // check if not in checkout page
		var $item = $(this).closest(".cart-item");
		var headerCart = $("#header-cart");
		$item.remove();
		setEmptyCart(headerCart);
		$(".cart-wrp .cart-item-qty").text(0);
		eraseCookie("vialTime");
		$.post("/cart/removevials/");
	}
	else {
		eraseCookie("vialTime");
		sessionEnded = true;
		showConfirmOrderSpinner();
		$.post("/cart/removevials/").always(function () {
			if ($('#donor-profile-url').val()) {
				window.location = $('#donor-profile-url').val();
			}
			else {
				window.location = "/";
			}
		});
	}
}

/// cookie support for countdown
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

$(window).load(function () {
    var vialCartTime = readCookie("vialTime");
    if (!$.isEmptyObject(vialCartTime)) {
        var secsLeft = 3598 - Math.floor((Date.now() - vialCartTime) / 1000);
        setCountdown(secsLeft);
    }
});;
// also in cart_checkout.js  consolidate when checkout page and main site share same js file
String.prototype.addCommas = function () {
	return this.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Number.prototype.toStringWithCommas = function () {
	return this.toString().addCommas();
}

//TODO: Move to global shared js file when possible
function CustomAlert(title, message, options) {
	if ($.fancybox) {
		$.fancybox(message, options);
	}
	else if (bootbox) {
		bootbox.alert({ title: title, message: message });
	}
	else {
		alert(message);
	}
}

//Logic To display instead of actual vial availability
function vialAvailabilityToDisplay(val) {
	var intVal = parseInt(val);

	if (intVal < MIN_VIALS_TO_DISPLAY) {
		return "<span class='low'>Call for Availability: <a href='tel:866-927-9622'>866-927-9622</a></span>";
	}
	else if (intVal < MAX_VIALS) {
		return "<span class='mid'>" +val + " vials</span>";
	}
	else {
		return "<span class='high'>" + MAX_VIALS + "+ vials</span>";
	}
}

//Logic for vial icons
function vialAvailabilityIconDisplay(vials) {
    if (vials >= MAX_VIALS) {
        return "full";
    } else if (vials > 0) {
        return "semi";
    } else {
        return "none";
    }
}

function vialAvailabilityIconToolTip(vials) {
	if (vials >= MAX_VIALS) {
		return MAX_VIALS + "+ vials";
	} else if (vials > 0) {
		return "Low vial availability";
	} else {
		return "";
	}
}

function vialStatusIconDisplay(vialStatus) {
    switch (vialStatus) {
        case "high":
            return "full";
        case "low":
            return "semi";
        case "none":
            return "none";
        default:
            return "none";
    }
}

function vialStatusIconToolTip(vialStatus) {
    switch (vialStatus) {
        case "high":
            return MAX_VIALS + "+ vials";
        case "low":
            return "Low vial availability";
        case "none":
            return "";
        default:
            return "";
    }
}

//var MAX_VIALS;  //SET in HeaderCart HTML files
var cartTimer;
var hoverTimer;

fancyboxOptions = {
	'title': 'Alert',
	'titleShow': true,
	'easingIn': 'easeOutBack',
	'easingOut': 'easeInBack',
	'transitionIn': 'elastic',
	'transitionOut': 'elastic'
}

var vialsInCartAlert = false;

//Add Vials to Cart
//id: vial ID
function addVialsToCart(id, description, qty, price, moreDetails, availQty, isSession) {
	// segment track
	// get donor position from url
	const isFeaturedDonor = document.URL.includes("featuredsearch");
	const queryParams = new URLSearchParams(window.location.search);
	const position_prop_name = 'position';
	let search_position = '';
	if (queryParams.has(position_prop_name)) {
		search_position = queryParams.get(position_prop_name);
		if (isFeaturedDonor) {
			search_position = 'featured-' + search_position;
		}
	}

	// had issue where data was trying to be access when it didn't exist. This insures data exists when trying to access it
	let imgUrl = $(".photo-wrap img") ? ( $(".photo-wrap img")[0] !== undefined ? $(".photo-wrap img")[0].src : 'could not find photo source') : '';
	let donorId = $(".donor-info .donor-id .id") ? ($(".donor-info .donor-id .id")[0] !== undefined ? $(".donor-info .donor-id .id")[0].innerHTML : 'could not find donor id') : '';

	// will only trigger when event only fires
	if ( isSession == false && $(".photo-wrap img")[0] !== undefined && $(".donor-info .donor-id .id")[0] !== undefined) {
		analyticsTrack("Product Added", {
			donor_id: donorId,
			featured_donor: isFeaturedDonor,
			product_category: 'vials',
			product_name: 'vials',
			price: price,
			quantity: qty,
			value: qty * price,
			position: search_position,
			url: window.location.href,
			image_url: imgUrl,
			product_name: description
		});
	}
  	// end segment track

	//Update available quantity if you have same vials already checked out
	if (checkedOutVials[id]) {
		availQty += checkedOutVials[id];  //checkedOutVials set in HeaderCart.ascx/cshtml
	}

	if (qty > MAX_VIALS) {
		alertMaxVails();
		return;
	}

	//(should only be called) qty entered on profile page is more than available
	if (availQty && qty > availQty) {
		alertMoreThanAvail(availQty);
		qty = availQty;
	}

	
	qty = parseInt(qty);
	price = parseInt(price);
	var splitId = id.split("-");
	var donorNo = splitId[0];

	var headerCart = $("#header-cart");
	
	//if on donor page and is same donor is vials in cart
	if (typeof (_donor_model) != 'undefined' && _donor_model.DonorNo == donorNo) {
		if (showLowVialsMsg) {

			$('.low-vial-warning .alert').show();
			$('.low-vial-warning .alert').addClass('in');
		}
		else {
			$('.low-vial-warning .alert').hide();
			$('.low-vial-warning .alert').removeClass('in');
		}
	}

	//Check if Other donor
	if (headerCart.find(".donor-no").text() != "" &&
		(headerCart.find(".donor-no").text() != donorNo && !isSession)) {
		//$.fancybox('<p>Please remove the existing donor from your cart.</p><p>California Cryobank only allows the purchase of one donor at a time. You may contact us at 866-927-9622 with any questions.</p>', fancyboxOptions);
		CustomAlert('Alert','<p>Please remove the existing donor from your cart.</p><p>California Cryobank only allows the purchase of one donor at a time. You may contact us at 866-927-9622 with any questions.</p>', fancyboxOptions);
	}
	else {
		//empty cart
		if (headerCart.find(".active-cart").hasClass("hidden")) {
			headerCart.find(".empty-cart").addClass("hidden");				//hide Empty cart
			headerCart.find(".active-cart").removeClass("hidden");			//Show Active cart
			headerCart.find(".donor-no").text(donorNo);						//insert donor no
			headerCart.find(".donor-info a").attr('href', headerCart.find(".donor-info a").attr('href') + donorNo);
			headerCart.find(".more-details").text("").append(donorMoreInfotoHtml(moreDetails));	//insert donor (more) info (characaristics)
		}
		var dataAttr = "data-item-id=" + id;
		var currentItem = headerCart.find(".cart-item[" + dataAttr + " ]");

		//Has existing items
		if (currentItem.length > 0) {
			currentItem = currentItem.first();
			var currentQty = parseInt(currentItem.find(".qty").val());
			var newQty = currentQty + qty;

			//if wanted amount is more than alowed
			if (newQty > MAX_VIALS) {
				alertMaxVails();
				return;
			}
			
			//AvailQty is set
			if (availQty) {
				if (newQty > availQty) {

					// Commented instead of removed just in case team decides to enforce 2 vials per purchase in cart in the future.
					// Ensure IVF vials are ordered in an even number
					/*if ((id.toUpperCase().includes("-PT") && availQty % 2 == 1)) {
						alertMoreThanAvailIVFVials(availQty - 1);
						newQty = availQty - 1;
					}
					else {
						alertMoreThanAvail(availQty); // code is implemented below, when uncommenting.
						newQty = availQty;
					}*/
					alertMoreThanAvail(availQty);
					newQty = availQty;
				}
			}

			currentItem.find(".qty").val(newQty).change();
			currentItem.find("input[name=hdnCurrentQty]").val(newQty);
			updateSessionWithQty(newQty, id, availQty, false);
		}
			//New Item
		else {
			//Validate quantity under max
			var otherItemsQty = 0;
			headerCart.find(".cart-item").find(".qty").each(function () { otherItemsQty += parseInt(this.value) });
			if (otherItemsQty + qty > MAX_VIALS) {
				alertMaxVails();
				return;
			}

			var newItem = headerCart.find(".cart-item-skeleton").clone();
			newItem.removeClass("cart-item-skeleton").addClass("cart-item");			
			newItem.find(".cart-item-type").text(description); 							//description
			newItem.find(".cart-item-detail .price").text(price.toStringWithCommas());				//prices
			newItem.find("select.qty").val(qty);													//quantity
			newItem.find("input[name=hdnCurrentQty]").val(qty);
			newItem.find(".cart-item-detail .sub-total").text((qty * price).toStringWithCommas());	//subtotal
			newItem.attr("data-item-id", id);														//id (donor + type)
			newItem.attr("data-item-desc", description);											//description
			
			//limit dropdown
			//if (availQty  && availQty < MAX_VIALS) {
                newItem.find('.qty option').each(function () {
                    
					var $this = $(this);

					// Commented instead of removed just in case team decides to enforce 2 vials per purchase in cart in the future.
                    if ($this.text() > availQty /* || id.toUpperCase().includes(VIAL_TYPES)  && parseInt($this.text()) % 2 == 1) */) {
						$this.remove();
					}
				});
			//}

			headerCart.find(".cart-items").append(newItem);

			updateSessionWithQty(qty, id, availQty, false);

		}

		updateHeaderCartItemCount(headerCart);
	}
}

//called from profile
function addAndDisplayVialsToCart(id, description, qty, price, moreDetails, availQty)
{
	addVialsToCart(id, description, qty, price, moreDetails, availQty, false);
	showCart();															// 1.show cart
	cartTimer = setTimeout(function () { hideCart(); }, 7000);			// 2.hide cart on timer
								// 3. update session with updated cart
}

function addShipmentToCart(id, description, qty, price, moreDetails, availQty, contractNo, locationCode, isSession) {
	//segment track would go here

	//parse args
	qty = parseInt(qty);
	price = parseInt(price);
	var splitId = id.split("-");
	var donorNo = splitId[0];

	var headerCart = $("#header-cart");

	//Check if Other donor, maybe also need to check for same donor sale order here?
	if (headerCart.find(".donor-no").text() != "" &&
		(headerCart.find(".donor-no").text() != donorNo && !isSession)) {
		//$.fancybox('<p>Please remove the existing donor from your cart.</p><p>California Cryobank only allows the purchase of one donor at a time. You may contact us at 866-927-9622 with any questions.</p>', fancyboxOptions);
		CustomAlert('Alert', '<p>Please remove the existing donor from your cart.</p><p>California Cryobank only allows the purchase of one donor at a time. You may contact us at 866-927-9622 with any questions.</p>', fancyboxOptions);
	} else {
		//empty cart
		if (headerCart.find(".active-cart").hasClass("hidden")) {
			headerCart.find(".empty-cart").addClass("hidden");				//hide Empty cart
			headerCart.find(".active-cart").removeClass("hidden");			//Show Active cart
			headerCart.find(".donor-no").text(donorNo);						//insert donor no
			headerCart.find(".donor-info a").attr('href', headerCart.find(".donor-info a").attr('href') + donorNo);
			headerCart.find(".more-details").text("").append(donorMoreInfotoHtml(moreDetails));	//insert donor (more) info (characaristics)
			headerCart.find(".active-cart").addClass("shipment"); //shipment class for jquery callbacks to check
		}
		var dataAttr = "data-item-id=" + id;
		var currentItem = headerCart.find(".cart-item[" + dataAttr + " ]");

		//Has existing items
		if (currentItem.length > 0) {
			currentItem = currentItem.first();
			var currentQty = parseInt(currentItem.find(".qty").val());
			var newQty = currentQty + qty;

			//AvailQty is set
			if (availQty) {
				if (newQty > availQty) {
					vialsInCartAlert = true;
					newQty = availQty;
				}
			}

			currentItem.find(".qty").val(newQty).change();
			currentItem.find("input[name=hdnCurrentQty]").val(newQty);
			updateSessionWithQty(newQty, id, availQty, null, null, true);
		}
		//New Item
		else {
			//Validate quantity under max
			var otherItemsQty = 0;
			headerCart.find(".cart-item").find(".qty").each(function () { otherItemsQty += parseInt(this.value) });

			var newItem = headerCart.find(".cart-item-skeleton").clone();
			newItem.removeClass("cart-item-skeleton").addClass("cart-item");
			newItem.find(".cart-item-type").text(description); 					//description
			newItem.find(".cart-item-detail .price").text(price.toStringWithCommas());				//prices
			newItem.find(".cart-item-detail .price").parent().addClass("hidden");					//hide price for ship orders
			newItem.find("select.qty").val(qty);													//quantity
			newItem.find("input[name=hdnCurrentQty]").val(qty);
			newItem.find(".cart-item-detail .sub-total").text((qty * price).toStringWithCommas());	//subtotal
			newItem.find(".cart-item-detail .sub-total").parent().addClass("hidden");				//hide subtotal
			newItem.find(".cart-item-detail .detail-ship").parent().removeClass("hidden");			//Show that this is a ship from storage cart
			newItem.attr("data-item-id", id);														//id (donor + type)
			newItem.attr("data-item-desc", description);											//description

			//hide sales order messaging
			headerCart.find(".low-vial-warning").addClass("hidden");
			headerCart.find(".storage-programs").addClass("hidden");
			headerCart.find(".upsell-messages").addClass("hidden");
			headerCart.find(".notifications").addClass("hidden");
			//limit dropdown
			//if (availQty  && availQty < MAX_VIALS) {
			newItem.find('.qty option').each(function () {

				var $this = $(this);

				// Commented instead of removed just in case team decides to enforce 2 vials per purchase in cart in the future.
				if (parseInt($this.text()) > parseInt(availQty) /* || id.toUpperCase().includes(VIAL_TYPES)  && parseInt($this.text()) % 2 == 1) */) {
					$this.remove();
				}
			});
			//}

			headerCart.find(".cart-items").append(newItem);

			updateSessionWithQty(qty, id, availQty, contractNo, locationCode, true);

		}

		updateHeaderCartItemCount(headerCart);
	}
	
}

//call from storage manager
function addAndDisplayShipmentToCart(id, description, qty, price, moreDetails, availQty, contractNo, locationCode)
{
	addShipmentToCart(id, description, qty, price, moreDetails, availQty, contractNo, locationCode, false);
	showCart();															// 1.show cart
	cartTimer = setTimeout(function () { hideCart(); }, 7000);			// 2.hide cart on timer
								// 3. update session with updated cart
}

function hideCart() {
	//$("#header-cart").slideUp("normal", function () {
		
	//});

	$(".cart-wrp").removeClass("active");
	$("#header-cart").trigger("headerCart.closed");
	$("#header-cart").hide();
}

function showCart() {
	$("#header-cart").trigger("headerCart.opening");
	//$("#header-cart").slideDown("slow");
	$(".cart-wrp").addClass("active");
	$("#header-cart").show();
}

function donorMoreInfotoHtml(moreDetails) {
	var res = "<ul>";
	for (var item in moreDetails) {
		res += "<li><label>" + item + ":</label>" + unescape(moreDetails[item]) + "</li>";
	}
	return res + "</ul>";
}

function setEmptyCart(headerCart, shipable) {
	if (!shipable) {
		headerCart.find(".empty-cart").removeClass("hidden");
	}
	headerCart.find(".active-cart").addClass("hidden");
	headerCart.find(".donor-no").text("");
	headerCart.find(".more-details").text("");

	//reset hidden tags to default
	headerCart.find(".active-cart").removeClass("shipment");
	headerCart.find(".cart-item-detail").removeClass("hidden");
	headerCart.find(".detail-ship").parent().addClass("hidden");
	//headerCart.find(".checkout.btn").addClass("disabled");
}

function updateHeaderCartItemCount(headerCart) {
	var cartItemQty = 0;
	headerCart.find(".cart-item .qty").each(function () { cartItemQty += parseInt(this.value) });
	$(".cart-wrp .cart-item-qty").text(cartItemQty);	//add item count to header
	updateUpsellVials();
}

function updateUpsellVials() {
	// get promotion vial amounts
	if (typeof (minVials) != "undefined") {
		var promo = minVials;
		var vialsSelected = $(".cart-item-qty").first().text();
		if (vialsSelected < promo) {
			$('.upsell-messages .upsell-message').show();
			$('.upsell-messages .upsell-qualified').hide();
			var diff = promo - vialsSelected;
		}
		else {
			$('.upsell-messages .upsell-message').hide();
			$('.upsell-messages .upsell-qualified').show();
		}
		$('.upsell-vial-qty').text(diff);
	}
}

function updateHeaderCartFromSession() {
	var data = new Object();
	data.action = "getCart";
	$.post("/_handlers/cart.ashx", data, function (data) {
		if (data && data.cart && data.cart != "" && data.cart.Items && data.cart.Items != "") {
			// remove all vials in headerCart before adding them from session
			$(".cart-item").remove();
			var totalQuantityLeft = 0;
			if (data.cart.DonorInfo && data.cart.DonorInfo.Retired_Zero && data.cart.DonorInfo.VialsAvailable < 50) {
				$('.low-vial-warning .alert').show();
				$('.low-vial-warning .alert').addClass('in');
			}
			else {
				$('.low-vial-warning .alert').hide();
				$('.low-vial-warning .alert').removeClass('in');
			}
			if (data.cart.DonorInfo && data.cart.DonorInfo != "") {
					var donorMoreInfo = {
					    "HAIR COLOR": data.cart.DonorInfo.Hair_Color,
					    "EYE COLOR": data.cart.DonorInfo.Eye_Color,
					    HEIGHT: data.cart.DonorInfo.Height,
					    WEIGHT: data.cart.DonorInfo.Weight,
					    "BLOOD TYPE": data.cart.DonorInfo.Blood_Type,
					    "DONOR TYPE": data.cart.DonorInfo.Donor_Subtype,
					    ANCESTRY: data.cart.DonorInfo.Ancestry.join(", ")
					};
				}
				else {
					var donorMoreInfo = {
						"HAIR COLOR": "",
						"EYE COLOR": "",
						HEIGHT: "",
						WEIGHT: "",
						"BLOOD TYPE": "",
						"DONOR TYPE": "",
						ANCESTRY: ""
					};
			}
			if (data.cart.IsShipFromStorage) {
				for (var i = 0; i < data.cart.Items.length; i++) {
					addShipmentToCart(data.cart.Items[i].TypeDetail, data.cart.Items[i].TypeDescription, data.cart.Items[i].Quantity, data.cart.Items[i].Price, donorMoreInfo, data.cart.Items[i].AvailableQuantity, null, null, true);
				}
			} else {
				for (var i = 0; i < data.cart.Items.length; i++) {
					addVialsToCart(data.cart.Items[i].TypeDetail, data.cart.Items[i].TypeDescription, data.cart.Items[i].Quantity, data.cart.Items[i].Price, donorMoreInfo, data.cart.Items[i].AvailableQuantity, true);
				}
			}
		}
	}); //save cart in session
}

function alertMaxVails() {
	CustomAlert('Alert','<p>We\'re sorry, you cannot add more than ' + MAX_VIALS + ' vials to your cart. <br>Please contact Client Services at 866-927-9622 to purchase additional vials. </p>', fancyboxOptions);
}

function alertMoreThanAvail(availQty) {
	CustomAlert('Alert',"<p>We’re sorry, but we don’t have the quantity of vials you requested. We added " + availQty + " vials to your cart.</p>", fancyboxOptions);
}

function alertStorageAleadyInCart() {
    CustomAlert('Alert', "<p>We're sorry, these storage vials have already been added to your cart. </p>", fancyboxOptions);
}

// Commented instead of removed just in case team decides to enforce 2 vials per purchase in cart in the future.
/*function alertMoreThanAvailIVFVials(availQty) {
	CustomAlert('Alert', "<p>We’re sorry, but we don’t have the quantity of vials you requested. Since IVF Vials are sold in packs of two, we added " + availQty + " vials to your cart.</p>", fancyboxOptions);
}*/

function updateSessionCart(element) {
	
	$.post("/cart/updatequantity/",
	{
		quantity: element.find(".qty").val(),
		quantityType: element.attr('data-item-id'),
		quantityDescription: element.attr('data-item-desc'),
		isShipFromStorage: !element.find(".detail-ship").parent().hasClass("hidden"),
		items: JSON.stringify($("#header-cart .cart-item").map(function (i, el) {
			var $el = $(el);
			var tempPrice = $el.find(".price").text().replace(/,/g, '');
			return {
				'TypeDetail': $el.attr("data-item-id"),
				'TypeDescription': $el.attr("data-item-desc"),
				'Price': 0 + $el.find(".price").text().replace(/,/g, ''),
				'Quantity': $el.find(".qty").val(),
				'AvailableQuantity': $el.find("option").last().val(), //maximum quantity is last option
				'Type': "Item", // G/L Account,Item,Resource,Fixed Asset,Charge
			}
		}).toArray())
	});
}

// // doesn't add, it replaces which isn't correct
function updateSessionWithQty(qty, vialType, availQty, contractNo, locationCode, isShipFromStorage)
{
	$.post("/cart/updatequantity/",
	{
		quantity: qty,
		quantityType: vialType,
		isShipFromStorage: isShipFromStorage,
		items: JSON.stringify($("#header-cart .cart-item").map(function (i, el) {
			var $el = $(el);
			return {
				'TypeDetail': $el.attr("data-item-id"),
				'TypeDescription': $el.attr("data-item-desc"),
				'price': isShipFromStorage? "0" : $el.find(".price").text().replace(/,/g, ''),
				'Quantity': $el.find(".qty").val(),
				'AvailableQuantity': $el.attr("data-item-id") == vialType ? availQty : $el.find("option").last().val(),
				'Type': "Item", // G/L Account,Item,Resource,Fixed Asset,Charge,
				'ContractNo': contractNo,
				'LocationCode': locationCode,
			}
		}).toArray())
	});
}

$(document).ready(function () {
	

	//Checkout
    $("#header-cart .checkout.btn").click(function () {
        $('#header-cart .checkout.btn').attr("disabled", true);
		$("#header-cart .checkout-wrp .fa-spinner").show();
		window.location = "/cart";
		createCookie("vialTime", Date.now());
	});


	//More Info
	$("#header-cart .more-link").click(function (e) {
	    e.stopPropagation();
		$(".more-details").toggle("normal")
	});

	
	//Remove Item
	$("#header-cart").on("click", ".removeItem", function (e) {
		var thisItem = $(this).closest(".cart-item");
		var headerCart = $("#header-cart");
		//update cart total count in header
		thisQty = parseInt(thisItem.find(".qty").val());
		var shipable = false;
		if ($("#header-cart .active-cart")[0].className.includes("shipment")) {
			shipable = true;
		}
		var cartItemQty = parseInt($(".cart-wrp .cart-item-qty").first().text()) - thisQty;
		$(".cart-wrp .cart-item-qty").text(cartItemQty);
		updateUpsellVials();
		thisItem.remove();

		//Empty Cart
		if (cartItemQty == 0) {
			setEmptyCart(headerCart, shipable);
		    eraseCookie("vialTime");
		    $.post("/cart/removevials/");
		}
		else{
			updateSessionCart(thisItem); //update session
		}
	});

	//Item Quantity change (select dropdown)
	$("#header-cart").on("change", "select.qty", function () {
		var thisItem = $(this).closest(".cart-item");
		var headerCart = thisItem.closest("#header-cart");
		var previousQty = thisItem.find("input[name=hdnCurrentQty]").val();

		//validate total 
		var cartItemQty = 0;
		var qty = parseInt(thisItem.find(".qty").val());
		headerCart.find(".cart-item").not(thisItem).find(".qty").each(function () { cartItemQty += parseInt(this.value) });

		if (cartItemQty + qty > MAX_VIALS) {
			thisItem.find(".qty").val(previousQty); //return to previous quantity
			alertMaxVails();
		}
		else {
			thisItem.find("input[name=hdnCurrentQty]").val(qty);
			//update subtotal
			var price = parseInt($(".cart-item").first().find(".price").text().replace(',', ''));
			thisItem.find(".sub-total").text((price * qty).toStringWithCommas());

			updateHeaderCartItemCount(headerCart);
			updateSessionCart(thisItem); //update session

			var donorId = $(".donor-no") ? ($(".donor-no")[0] !== undefined ? $(".donor-no")[0].innerText : 'Could not process donor number') : '';

			let props = {
				donor_id: donorId,
				price: parseFloat(price),
				quantity: parseInt(previousQty),
				value: parseFloat(previousQty * price),
				new_quantity: parseInt(qty),
				new_value: parseFloat(qty * price),
				product_name: thisItem.attr("data-item-desc")
			};
			analyticsTrack("Quantity Updated", props);
		}
	});


	// === Show/Hide Cart Summary ===
	

	//close on page click
	$("body").bind("click touchstart", function (e) {
		if ($(e.target).closest(".cart-wrp").length == 0) {
			hideCart();
		}
	});

	//toggle view on Icon Click
	$(".cart-link").click(function () {
		var $this = $(this);
		var $headerCart = $("#header-cart");

		var isCartEmpty = $("#header-cart .active-cart")[0].className.includes("hidden");
		var isMessageHidden = $("#header-cart .empty-cart")[0].className.includes("hidden");

		if (isCartEmpty && isMessageHidden) {
			$headerCart.find(".empty-cart").removeClass("hidden");
			showCart();
			$headerCart.find("#hdnCartClicked").val("true");
		} else if ($headerCart.is(":visible")) {
			hideCart();
			$headerCart.find("#hdnCartClicked").val("false");
		} else {
			showCart();
			$headerCart.find("#hdnCartClicked").val("true");
		}

		//clearTimeout(cartTimer);
	});

	//toggle view on Hover
	$(".cart-wrp").hover(
		function () {
			$headerCart = $(this).find("#header-cart");
			//already open
			if (!$headerCart.is(":visible")) {
				hoverTimer = setTimeout(function () {
					showCart();
				}, 1000);
			}
			clearTimeout(cartTimer);
		},
		function () {
			clearTimeout(hoverTimer);
			if ($("#hdnCartClicked").val() == "false" ) {
				hideCart();
			}
		}
	);
	
	$(".cart-wrp, #fancybox-close").click(
		function (e) {
			e.stopPropagation(); //prevent click (on body) from closing cart}
		});

	updateHeaderCartItemCount($("#header-cart"));
	updateHeaderCartFromSession();


});;
function getQueryStringParameterByName(name, url) {
	if (!url) url = window.location.href;
	name = name.replace(/[\[\]]/g, "\\$&");
	var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
	if (!results) return "";
	if (!results[2]) return '';
	return decodeURIComponent(results[2].replace(/\+/g, " "));
}

//URL - leave empty to use current url
function UpdateQueryString(key, value, url) {
    if (!url) url = window.location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null)
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
        else
            return url;
    }
};
// Helper Method
/**
* Wrapper for forms that require a Recaptcha check
* @param {string} action
* @param {void} callback
* @returns {<Promise> string}
*/
function captchaCheck(action, callback) {
    const promise = new Promise((resolve, reject) => {
        grecaptcha.ready(() =>
            grecaptcha.execute(captchaKey, { action }).then(token => {
                resolve(token);
            }, reject)
        );
    }).then(token => callback(token)).catch(err => {
        throw err;
    });
    return promise;
};
/*
 AngularJS v1.4.0
 (c) 2010-2015 Google, Inc. http://angularjs.org
 License: MIT
*/
(function(N,W,u){'use strict';function F(b){return function(){var a=arguments[0],c;c="["+(b?b+":":"")+a+"] http://errors.angularjs.org/1.4.0/"+(b?b+"/":"")+a;for(a=1;a<arguments.length;a++){c=c+(1==a?"?":"&")+"p"+(a-1)+"=";var d=encodeURIComponent,e;e=arguments[a];e="function"==typeof e?e.toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof e?"undefined":"string"!=typeof e?JSON.stringify(e):e;c+=d(e)}return Error(c)}}function Da(b){if(null==b||Ta(b))return!1;var a="length"in Object(b)&&b.length;
return b.nodeType===pa&&a?!0:L(b)||K(b)||0===a||"number"===typeof a&&0<a&&a-1 in b}function n(b,a,c){var d,e;if(b)if(G(b))for(d in b)"prototype"==d||"length"==d||"name"==d||b.hasOwnProperty&&!b.hasOwnProperty(d)||a.call(c,b[d],d,b);else if(K(b)||Da(b)){var f="object"!==typeof b;d=0;for(e=b.length;d<e;d++)(f||d in b)&&a.call(c,b[d],d,b)}else if(b.forEach&&b.forEach!==n)b.forEach(a,c,b);else if(nc(b))for(d in b)a.call(c,b[d],d,b);else if("function"===typeof b.hasOwnProperty)for(d in b)b.hasOwnProperty(d)&&
a.call(c,b[d],d,b);else for(d in b)kb.call(b,d)&&a.call(c,b[d],d,b);return b}function oc(b,a,c){for(var d=Object.keys(b).sort(),e=0;e<d.length;e++)a.call(c,b[d[e]],d[e]);return d}function pc(b){return function(a,c){b(c,a)}}function Td(){return++lb}function qc(b,a){a?b.$$hashKey=a:delete b.$$hashKey}function Nb(b,a,c){for(var d=b.$$hashKey,e=0,f=a.length;e<f;++e){var g=a[e];if(C(g)||G(g))for(var h=Object.keys(g),l=0,k=h.length;l<k;l++){var m=h[l],r=g[m];c&&C(r)?(C(b[m])||(b[m]=K(r)?[]:{}),Nb(b[m],
[r],!0)):b[m]=r}}qc(b,d);return b}function Q(b){return Nb(b,ra.call(arguments,1),!1)}function Ud(b){return Nb(b,ra.call(arguments,1),!0)}function Y(b){return parseInt(b,10)}function Ob(b,a){return Q(Object.create(b),a)}function w(){}function Ua(b){return b}function qa(b){return function(){return b}}function v(b){return"undefined"===typeof b}function y(b){return"undefined"!==typeof b}function C(b){return null!==b&&"object"===typeof b}function nc(b){return null!==b&&"object"===typeof b&&!rc(b)}function L(b){return"string"===
typeof b}function V(b){return"number"===typeof b}function da(b){return"[object Date]"===sa.call(b)}function G(b){return"function"===typeof b}function Va(b){return"[object RegExp]"===sa.call(b)}function Ta(b){return b&&b.window===b}function Wa(b){return b&&b.$evalAsync&&b.$watch}function Xa(b){return"boolean"===typeof b}function sc(b){return!(!b||!(b.nodeName||b.prop&&b.attr&&b.find))}function Vd(b){var a={};b=b.split(",");var c;for(c=0;c<b.length;c++)a[b[c]]=!0;return a}function ta(b){return E(b.nodeName||
b[0]&&b[0].nodeName)}function Ya(b,a){var c=b.indexOf(a);0<=c&&b.splice(c,1);return c}function ua(b,a,c,d){function e(a,b,c,d,e){var f=ua(b,null,d,e);C(b)&&(d.push(b),e.push(f));c[a]=f}if(Ta(b)||Wa(b))throw Ea("cpws");if(tc.test(sa.call(a)))throw Ea("cpta");if(a){if(b===a)throw Ea("cpi");c=c||[];d=d||[];if(C(b)){var f=c.indexOf(b);if(-1!==f)return d[f];c.push(b);d.push(a)}var g;if(K(b))for(f=a.length=0;f<b.length;f++)g=ua(b[f],null,c,d),C(b[f])&&(c.push(b[f]),d.push(g)),a.push(g);else{f=a.$$hashKey;
K(a)?a.length=0:n(a,function(b,c){delete a[c]});if(nc(b))for(g in b)e(g,b[g],a,c,d);else if(b&&"function"===typeof b.hasOwnProperty)for(g in b)b.hasOwnProperty(g)&&e(g,b[g],a,c,d);else for(g in b)kb.call(b,g)&&e(g,b[g],a,c,d);qc(a,f)}}else if(a=b)K(b)?a=ua(b,[],c,d):tc.test(sa.call(b))?a=new b.constructor(b):da(b)?a=new Date(b.getTime()):Va(b)?(a=new RegExp(b.source,b.toString().match(/[^\/]*$/)[0]),a.lastIndex=b.lastIndex):C(b)&&(g=Object.create(rc(b)),a=ua(b,g,c,d));return a}function fa(b,a){if(K(b)){a=
a||[];for(var c=0,d=b.length;c<d;c++)a[c]=b[c]}else if(C(b))for(c in a=a||{},b)if("$"!==c.charAt(0)||"$"!==c.charAt(1))a[c]=b[c];return a||b}function ka(b,a){if(b===a)return!0;if(null===b||null===a)return!1;if(b!==b&&a!==a)return!0;var c=typeof b,d;if(c==typeof a&&"object"==c)if(K(b)){if(!K(a))return!1;if((c=b.length)==a.length){for(d=0;d<c;d++)if(!ka(b[d],a[d]))return!1;return!0}}else{if(da(b))return da(a)?ka(b.getTime(),a.getTime()):!1;if(Va(b))return Va(a)?b.toString()==a.toString():!1;if(Wa(b)||
Wa(a)||Ta(b)||Ta(a)||K(a)||da(a)||Va(a))return!1;c=ga();for(d in b)if("$"!==d.charAt(0)&&!G(b[d])){if(!ka(b[d],a[d]))return!1;c[d]=!0}for(d in a)if(!(d in c||"$"===d.charAt(0)||a[d]===u||G(a[d])))return!1;return!0}return!1}function Za(b,a,c){return b.concat(ra.call(a,c))}function uc(b,a){var c=2<arguments.length?ra.call(arguments,2):[];return!G(a)||a instanceof RegExp?a:c.length?function(){return arguments.length?a.apply(b,Za(c,arguments,0)):a.apply(b,c)}:function(){return arguments.length?a.apply(b,
arguments):a.call(b)}}function Wd(b,a){var c=a;"string"===typeof b&&"$"===b.charAt(0)&&"$"===b.charAt(1)?c=u:Ta(a)?c="$WINDOW":a&&W===a?c="$DOCUMENT":Wa(a)&&(c="$SCOPE");return c}function $a(b,a){if("undefined"===typeof b)return u;V(a)||(a=a?2:null);return JSON.stringify(b,Wd,a)}function vc(b){return L(b)?JSON.parse(b):b}function wc(b,a){var c=Date.parse("Jan 01, 1970 00:00:00 "+b)/6E4;return isNaN(c)?a:c}function Pb(b,a,c){c=c?-1:1;var d=wc(a,b.getTimezoneOffset());a=b;b=c*(d-b.getTimezoneOffset());
a=new Date(a.getTime());a.setMinutes(a.getMinutes()+b);return a}function va(b){b=z(b).clone();try{b.empty()}catch(a){}var c=z("<div>").append(b).html();try{return b[0].nodeType===ab?E(c):c.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/,function(a,b){return"<"+E(b)})}catch(d){return E(c)}}function xc(b){try{return decodeURIComponent(b)}catch(a){}}function yc(b){var a={},c,d;n((b||"").split("&"),function(b){b&&(c=b.replace(/\+/g,"%20").split("="),d=xc(c[0]),y(d)&&(b=y(c[1])?xc(c[1]):!0,kb.call(a,d)?K(a[d])?
a[d].push(b):a[d]=[a[d],b]:a[d]=b))});return a}function Qb(b){var a=[];n(b,function(b,d){K(b)?n(b,function(b){a.push(ia(d,!0)+(!0===b?"":"="+ia(b,!0)))}):a.push(ia(d,!0)+(!0===b?"":"="+ia(b,!0)))});return a.length?a.join("&"):""}function mb(b){return ia(b,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function ia(b,a){return encodeURIComponent(b).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%3B/gi,";").replace(/%20/g,a?"%20":"+")}
function Xd(b,a){var c,d,e=Na.length;for(d=0;d<e;++d)if(c=Na[d]+a,L(c=b.getAttribute(c)))return c;return null}function Yd(b,a){var c,d,e={};n(Na,function(a){a+="app";!c&&b.hasAttribute&&b.hasAttribute(a)&&(c=b,d=b.getAttribute(a))});n(Na,function(a){a+="app";var e;!c&&(e=b.querySelector("["+a.replace(":","\\:")+"]"))&&(c=e,d=e.getAttribute(a))});c&&(e.strictDi=null!==Xd(c,"strict-di"),a(c,d?[d]:[],e))}function zc(b,a,c){C(c)||(c={});c=Q({strictDi:!1},c);var d=function(){b=z(b);if(b.injector()){var d=
b[0]===W?"document":va(b);throw Ea("btstrpd",d.replace(/</,"&lt;").replace(/>/,"&gt;"));}a=a||[];a.unshift(["$provide",function(a){a.value("$rootElement",b)}]);c.debugInfoEnabled&&a.push(["$compileProvider",function(a){a.debugInfoEnabled(!0)}]);a.unshift("ng");d=bb(a,c.strictDi);d.invoke(["$rootScope","$rootElement","$compile","$injector",function(a,b,c,d){a.$apply(function(){b.data("$injector",d);c(b)(a)})}]);return d},e=/^NG_ENABLE_DEBUG_INFO!/,f=/^NG_DEFER_BOOTSTRAP!/;N&&e.test(N.name)&&(c.debugInfoEnabled=
!0,N.name=N.name.replace(e,""));if(N&&!f.test(N.name))return d();N.name=N.name.replace(f,"");aa.resumeBootstrap=function(b){n(b,function(b){a.push(b)});return d()};G(aa.resumeDeferredBootstrap)&&aa.resumeDeferredBootstrap()}function Zd(){N.name="NG_ENABLE_DEBUG_INFO!"+N.name;N.location.reload()}function $d(b){b=aa.element(b).injector();if(!b)throw Ea("test");return b.get("$$testability")}function Ac(b,a){a=a||"_";return b.replace(ae,function(b,d){return(d?a:"")+b.toLowerCase()})}function be(){var b;
if(!Bc){var a=nb();la=N.jQuery;y(a)&&(la=null===a?u:N[a]);la&&la.fn.on?(z=la,Q(la.fn,{scope:Oa.scope,isolateScope:Oa.isolateScope,controller:Oa.controller,injector:Oa.injector,inheritedData:Oa.inheritedData}),b=la.cleanData,la.cleanData=function(a){var d;if(Rb)Rb=!1;else for(var e=0,f;null!=(f=a[e]);e++)(d=la._data(f,"events"))&&d.$destroy&&la(f).triggerHandler("$destroy");b(a)}):z=R;aa.element=z;Bc=!0}}function Sb(b,a,c){if(!b)throw Ea("areq",a||"?",c||"required");return b}function Pa(b,a,c){c&&
K(b)&&(b=b[b.length-1]);Sb(G(b),a,"not a function, got "+(b&&"object"===typeof b?b.constructor.name||"Object":typeof b));return b}function Qa(b,a){if("hasOwnProperty"===b)throw Ea("badname",a);}function Cc(b,a,c){if(!a)return b;a=a.split(".");for(var d,e=b,f=a.length,g=0;g<f;g++)d=a[g],b&&(b=(e=b)[d]);return!c&&G(b)?uc(e,b):b}function ob(b){var a=b[0];b=b[b.length-1];var c=[a];do{a=a.nextSibling;if(!a)break;c.push(a)}while(a!==b);return z(c)}function ga(){return Object.create(null)}function ce(b){function a(a,
b,c){return a[b]||(a[b]=c())}var c=F("$injector"),d=F("ng");b=a(b,"angular",Object);b.$$minErr=b.$$minErr||F;return a(b,"module",function(){var b={};return function(f,g,h){if("hasOwnProperty"===f)throw d("badname","module");g&&b.hasOwnProperty(f)&&(b[f]=null);return a(b,f,function(){function a(c,d,e,f){f||(f=b);return function(){f[e||"push"]([c,d,arguments]);return A}}if(!g)throw c("nomod",f);var b=[],d=[],e=[],s=a("$injector","invoke","push",d),A={_invokeQueue:b,_configBlocks:d,_runBlocks:e,requires:g,
name:f,provider:a("$provide","provider"),factory:a("$provide","factory"),service:a("$provide","service"),value:a("$provide","value"),constant:a("$provide","constant","unshift"),decorator:a("$provide","decorator"),animation:a("$animateProvider","register"),filter:a("$filterProvider","register"),controller:a("$controllerProvider","register"),directive:a("$compileProvider","directive"),config:s,run:function(a){e.push(a);return this}};h&&s(h);return A})}})}function de(b){Q(b,{bootstrap:zc,copy:ua,extend:Q,
merge:Ud,equals:ka,element:z,forEach:n,injector:bb,noop:w,bind:uc,toJson:$a,fromJson:vc,identity:Ua,isUndefined:v,isDefined:y,isString:L,isFunction:G,isObject:C,isNumber:V,isElement:sc,isArray:K,version:ee,isDate:da,lowercase:E,uppercase:pb,callbacks:{counter:0},getTestability:$d,$$minErr:F,$$csp:cb,reloadWithDebugInfo:Zd});db=ce(N);try{db("ngLocale")}catch(a){db("ngLocale",[]).provider("$locale",fe)}db("ng",["ngLocale"],["$provide",function(a){a.provider({$$sanitizeUri:ge});a.provider("$compile",
Dc).directive({a:he,input:Ec,textarea:Ec,form:ie,script:je,select:ke,style:le,option:me,ngBind:ne,ngBindHtml:oe,ngBindTemplate:pe,ngClass:qe,ngClassEven:re,ngClassOdd:se,ngCloak:te,ngController:ue,ngForm:ve,ngHide:we,ngIf:xe,ngInclude:ye,ngInit:ze,ngNonBindable:Ae,ngPluralize:Be,ngRepeat:Ce,ngShow:De,ngStyle:Ee,ngSwitch:Fe,ngSwitchWhen:Ge,ngSwitchDefault:He,ngOptions:Ie,ngTransclude:Je,ngModel:Ke,ngList:Le,ngChange:Me,pattern:Fc,ngPattern:Fc,required:Gc,ngRequired:Gc,minlength:Hc,ngMinlength:Hc,maxlength:Ic,
ngMaxlength:Ic,ngValue:Ne,ngModelOptions:Oe}).directive({ngInclude:Pe}).directive(qb).directive(Jc);a.provider({$anchorScroll:Qe,$animate:Re,$$animateQueue:Se,$$AnimateRunner:Te,$browser:Ue,$cacheFactory:Ve,$controller:We,$document:Xe,$exceptionHandler:Ye,$filter:Kc,$interpolate:Ze,$interval:$e,$http:af,$httpParamSerializer:bf,$httpParamSerializerJQLike:cf,$httpBackend:df,$location:ef,$log:ff,$parse:gf,$rootScope:hf,$q:jf,$$q:kf,$sce:lf,$sceDelegate:mf,$sniffer:nf,$templateCache:of,$templateRequest:pf,
$$testability:qf,$timeout:rf,$window:sf,$$rAF:tf,$$asyncCallback:uf,$$jqLite:vf,$$HashMap:wf,$$cookieReader:xf})}])}function eb(b){return b.replace(yf,function(a,b,d,e){return e?d.toUpperCase():d}).replace(zf,"Moz$1")}function Lc(b){b=b.nodeType;return b===pa||!b||9===b}function Mc(b,a){var c,d,e=a.createDocumentFragment(),f=[];if(Tb.test(b)){c=c||e.appendChild(a.createElement("div"));d=(Af.exec(b)||["",""])[1].toLowerCase();d=ma[d]||ma._default;c.innerHTML=d[1]+b.replace(Bf,"<$1></$2>")+d[2];for(d=
d[0];d--;)c=c.lastChild;f=Za(f,c.childNodes);c=e.firstChild;c.textContent=""}else f.push(a.createTextNode(b));e.textContent="";e.innerHTML="";n(f,function(a){e.appendChild(a)});return e}function R(b){if(b instanceof R)return b;var a;L(b)&&(b=T(b),a=!0);if(!(this instanceof R)){if(a&&"<"!=b.charAt(0))throw Ub("nosel");return new R(b)}if(a){a=W;var c;b=(c=Cf.exec(b))?[a.createElement(c[1])]:(c=Mc(b,a))?c.childNodes:[]}Nc(this,b)}function Vb(b){return b.cloneNode(!0)}function rb(b,a){a||sb(b);if(b.querySelectorAll)for(var c=
b.querySelectorAll("*"),d=0,e=c.length;d<e;d++)sb(c[d])}function Oc(b,a,c,d){if(y(d))throw Ub("offargs");var e=(d=tb(b))&&d.events,f=d&&d.handle;if(f)if(a)n(a.split(" "),function(a){if(y(c)){var d=e[a];Ya(d||[],c);if(d&&0<d.length)return}b.removeEventListener(a,f,!1);delete e[a]});else for(a in e)"$destroy"!==a&&b.removeEventListener(a,f,!1),delete e[a]}function sb(b,a){var c=b.ng339,d=c&&ub[c];d&&(a?delete d.data[a]:(d.handle&&(d.events.$destroy&&d.handle({},"$destroy"),Oc(b)),delete ub[c],b.ng339=
u))}function tb(b,a){var c=b.ng339,c=c&&ub[c];a&&!c&&(b.ng339=c=++Df,c=ub[c]={events:{},data:{},handle:u});return c}function Wb(b,a,c){if(Lc(b)){var d=y(c),e=!d&&a&&!C(a),f=!a;b=(b=tb(b,!e))&&b.data;if(d)b[a]=c;else{if(f)return b;if(e)return b&&b[a];Q(b,a)}}}function vb(b,a){return b.getAttribute?-1<(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").indexOf(" "+a+" "):!1}function wb(b,a){a&&b.setAttribute&&n(a.split(" "),function(a){b.setAttribute("class",T((" "+(b.getAttribute("class")||
"")+" ").replace(/[\n\t]/g," ").replace(" "+T(a)+" "," ")))})}function xb(b,a){if(a&&b.setAttribute){var c=(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ");n(a.split(" "),function(a){a=T(a);-1===c.indexOf(" "+a+" ")&&(c+=a+" ")});b.setAttribute("class",T(c))}}function Nc(b,a){if(a)if(a.nodeType)b[b.length++]=a;else{var c=a.length;if("number"===typeof c&&a.window!==a){if(c)for(var d=0;d<c;d++)b[b.length++]=a[d]}else b[b.length++]=a}}function Pc(b,a){return yb(b,"$"+(a||"ngController")+
"Controller")}function yb(b,a,c){9==b.nodeType&&(b=b.documentElement);for(a=K(a)?a:[a];b;){for(var d=0,e=a.length;d<e;d++)if((c=z.data(b,a[d]))!==u)return c;b=b.parentNode||11===b.nodeType&&b.host}}function Qc(b){for(rb(b,!0);b.firstChild;)b.removeChild(b.firstChild)}function Xb(b,a){a||rb(b);var c=b.parentNode;c&&c.removeChild(b)}function Ef(b,a){a=a||N;if("complete"===a.document.readyState)a.setTimeout(b);else z(a).on("load",b)}function Rc(b,a){var c=zb[a.toLowerCase()];return c&&Sc[ta(b)]&&c}function Ff(b,
a){var c=b.nodeName;return("INPUT"===c||"TEXTAREA"===c)&&Tc[a]}function Gf(b,a){var c=function(c,e){c.isDefaultPrevented=function(){return c.defaultPrevented};var f=a[e||c.type],g=f?f.length:0;if(g){if(v(c.immediatePropagationStopped)){var h=c.stopImmediatePropagation;c.stopImmediatePropagation=function(){c.immediatePropagationStopped=!0;c.stopPropagation&&c.stopPropagation();h&&h.call(c)}}c.isImmediatePropagationStopped=function(){return!0===c.immediatePropagationStopped};1<g&&(f=fa(f));for(var l=
0;l<g;l++)c.isImmediatePropagationStopped()||f[l].call(b,c)}};c.elem=b;return c}function vf(){this.$get=function(){return Q(R,{hasClass:function(b,a){b.attr&&(b=b[0]);return vb(b,a)},addClass:function(b,a){b.attr&&(b=b[0]);return xb(b,a)},removeClass:function(b,a){b.attr&&(b=b[0]);return wb(b,a)}})}}function Fa(b,a){var c=b&&b.$$hashKey;if(c)return"function"===typeof c&&(c=b.$$hashKey()),c;c=typeof b;return c="function"==c||"object"==c&&null!==b?b.$$hashKey=c+":"+(a||Td)():c+":"+b}function Ra(b,a){if(a){var c=
0;this.nextUid=function(){return++c}}n(b,this.put,this)}function Hf(b){return(b=b.toString().replace(Uc,"").match(Vc))?"function("+(b[1]||"").replace(/[\s\r\n]+/," ")+")":"fn"}function bb(b,a){function c(a){return function(b,c){if(C(b))n(b,pc(a));else return a(b,c)}}function d(a,b){Qa(a,"service");if(G(b)||K(b))b=s.instantiate(b);if(!b.$get)throw Ga("pget",a);return r[a+"Provider"]=b}function e(a,b){return function(){var c=H.invoke(b,this);if(v(c))throw Ga("undef",a);return c}}function f(a,b,c){return d(a,
{$get:!1!==c?e(a,b):b})}function g(a){var b=[],c;n(a,function(a){function d(a){var b,c;b=0;for(c=a.length;b<c;b++){var e=a[b],f=s.get(e[0]);f[e[1]].apply(f,e[2])}}if(!m.get(a)){m.put(a,!0);try{L(a)?(c=db(a),b=b.concat(g(c.requires)).concat(c._runBlocks),d(c._invokeQueue),d(c._configBlocks)):G(a)?b.push(s.invoke(a)):K(a)?b.push(s.invoke(a)):Pa(a,"module")}catch(e){throw K(a)&&(a=a[a.length-1]),e.message&&e.stack&&-1==e.stack.indexOf(e.message)&&(e=e.message+"\n"+e.stack),Ga("modulerr",a,e.stack||e.message||
e);}}});return b}function h(b,c){function d(a,e){if(b.hasOwnProperty(a)){if(b[a]===l)throw Ga("cdep",a+" <- "+k.join(" <- "));return b[a]}try{return k.unshift(a),b[a]=l,b[a]=c(a,e)}catch(f){throw b[a]===l&&delete b[a],f;}finally{k.shift()}}function e(b,c,f,g){"string"===typeof f&&(g=f,f=null);var h=[],k=bb.$$annotate(b,a,g),l,s,m;s=0;for(l=k.length;s<l;s++){m=k[s];if("string"!==typeof m)throw Ga("itkn",m);h.push(f&&f.hasOwnProperty(m)?f[m]:d(m,g))}K(b)&&(b=b[l]);return b.apply(c,h)}return{invoke:e,
instantiate:function(a,b,c){var d=Object.create((K(a)?a[a.length-1]:a).prototype||null);a=e(a,d,b,c);return C(a)||G(a)?a:d},get:d,annotate:bb.$$annotate,has:function(a){return r.hasOwnProperty(a+"Provider")||b.hasOwnProperty(a)}}}a=!0===a;var l={},k=[],m=new Ra([],!0),r={$provide:{provider:c(d),factory:c(f),service:c(function(a,b){return f(a,["$injector",function(a){return a.instantiate(b)}])}),value:c(function(a,b){return f(a,qa(b),!1)}),constant:c(function(a,b){Qa(a,"constant");r[a]=b;A[a]=b}),
decorator:function(a,b){var c=s.get(a+"Provider"),d=c.$get;c.$get=function(){var a=H.invoke(d,c);return H.invoke(b,null,{$delegate:a})}}}},s=r.$injector=h(r,function(a,b){aa.isString(b)&&k.push(b);throw Ga("unpr",k.join(" <- "));}),A={},H=A.$injector=h(A,function(a,b){var c=s.get(a+"Provider",b);return H.invoke(c.$get,c,u,a)});n(g(b),function(a){H.invoke(a||w)});return H}function Qe(){var b=!0;this.disableAutoScrolling=function(){b=!1};this.$get=["$window","$location","$rootScope",function(a,c,d){function e(a){var b=
null;Array.prototype.some.call(a,function(a){if("a"===ta(a))return b=a,!0});return b}function f(b){if(b){b.scrollIntoView();var c;c=g.yOffset;G(c)?c=c():sc(c)?(c=c[0],c="fixed"!==a.getComputedStyle(c).position?0:c.getBoundingClientRect().bottom):V(c)||(c=0);c&&(b=b.getBoundingClientRect().top,a.scrollBy(0,b-c))}else a.scrollTo(0,0)}function g(a){a=L(a)?a:c.hash();var b;a?(b=h.getElementById(a))?f(b):(b=e(h.getElementsByName(a)))?f(b):"top"===a&&f(null):f(null)}var h=a.document;b&&d.$watch(function(){return c.hash()},
function(a,b){a===b&&""===a||Ef(function(){d.$evalAsync(g)})});return g}]}function fb(b,a){if(!b&&!a)return"";if(!b)return a;if(!a)return b;K(b)&&(b=b.join(" "));K(a)&&(a=a.join(" "));return b+" "+a}function If(b){L(b)&&(b=b.split(" "));var a=ga();n(b,function(b){b.length&&(a[b]=!0)});return a}function Ha(b){return C(b)?b:{}}function uf(){this.$get=["$$rAF","$timeout",function(b,a){return b.supported?function(a){return b(a)}:function(b){return a(b,0,!1)}}]}function Jf(b,a,c,d){function e(a){try{a.apply(null,
ra.call(arguments,1))}finally{if(H--,0===H)for(;M.length;)try{M.pop()()}catch(b){c.error(b)}}}function f(){g();h()}function g(){a:{try{t=m.state;break a}catch(a){}t=void 0}t=v(t)?null:t;ka(t,D)&&(t=D);D=t}function h(){if(x!==l.url()||p!==t)x=l.url(),p=t,n(B,function(a){a(l.url(),t)})}var l=this,k=b.location,m=b.history,r=b.setTimeout,s=b.clearTimeout,A={};l.isMock=!1;var H=0,M=[];l.$$completeOutstandingRequest=e;l.$$incOutstandingRequestCount=function(){H++};l.notifyWhenNoOutstandingRequests=function(a){0===
H?a():M.push(a)};var t,p,x=k.href,q=a.find("base"),I=null;g();p=t;l.url=function(a,c,e){v(e)&&(e=null);k!==b.location&&(k=b.location);m!==b.history&&(m=b.history);if(a){var f=p===e;if(x===a&&(!d.history||f))return l;var h=x&&Ia(x)===Ia(a);x=a;p=e;!d.history||h&&f?(h||(I=a),c?k.replace(a):h?(c=k,e=a.indexOf("#"),a=-1===e?"":a.substr(e+1),c.hash=a):k.href=a):(m[c?"replaceState":"pushState"](e,"",a),g(),p=t);return l}return I||k.href.replace(/%27/g,"'")};l.state=function(){return t};var B=[],O=!1,D=
null;l.onUrlChange=function(a){if(!O){if(d.history)z(b).on("popstate",f);z(b).on("hashchange",f);O=!0}B.push(a);return a};l.$$applicationDestroyed=function(){z(b).off("hashchange popstate",f)};l.$$checkUrlChange=h;l.baseHref=function(){var a=q.attr("href");return a?a.replace(/^(https?\:)?\/\/[^\/]*/,""):""};l.defer=function(a,b){var c;H++;c=r(function(){delete A[c];e(a)},b||0);A[c]=!0;return c};l.defer.cancel=function(a){return A[a]?(delete A[a],s(a),e(w),!0):!1}}function Ue(){this.$get=["$window",
"$log","$sniffer","$document",function(b,a,c,d){return new Jf(b,d,a,c)}]}function Ve(){this.$get=function(){function b(b,d){function e(a){a!=r&&(s?s==a&&(s=a.n):s=a,f(a.n,a.p),f(a,r),r=a,r.n=null)}function f(a,b){a!=b&&(a&&(a.p=b),b&&(b.n=a))}if(b in a)throw F("$cacheFactory")("iid",b);var g=0,h=Q({},d,{id:b}),l={},k=d&&d.capacity||Number.MAX_VALUE,m={},r=null,s=null;return a[b]={put:function(a,b){if(!v(b)){if(k<Number.MAX_VALUE){var c=m[a]||(m[a]={key:a});e(c)}a in l||g++;l[a]=b;g>k&&this.remove(s.key);
return b}},get:function(a){if(k<Number.MAX_VALUE){var b=m[a];if(!b)return;e(b)}return l[a]},remove:function(a){if(k<Number.MAX_VALUE){var b=m[a];if(!b)return;b==r&&(r=b.p);b==s&&(s=b.n);f(b.n,b.p);delete m[a]}delete l[a];g--},removeAll:function(){l={};g=0;m={};r=s=null},destroy:function(){m=h=l=null;delete a[b]},info:function(){return Q({},h,{size:g})}}}var a={};b.info=function(){var b={};n(a,function(a,e){b[e]=a.info()});return b};b.get=function(b){return a[b]};return b}}function of(){this.$get=
["$cacheFactory",function(b){return b("templates")}]}function Dc(b,a){function c(a,b,c){var d=/^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/,e={};n(a,function(a,f){var g=a.match(d);if(!g)throw ea("iscp",b,f,a,c?"controller bindings definition":"isolate scope definition");e[f]={mode:g[1][0],collection:"*"===g[2],optional:"?"===g[3],attrName:g[4]||f}});return e}function d(a){var b=a.charAt(0);if(!b||b!==E(b))throw ea("baddir",a);if(a!==a.trim())throw ea("baddir",a);}var e={},f=/^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
g=/(([\w\-]+)(?:\:([^;]+))?;?)/,h=Vd("ngSrc,ngSrcset,src,srcset"),l=/^(?:(\^\^?)?(\?)?(\^\^?)?)?/,k=/^(on[a-z]+|formaction)$/;this.directive=function s(a,f){Qa(a,"directive");L(a)?(d(a),Sb(f,"directiveFactory"),e.hasOwnProperty(a)||(e[a]=[],b.factory(a+"Directive",["$injector","$exceptionHandler",function(b,d){var f=[];n(e[a],function(e,g){try{var h=b.invoke(e);G(h)?h={compile:qa(h)}:!h.compile&&h.link&&(h.compile=qa(h.link));h.priority=h.priority||0;h.index=g;h.name=h.name||a;h.require=h.require||
h.controller&&h.name;h.restrict=h.restrict||"EA";var k=h,l=h,s=h.name,m={isolateScope:null,bindToController:null};C(l.scope)&&(!0===l.bindToController?(m.bindToController=c(l.scope,s,!0),m.isolateScope={}):m.isolateScope=c(l.scope,s,!1));C(l.bindToController)&&(m.bindToController=c(l.bindToController,s,!0));if(C(m.bindToController)){var H=l.controller,ba=l.controllerAs;if(!H)throw ea("noctrl",s);var ha;a:if(ba&&L(ba))ha=ba;else{if(L(H)){var n=Wc.exec(H);if(n){ha=n[3];break a}}ha=void 0}if(!ha)throw ea("noident",
s);}var q=k.$$bindings=m;C(q.isolateScope)&&(h.$$isolateBindings=q.isolateScope);f.push(h)}catch(u){d(u)}});return f}])),e[a].push(f)):n(a,pc(s));return this};this.aHrefSanitizationWhitelist=function(b){return y(b)?(a.aHrefSanitizationWhitelist(b),this):a.aHrefSanitizationWhitelist()};this.imgSrcSanitizationWhitelist=function(b){return y(b)?(a.imgSrcSanitizationWhitelist(b),this):a.imgSrcSanitizationWhitelist()};var m=!0;this.debugInfoEnabled=function(a){return y(a)?(m=a,this):m};this.$get=["$injector",
"$interpolate","$exceptionHandler","$templateRequest","$parse","$controller","$rootScope","$document","$sce","$animate","$$sanitizeUri",function(a,b,c,d,t,p,x,q,I,B,O){function D(a,b){try{a.addClass(b)}catch(c){}}function S(a,b,c,d,e){a instanceof z||(a=z(a));n(a,function(b,c){b.nodeType==ab&&b.nodeValue.match(/\S+/)&&(a[c]=z(b).wrap("<span></span>").parent()[0])});var f=P(a,b,a,c,d,e);S.$$addScopeClass(a);var g=null;return function(b,c,d){Sb(b,"scope");d=d||{};var e=d.parentBoundTranscludeFn,h=d.transcludeControllers;
d=d.futureParentElement;e&&e.$$boundTransclude&&(e=e.$$boundTransclude);g||(g=(d=d&&d[0])?"foreignobject"!==ta(d)&&d.toString().match(/SVG/)?"svg":"html":"html");d="html"!==g?z(Yb(g,z("<div>").append(a).html())):c?Oa.clone.call(a):a;if(h)for(var l in h)d.data("$"+l+"Controller",h[l].instance);S.$$addScopeInfo(d,b);c&&c(d,b);f&&f(b,d,d,e);return d}}function P(a,b,c,d,e,f){function g(a,c,d,e){var f,l,k,m,s,B,A;if(p)for(A=Array(c.length),m=0;m<h.length;m+=3)f=h[m],A[f]=c[f];else A=c;m=0;for(s=h.length;m<
s;)if(l=A[h[m++]],c=h[m++],f=h[m++],c){if(c.scope){if(k=a.$new(),S.$$addScopeInfo(z(l),k),B=c.$$destroyBindings)c.$$destroyBindings=null,k.$on("$destroyed",B)}else k=a;B=c.transcludeOnThisElement?ba(a,c.transclude,e,c.elementTranscludeOnThisElement):!c.templateOnThisElement&&e?e:!e&&b?ba(a,b):null;c(f,k,l,d,B,c)}else f&&f(a,l.childNodes,u,e)}for(var h=[],l,k,m,s,p,B=0;B<a.length;B++){l=new aa;k=ha(a[B],[],l,0===B?d:u,e);(f=k.length?J(k,a[B],l,b,c,null,[],[],f):null)&&f.scope&&S.$$addScopeClass(l.$$element);
l=f&&f.terminal||!(m=a[B].childNodes)||!m.length?null:P(m,f?(f.transcludeOnThisElement||!f.templateOnThisElement)&&f.transclude:b);if(f||l)h.push(B,f,l),s=!0,p=p||f;f=null}return s?g:null}function ba(a,b,c,d){return function(d,e,f,g,h){d||(d=a.$new(!1,h),d.$$transcluded=!0);return b(d,e,{parentBoundTranscludeFn:c,transcludeControllers:f,futureParentElement:g})}}function ha(a,b,c,d,e){var h=c.$attr,l;switch(a.nodeType){case pa:v(b,xa(ta(a)),"E",d,e);for(var k,m,s,p=a.attributes,B=0,A=p&&p.length;B<
A;B++){var H=!1,M=!1;k=p[B];l=k.name;m=T(k.value);k=xa(l);if(s=ia.test(k))l=l.replace(Yc,"").substr(8).replace(/_(.)/g,function(a,b){return b.toUpperCase()});var P=k.replace(/(Start|End)$/,"");F(P)&&k===P+"Start"&&(H=l,M=l.substr(0,l.length-5)+"end",l=l.substr(0,l.length-6));k=xa(l.toLowerCase());h[k]=l;if(s||!c.hasOwnProperty(k))c[k]=m,Rc(a,k)&&(c[k]=!0);V(a,b,m,k,s);v(b,k,"A",d,e,H,M)}a=a.className;C(a)&&(a=a.animVal);if(L(a)&&""!==a)for(;l=g.exec(a);)k=xa(l[2]),v(b,k,"C",d,e)&&(c[k]=T(l[3])),a=
a.substr(l.index+l[0].length);break;case ab:za(b,a.nodeValue);break;case 8:try{if(l=f.exec(a.nodeValue))k=xa(l[1]),v(b,k,"M",d,e)&&(c[k]=T(l[2]))}catch(O){}}b.sort(Ja);return b}function wa(a,b,c){var d=[],e=0;if(b&&a.hasAttribute&&a.hasAttribute(b)){do{if(!a)throw ea("uterdir",b,c);a.nodeType==pa&&(a.hasAttribute(b)&&e++,a.hasAttribute(c)&&e--);d.push(a);a=a.nextSibling}while(0<e)}else d.push(a);return z(d)}function Xc(a,b,c){return function(d,e,f,g,h){e=wa(e[0],b,c);return a(d,e,f,g,h)}}function J(a,
b,d,e,f,g,h,k,m){function s(a,b,c,d){if(a){c&&(a=Xc(a,c,d));a.require=J.require;a.directiveName=w;if(t===J||J.$$isolateScope)a=Z(a,{isolateScope:!0});h.push(a)}if(b){c&&(b=Xc(b,c,d));b.require=J.require;b.directiveName=w;if(t===J||J.$$isolateScope)b=Z(b,{isolateScope:!0});k.push(b)}}function B(a,b,c,d){var e;if(L(b)){var f=b.match(l);b=b.substring(f[0].length);var g=f[1]||f[3],f="?"===f[2];"^^"===g?c=c.parent():e=(e=d&&d[b])&&e.instance;e||(d="$"+b+"Controller",e=g?c.inheritedData(d):c.data(d));if(!e&&
!f)throw ea("ctreq",b,a);}else if(K(b))for(e=[],g=0,f=b.length;g<f;g++)e[g]=B(a,b[g],c,d);return e||null}function A(a,b,c,d,e,f){var g=ga(),h;for(h in d){var l=d[h],k={$scope:l===t||l.$$isolateScope?e:f,$element:a,$attrs:b,$transclude:c},m=l.controller;"@"==m&&(m=b[l.name]);k=p(m,k,!0,l.controllerAs);g[l.name]=k;q||a.data("$"+l.name+"Controller",k.instance)}return g}function M(a,c,e,f,g,l){function m(a,b,c){var d;Wa(a)||(c=b,b=a,a=u);q&&(d=n);c||(c=q?ja.parent():ja);return g(a,b,d,c,X)}var s,p,H,
P,n,ha,ja;b===e?(f=d,ja=d.$$element):(ja=z(e),f=new aa(ja,d));t&&(P=c.$new(!0));g&&(ha=m,ha.$$boundTransclude=g);ba&&(n=A(ja,f,ha,ba,P,c));t&&(S.$$addScopeInfo(ja,P,!0,!(D&&(D===t||D===t.$$originalDirective))),S.$$addScopeClass(ja,!0),P.$$isolateBindings=t.$$isolateBindings,Y(c,f,P,P.$$isolateBindings,t,P));if(n){var x=t||O,I;x&&n[x.name]&&(p=x.$$bindings.bindToController,(H=n[x.name])&&H.identifier&&p&&(I=H,l.$$destroyBindings=Y(c,f,H.instance,p,x)));for(s in n){H=n[s];var wa=H();wa!==H.instance&&
(H.instance=wa,ja.data("$"+J.name+"Controller",wa),H===I&&(l.$$destroyBindings(),l.$$destroyBindings=Y(c,f,wa,p,x)))}}s=0;for(l=h.length;s<l;s++)p=h[s],$(p,p.isolateScope?P:c,ja,f,p.require&&B(p.directiveName,p.require,ja,n),ha);var X=c;t&&(t.template||null===t.templateUrl)&&(X=P);a&&a(X,e.childNodes,u,g);for(s=k.length-1;0<=s;s--)p=k[s],$(p,p.isolateScope?P:c,ja,f,p.require&&B(p.directiveName,p.require,ja,n),ha)}m=m||{};for(var P=-Number.MAX_VALUE,O,ba=m.controllerDirectives,t=m.newIsolateScopeDirective,
D=m.templateDirective,n=m.nonTlbTranscludeDirective,x=!1,I=!1,q=m.hasElementTranscludeDirective,X=d.$$element=z(b),J,w,v,Ja=e,za,F=0,E=a.length;F<E;F++){J=a[F];var Ab=J.$$start,Q=J.$$end;Ab&&(X=wa(b,Ab,Q));v=u;if(P>J.priority)break;if(v=J.scope)J.templateUrl||(C(v)?(N("new/isolated scope",t||O,J,X),t=J):N("new/isolated scope",t,J,X)),O=O||J;w=J.name;!J.templateUrl&&J.controller&&(v=J.controller,ba=ba||ga(),N("'"+w+"' controller",ba[w],J,X),ba[w]=J);if(v=J.transclude)x=!0,J.$$tlb||(N("transclusion",
n,J,X),n=J),"element"==v?(q=!0,P=J.priority,v=X,X=d.$$element=z(W.createComment(" "+w+": "+d[w]+" ")),b=X[0],U(f,ra.call(v,0),b),Ja=S(v,e,P,g&&g.name,{nonTlbTranscludeDirective:n})):(v=z(Vb(b)).contents(),X.empty(),Ja=S(v,e));if(J.template)if(I=!0,N("template",D,J,X),D=J,v=G(J.template)?J.template(X,d):J.template,v=fa(v),J.replace){g=J;v=Tb.test(v)?Zc(Yb(J.templateNamespace,T(v))):[];b=v[0];if(1!=v.length||b.nodeType!==pa)throw ea("tplrt",w,"");U(f,X,b);E={$attr:{}};v=ha(b,[],E);var R=a.splice(F+
1,a.length-(F+1));t&&y(v);a=a.concat(v).concat(R);$c(d,E);E=a.length}else X.html(v);if(J.templateUrl)I=!0,N("template",D,J,X),D=J,J.replace&&(g=J),M=Kf(a.splice(F,a.length-F),X,d,f,x&&Ja,h,k,{controllerDirectives:ba,newIsolateScopeDirective:t,templateDirective:D,nonTlbTranscludeDirective:n}),E=a.length;else if(J.compile)try{za=J.compile(X,d,Ja),G(za)?s(null,za,Ab,Q):za&&s(za.pre,za.post,Ab,Q)}catch(V){c(V,va(X))}J.terminal&&(M.terminal=!0,P=Math.max(P,J.priority))}M.scope=O&&!0===O.scope;M.transcludeOnThisElement=
x;M.elementTranscludeOnThisElement=q;M.templateOnThisElement=I;M.transclude=Ja;m.hasElementTranscludeDirective=q;return M}function y(a){for(var b=0,c=a.length;b<c;b++)a[b]=Ob(a[b],{$$isolateScope:!0})}function v(b,d,f,g,h,l,k){if(d===h)return null;h=null;if(e.hasOwnProperty(d)){var m;d=a.get(d+"Directive");for(var p=0,B=d.length;p<B;p++)try{m=d[p],(g===u||g>m.priority)&&-1!=m.restrict.indexOf(f)&&(l&&(m=Ob(m,{$$start:l,$$end:k})),b.push(m),h=m)}catch(A){c(A)}}return h}function F(b){if(e.hasOwnProperty(b))for(var c=
a.get(b+"Directive"),d=0,f=c.length;d<f;d++)if(b=c[d],b.multiElement)return!0;return!1}function $c(a,b){var c=b.$attr,d=a.$attr,e=a.$$element;n(a,function(d,e){"$"!=e.charAt(0)&&(b[e]&&b[e]!==d&&(d+=("style"===e?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});n(b,function(b,f){"class"==f?(D(e,b),a["class"]=(a["class"]?a["class"]+" ":"")+b):"style"==f?(e.attr("style",e.attr("style")+";"+b),a.style=(a.style?a.style+";":"")+b):"$"==f.charAt(0)||a.hasOwnProperty(f)||(a[f]=b,d[f]=c[f])})}function Kf(a,b,c,e,f,g,
h,l){var k=[],m,s,p=b[0],B=a.shift(),A=Ob(B,{templateUrl:null,transclude:null,replace:null,$$originalDirective:B}),H=G(B.templateUrl)?B.templateUrl(b,c):B.templateUrl,O=B.templateNamespace;b.empty();d(I.getTrustedResourceUrl(H)).then(function(d){var M,t;d=fa(d);if(B.replace){d=Tb.test(d)?Zc(Yb(O,T(d))):[];M=d[0];if(1!=d.length||M.nodeType!==pa)throw ea("tplrt",B.name,H);d={$attr:{}};U(e,b,M);var x=ha(M,[],d);C(B.scope)&&y(x);a=x.concat(a);$c(c,d)}else M=p,b.html(d);a.unshift(A);m=J(a,M,c,f,b,B,g,
h,l);n(e,function(a,c){a==M&&(e[c]=b[0])});for(s=P(b[0].childNodes,f);k.length;){d=k.shift();t=k.shift();var S=k.shift(),I=k.shift(),x=b[0];if(!d.$$destroyed){if(t!==p){var wa=t.className;l.hasElementTranscludeDirective&&B.replace||(x=Vb(M));U(S,z(t),x);D(z(x),wa)}t=m.transcludeOnThisElement?ba(d,m.transclude,I):I;m(s,d,x,e,t,m)}}k=null});return function(a,b,c,d,e){a=e;b.$$destroyed||(k?k.push(b,c,d,a):(m.transcludeOnThisElement&&(a=ba(b,m.transclude,e)),m(s,b,c,d,a,m)))}}function Ja(a,b){var c=b.priority-
a.priority;return 0!==c?c:a.name!==b.name?a.name<b.name?-1:1:a.index-b.index}function N(a,b,c,d){if(b)throw ea("multidir",b.name,c.name,a,va(d));}function za(a,c){var d=b(c,!0);d&&a.push({priority:0,compile:function(a){a=a.parent();var b=!!a.length;b&&S.$$addBindingClass(a);return function(a,c){var e=c.parent();b||S.$$addBindingClass(e);S.$$addBindingInfo(e,d.expressions);a.$watch(d,function(a){c[0].nodeValue=a})}}})}function Yb(a,b){a=E(a||"html");switch(a){case "svg":case "math":var c=W.createElement("div");
c.innerHTML="<"+a+">"+b+"</"+a+">";return c.childNodes[0].childNodes;default:return b}}function R(a,b){if("srcdoc"==b)return I.HTML;var c=ta(a);if("xlinkHref"==b||"form"==c&&"action"==b||"img"!=c&&("src"==b||"ngSrc"==b))return I.RESOURCE_URL}function V(a,c,d,e,f){var g=R(a,e);f=h[e]||f;var l=b(d,!0,g,f);if(l){if("multiple"===e&&"select"===ta(a))throw ea("selmulti",va(a));c.push({priority:100,compile:function(){return{pre:function(a,c,h){c=h.$$observers||(h.$$observers={});if(k.test(e))throw ea("nodomevents");
var m=h[e];m!==d&&(l=m&&b(m,!0,g,f),d=m);l&&(h[e]=l(a),(c[e]||(c[e]=[])).$$inter=!0,(h.$$observers&&h.$$observers[e].$$scope||a).$watch(l,function(a,b){"class"===e&&a!=b?h.$updateClass(a,b):h.$set(e,a)}))}}}})}}function U(a,b,c){var d=b[0],e=b.length,f=d.parentNode,g,h;if(a)for(g=0,h=a.length;g<h;g++)if(a[g]==d){a[g++]=c;h=g+e-1;for(var l=a.length;g<l;g++,h++)h<l?a[g]=a[h]:delete a[g];a.length-=e-1;a.context===d&&(a.context=c);break}f&&f.replaceChild(c,d);a=W.createDocumentFragment();a.appendChild(d);
z(c).data(z(d).data());la?(Rb=!0,la.cleanData([d])):delete z.cache[d[z.expando]];d=1;for(e=b.length;d<e;d++)f=b[d],z(f).remove(),a.appendChild(f),delete b[d];b[0]=c;b.length=1}function Z(a,b){return Q(function(){return a.apply(null,arguments)},a,b)}function $(a,b,d,e,f,g){try{a(b,d,e,f,g)}catch(h){c(h,va(d))}}function Y(a,c,d,e,f,g){var h;n(e,function(e,g){var l=e.attrName,k=e.optional,m,s,p,B;switch(e.mode){case "@":c.$observe(l,function(a){d[g]=a});c.$$observers[l].$$scope=a;c[l]&&(d[g]=b(c[l])(a));
break;case "=":if(k&&!c[l])break;s=t(c[l]);B=s.literal?ka:function(a,b){return a===b||a!==a&&b!==b};p=s.assign||function(){m=d[g]=s(a);throw ea("nonassign",c[l],f.name);};m=d[g]=s(a);k=function(b){B(b,d[g])||(B(b,m)?p(a,b=d[g]):d[g]=b);return m=b};k.$stateful=!0;k=e.collection?a.$watchCollection(c[l],k):a.$watch(t(c[l],k),null,s.literal);h=h||[];h.push(k);break;case "&":if(!c.hasOwnProperty(l)&&k)break;s=t(c[l]);if(s===w&&k)break;d[g]=function(b){return s(a,b)}}});e=h?function(){for(var a=0,b=h.length;a<
b;++a)h[a]()}:w;return g&&e!==w?(g.$on("$destroy",e),w):e}var aa=function(a,b){if(b){var c=Object.keys(b),d,e,f;d=0;for(e=c.length;d<e;d++)f=c[d],this[f]=b[f]}else this.$attr={};this.$$element=a};aa.prototype={$normalize:xa,$addClass:function(a){a&&0<a.length&&B.addClass(this.$$element,a)},$removeClass:function(a){a&&0<a.length&&B.removeClass(this.$$element,a)},$updateClass:function(a,b){var c=ad(a,b);c&&c.length&&B.addClass(this.$$element,c);(c=ad(b,a))&&c.length&&B.removeClass(this.$$element,c)},
$set:function(a,b,d,e){var f=this.$$element[0],g=Rc(f,a),h=Ff(f,a),f=a;g?(this.$$element.prop(a,b),e=g):h&&(this[h]=b,f=h);this[a]=b;e?this.$attr[a]=e:(e=this.$attr[a])||(this.$attr[a]=e=Ac(a,"-"));g=ta(this.$$element);if("a"===g&&"href"===a||"img"===g&&"src"===a)this[a]=b=O(b,"src"===a);else if("img"===g&&"srcset"===a){for(var g="",h=T(b),l=/(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/,l=/\s/.test(h)?l:/(,)/,h=h.split(l),l=Math.floor(h.length/2),k=0;k<l;k++)var m=2*k,g=g+O(T(h[m]),!0),g=g+(" "+T(h[m+1]));
h=T(h[2*k]).split(/\s/);g+=O(T(h[0]),!0);2===h.length&&(g+=" "+T(h[1]));this[a]=b=g}!1!==d&&(null===b||b===u?this.$$element.removeAttr(e):this.$$element.attr(e,b));(a=this.$$observers)&&n(a[f],function(a){try{a(b)}catch(d){c(d)}})},$observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers=ga()),e=d[a]||(d[a]=[]);e.push(b);x.$evalAsync(function(){!e.$$inter&&c.hasOwnProperty(a)&&b(c[a])});return function(){Ya(e,b)}}};var ca=b.startSymbol(),da=b.endSymbol(),fa="{{"==ca||"}}"==da?Ua:function(a){return a.replace(/\{\{/g,
ca).replace(/}}/g,da)},ia=/^ngAttr[A-Z]/;S.$$addBindingInfo=m?function(a,b){var c=a.data("$binding")||[];K(b)?c=c.concat(b):c.push(b);a.data("$binding",c)}:w;S.$$addBindingClass=m?function(a){D(a,"ng-binding")}:w;S.$$addScopeInfo=m?function(a,b,c,d){a.data(c?d?"$isolateScopeNoTemplate":"$isolateScope":"$scope",b)}:w;S.$$addScopeClass=m?function(a,b){D(a,b?"ng-isolate-scope":"ng-scope")}:w;return S}]}function xa(b){return eb(b.replace(Yc,""))}function ad(b,a){var c="",d=b.split(/\s+/),e=a.split(/\s+/),
f=0;a:for(;f<d.length;f++){for(var g=d[f],h=0;h<e.length;h++)if(g==e[h])continue a;c+=(0<c.length?" ":"")+g}return c}function Zc(b){b=z(b);var a=b.length;if(1>=a)return b;for(;a--;)8===b[a].nodeType&&Lf.call(b,a,1);return b}function We(){var b={},a=!1;this.register=function(a,d){Qa(a,"controller");C(a)?Q(b,a):b[a]=d};this.allowGlobals=function(){a=!0};this.$get=["$injector","$window",function(c,d){function e(a,b,c,d){if(!a||!C(a.$scope))throw F("$controller")("noscp",d,b);a.$scope[b]=c}return function(f,
g,h,l){var k,m,r;h=!0===h;l&&L(l)&&(r=l);if(L(f)){l=f.match(Wc);if(!l)throw Mf("ctrlfmt",f);m=l[1];r=r||l[3];f=b.hasOwnProperty(m)?b[m]:Cc(g.$scope,m,!0)||(a?Cc(d,m,!0):u);Pa(f,m,!0)}if(h)return h=(K(f)?f[f.length-1]:f).prototype,k=Object.create(h||null),r&&e(g,r,k,m||f.name),Q(function(){var a=c.invoke(f,k,g,m);a!==k&&(C(a)||G(a))&&(k=a,r&&e(g,r,k,m||f.name));return k},{instance:k,identifier:r});k=c.instantiate(f,g,m);r&&e(g,r,k,m||f.name);return k}}]}function Xe(){this.$get=["$window",function(b){return z(b.document)}]}
function Ye(){this.$get=["$log",function(b){return function(a,c){b.error.apply(b,arguments)}}]}function Zb(b){return C(b)?da(b)?b.toISOString():$a(b):b}function bf(){this.$get=function(){return function(b){if(!b)return"";var a=[];oc(b,function(b,d){null===b||v(b)||(K(b)?n(b,function(b,c){a.push(ia(d)+"="+ia(Zb(b)))}):a.push(ia(d)+"="+ia(Zb(b))))});return a.join("&")}}}function cf(){this.$get=function(){return function(b){function a(b,e,f){null===b||v(b)||(K(b)?n(b,function(b){a(b,e+"[]")}):C(b)&&
!da(b)?oc(b,function(b,c){a(b,e+(f?"":"[")+c+(f?"":"]"))}):c.push(ia(e)+"="+ia(Zb(b))))}if(!b)return"";var c=[];a(b,"",!0);return c.join("&")}}}function $b(b,a){if(L(b)){var c=b.replace(Nf,"").trim();if(c){var d=a("Content-Type");(d=d&&0===d.indexOf(bd))||(d=(d=c.match(Of))&&Pf[d[0]].test(c));d&&(b=vc(c))}}return b}function cd(b){var a=ga(),c;L(b)?n(b.split("\n"),function(b){c=b.indexOf(":");var e=E(T(b.substr(0,c)));b=T(b.substr(c+1));e&&(a[e]=a[e]?a[e]+", "+b:b)}):C(b)&&n(b,function(b,c){var f=
E(c),g=T(b);f&&(a[f]=a[f]?a[f]+", "+g:g)});return a}function dd(b){var a;return function(c){a||(a=cd(b));return c?(c=a[E(c)],void 0===c&&(c=null),c):a}}function ed(b,a,c,d){if(G(d))return d(b,a,c);n(d,function(d){b=d(b,a,c)});return b}function af(){var b=this.defaults={transformResponse:[$b],transformRequest:[function(a){return C(a)&&"[object File]"!==sa.call(a)&&"[object Blob]"!==sa.call(a)&&"[object FormData]"!==sa.call(a)?$a(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"},post:fa(ac),
put:fa(ac),patch:fa(ac)},xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",paramSerializer:"$httpParamSerializer"},a=!1;this.useApplyAsync=function(b){return y(b)?(a=!!b,this):a};var c=this.interceptors=[];this.$get=["$httpBackend","$$cookieReader","$cacheFactory","$rootScope","$q","$injector",function(d,e,f,g,h,l){function k(a){function c(a){var b=Q({},a);b.data=a.data?ed(a.data,a.headers,a.status,e.transformResponse):a.data;a=a.status;return 200<=a&&300>a?b:h.reject(b)}function d(a,b){var c,
e={};n(a,function(a,d){G(a)?(c=a(b),null!=c&&(e[d]=c)):e[d]=a});return e}if(!aa.isObject(a))throw F("$http")("badreq",a);var e=Q({method:"get",transformRequest:b.transformRequest,transformResponse:b.transformResponse,paramSerializer:b.paramSerializer},a);e.headers=function(a){var c=b.headers,e=Q({},a.headers),f,g,h,c=Q({},c.common,c[E(a.method)]);a:for(f in c){g=E(f);for(h in e)if(E(h)===g)continue a;e[f]=c[f]}return d(e,fa(a))}(a);e.method=pb(e.method);e.paramSerializer=L(e.paramSerializer)?l.get(e.paramSerializer):
e.paramSerializer;var f=[function(a){var d=a.headers,e=ed(a.data,dd(d),u,a.transformRequest);v(e)&&n(d,function(a,b){"content-type"===E(b)&&delete d[b]});v(a.withCredentials)&&!v(b.withCredentials)&&(a.withCredentials=b.withCredentials);return m(a,e).then(c,c)},u],g=h.when(e);for(n(A,function(a){(a.request||a.requestError)&&f.unshift(a.request,a.requestError);(a.response||a.responseError)&&f.push(a.response,a.responseError)});f.length;){a=f.shift();var k=f.shift(),g=g.then(a,k)}g.success=function(a){Pa(a,
"fn");g.then(function(b){a(b.data,b.status,b.headers,e)});return g};g.error=function(a){Pa(a,"fn");g.then(null,function(b){a(b.data,b.status,b.headers,e)});return g};return g}function m(c,f){function l(b,c,d,e){function f(){m(c,b,d,e)}O&&(200<=b&&300>b?O.put(P,[b,c,cd(d),e]):O.remove(P));a?g.$applyAsync(f):(f(),g.$$phase||g.$apply())}function m(a,b,d,e){b=Math.max(b,0);(200<=b&&300>b?I.resolve:I.reject)({data:a,status:b,headers:dd(d),config:c,statusText:e})}function A(a){m(a.data,a.status,fa(a.headers()),
a.statusText)}function n(){var a=k.pendingRequests.indexOf(c);-1!==a&&k.pendingRequests.splice(a,1)}var I=h.defer(),B=I.promise,O,D,S=c.headers,P=r(c.url,c.paramSerializer(c.params));k.pendingRequests.push(c);B.then(n,n);!c.cache&&!b.cache||!1===c.cache||"GET"!==c.method&&"JSONP"!==c.method||(O=C(c.cache)?c.cache:C(b.cache)?b.cache:s);O&&(D=O.get(P),y(D)?D&&G(D.then)?D.then(A,A):K(D)?m(D[1],D[0],fa(D[2]),D[3]):m(D,200,{},"OK"):O.put(P,B));v(D)&&((D=fd(c.url)?e()[c.xsrfCookieName||b.xsrfCookieName]:
u)&&(S[c.xsrfHeaderName||b.xsrfHeaderName]=D),d(c.method,P,f,l,S,c.timeout,c.withCredentials,c.responseType));return B}function r(a,b){0<b.length&&(a+=(-1==a.indexOf("?")?"?":"&")+b);return a}var s=f("$http");b.paramSerializer=L(b.paramSerializer)?l.get(b.paramSerializer):b.paramSerializer;var A=[];n(c,function(a){A.unshift(L(a)?l.get(a):l.invoke(a))});k.pendingRequests=[];(function(a){n(arguments,function(a){k[a]=function(b,c){return k(Q({},c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");
(function(a){n(arguments,function(a){k[a]=function(b,c,d){return k(Q({},d||{},{method:a,url:b,data:c}))}})})("post","put","patch");k.defaults=b;return k}]}function Qf(){return new N.XMLHttpRequest}function df(){this.$get=["$browser","$window","$document",function(b,a,c){return Rf(b,Qf,b.defer,a.angular.callbacks,c[0])}]}function Rf(b,a,c,d,e){function f(a,b,c){var f=e.createElement("script"),m=null;f.type="text/javascript";f.src=a;f.async=!0;m=function(a){f.removeEventListener("load",m,!1);f.removeEventListener("error",
m,!1);e.body.removeChild(f);f=null;var g=-1,A="unknown";a&&("load"!==a.type||d[b].called||(a={type:"error"}),A=a.type,g="error"===a.type?404:200);c&&c(g,A)};f.addEventListener("load",m,!1);f.addEventListener("error",m,!1);e.body.appendChild(f);return m}return function(e,h,l,k,m,r,s,A){function H(){p&&p();x&&x.abort()}function M(a,d,e,f,g){I!==u&&c.cancel(I);p=x=null;a(d,e,f,g);b.$$completeOutstandingRequest(w)}b.$$incOutstandingRequestCount();h=h||b.url();if("jsonp"==E(e)){var t="_"+(d.counter++).toString(36);
d[t]=function(a){d[t].data=a;d[t].called=!0};var p=f(h.replace("JSON_CALLBACK","angular.callbacks."+t),t,function(a,b){M(k,a,d[t].data,"",b);d[t]=w})}else{var x=a();x.open(e,h,!0);n(m,function(a,b){y(a)&&x.setRequestHeader(b,a)});x.onload=function(){var a=x.statusText||"",b="response"in x?x.response:x.responseText,c=1223===x.status?204:x.status;0===c&&(c=b?200:"file"==Aa(h).protocol?404:0);M(k,c,b,x.getAllResponseHeaders(),a)};e=function(){M(k,-1,null,null,"")};x.onerror=e;x.onabort=e;s&&(x.withCredentials=
!0);if(A)try{x.responseType=A}catch(q){if("json"!==A)throw q;}x.send(l)}if(0<r)var I=c(H,r);else r&&G(r.then)&&r.then(H)}}function Ze(){var b="{{",a="}}";this.startSymbol=function(a){return a?(b=a,this):b};this.endSymbol=function(b){return b?(a=b,this):a};this.$get=["$parse","$exceptionHandler","$sce",function(c,d,e){function f(a){return"\\\\\\"+a}function g(c){return c.replace(m,b).replace(r,a)}function h(f,h,m,r){function t(a){try{var b=a;a=m?e.getTrusted(m,b):e.valueOf(b);var c;if(r&&!y(a))c=a;
else if(null==a)c="";else{switch(typeof a){case "string":break;case "number":a=""+a;break;default:a=$a(a)}c=a}return c}catch(g){d(Ka.interr(f,g))}}r=!!r;for(var p,n,q=0,I=[],B=[],O=f.length,D=[],S=[];q<O;)if(-1!=(p=f.indexOf(b,q))&&-1!=(n=f.indexOf(a,p+l)))q!==p&&D.push(g(f.substring(q,p))),q=f.substring(p+l,n),I.push(q),B.push(c(q,t)),q=n+k,S.push(D.length),D.push("");else{q!==O&&D.push(g(f.substring(q)));break}m&&1<D.length&&Ka.throwNoconcat(f);if(!h||I.length){var P=function(a){for(var b=0,c=I.length;b<
c;b++){if(r&&v(a[b]))return;D[S[b]]=a[b]}return D.join("")};return Q(function(a){var b=0,c=I.length,e=Array(c);try{for(;b<c;b++)e[b]=B[b](a);return P(e)}catch(g){d(Ka.interr(f,g))}},{exp:f,expressions:I,$$watchDelegate:function(a,b){var c;return a.$watchGroup(B,function(d,e){var f=P(d);G(b)&&b.call(this,f,d!==e?c:f,a);c=f})}})}}var l=b.length,k=a.length,m=new RegExp(b.replace(/./g,f),"g"),r=new RegExp(a.replace(/./g,f),"g");h.startSymbol=function(){return b};h.endSymbol=function(){return a};return h}]}
function $e(){this.$get=["$rootScope","$window","$q","$$q",function(b,a,c,d){function e(e,h,l,k){var m=4<arguments.length,r=m?ra.call(arguments,4):[],s=a.setInterval,A=a.clearInterval,H=0,M=y(k)&&!k,t=(M?d:c).defer(),p=t.promise;l=y(l)?l:0;p.then(null,null,m?function(){e.apply(null,r)}:e);p.$$intervalId=s(function(){t.notify(H++);0<l&&H>=l&&(t.resolve(H),A(p.$$intervalId),delete f[p.$$intervalId]);M||b.$apply()},h);f[p.$$intervalId]=t;return p}var f={};e.cancel=function(b){return b&&b.$$intervalId in
f?(f[b.$$intervalId].reject("canceled"),a.clearInterval(b.$$intervalId),delete f[b.$$intervalId],!0):!1};return e}]}function fe(){this.$get=function(){return{id:"en-us",NUMBER_FORMATS:{DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{minInt:1,minFrac:0,maxFrac:3,posPre:"",posSuf:"",negPre:"-",negSuf:"",gSize:3,lgSize:3},{minInt:1,minFrac:2,maxFrac:2,posPre:"\u00a4",posSuf:"",negPre:"(\u00a4",negSuf:")",gSize:3,lgSize:3}],CURRENCY_SYM:"$"},DATETIME_FORMATS:{MONTH:"January February March April May June July August September October November December".split(" "),
SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),AMPMS:["AM","PM"],medium:"MMM d, y h:mm:ss a","short":"M/d/yy h:mm a",fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",mediumDate:"MMM d, y",shortDate:"M/d/yy",mediumTime:"h:mm:ss a",shortTime:"h:mm a",ERANAMES:["Before Christ","Anno Domini"],ERAS:["BC","AD"]},pluralCat:function(b){return 1===b?"one":"other"}}}}
function bc(b){b=b.split("/");for(var a=b.length;a--;)b[a]=mb(b[a]);return b.join("/")}function gd(b,a){var c=Aa(b);a.$$protocol=c.protocol;a.$$host=c.hostname;a.$$port=Y(c.port)||Sf[c.protocol]||null}function hd(b,a){var c="/"!==b.charAt(0);c&&(b="/"+b);var d=Aa(b);a.$$path=decodeURIComponent(c&&"/"===d.pathname.charAt(0)?d.pathname.substring(1):d.pathname);a.$$search=yc(d.search);a.$$hash=decodeURIComponent(d.hash);a.$$path&&"/"!=a.$$path.charAt(0)&&(a.$$path="/"+a.$$path)}function ya(b,a){if(0===
a.indexOf(b))return a.substr(b.length)}function Ia(b){var a=b.indexOf("#");return-1==a?b:b.substr(0,a)}function Bb(b){return b.replace(/(#.+)|#$/,"$1")}function cc(b){return b.substr(0,Ia(b).lastIndexOf("/")+1)}function dc(b,a){this.$$html5=!0;a=a||"";var c=cc(b);gd(b,this);this.$$parse=function(a){var b=ya(c,a);if(!L(b))throw Cb("ipthprfx",a,c);hd(b,this);this.$$path||(this.$$path="/");this.$$compose()};this.$$compose=function(){var a=Qb(this.$$search),b=this.$$hash?"#"+mb(this.$$hash):"";this.$$url=
bc(this.$$path)+(a?"?"+a:"")+b;this.$$absUrl=c+this.$$url.substr(1)};this.$$parseLinkUrl=function(d,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),!0;var f,g;(f=ya(b,d))!==u?(g=f,g=(f=ya(a,f))!==u?c+(ya("/",f)||f):b+g):(f=ya(c,d))!==u?g=c+f:c==d+"/"&&(g=c);g&&this.$$parse(g);return!!g}}function ec(b,a){var c=cc(b);gd(b,this);this.$$parse=function(d){d=ya(b,d)||ya(c,d);var e;"#"===d.charAt(0)?(e=ya(a,d),v(e)&&(e=d)):e=this.$$html5?d:"";hd(e,this);d=this.$$path;var f=/^\/[A-Z]:(\/.*)/;0===e.indexOf(b)&&
(e=e.replace(b,""));f.exec(e)||(d=(e=f.exec(d))?e[1]:d);this.$$path=d;this.$$compose()};this.$$compose=function(){var c=Qb(this.$$search),e=this.$$hash?"#"+mb(this.$$hash):"";this.$$url=bc(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+(this.$$url?a+this.$$url:"")};this.$$parseLinkUrl=function(a,c){return Ia(b)==Ia(a)?(this.$$parse(a),!0):!1}}function id(b,a){this.$$html5=!0;ec.apply(this,arguments);var c=cc(b);this.$$parseLinkUrl=function(d,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),!0;var f,
g;b==Ia(d)?f=d:(g=ya(c,d))?f=b+a+g:c===d+"/"&&(f=c);f&&this.$$parse(f);return!!f};this.$$compose=function(){var c=Qb(this.$$search),e=this.$$hash?"#"+mb(this.$$hash):"";this.$$url=bc(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+a+this.$$url}}function Db(b){return function(){return this[b]}}function jd(b,a){return function(c){if(v(c))return this[b];this[b]=a(c);this.$$compose();return this}}function ef(){var b="",a={enabled:!1,requireBase:!0,rewriteLinks:!0};this.hashPrefix=function(a){return y(a)?
(b=a,this):b};this.html5Mode=function(b){return Xa(b)?(a.enabled=b,this):C(b)?(Xa(b.enabled)&&(a.enabled=b.enabled),Xa(b.requireBase)&&(a.requireBase=b.requireBase),Xa(b.rewriteLinks)&&(a.rewriteLinks=b.rewriteLinks),this):a};this.$get=["$rootScope","$browser","$sniffer","$rootElement","$window",function(c,d,e,f,g){function h(a,b,c){var e=k.url(),f=k.$$state;try{d.url(a,b,c),k.$$state=d.state()}catch(g){throw k.url(e),k.$$state=f,g;}}function l(a,b){c.$broadcast("$locationChangeSuccess",k.absUrl(),
a,k.$$state,b)}var k,m;m=d.baseHref();var r=d.url(),s;if(a.enabled){if(!m&&a.requireBase)throw Cb("nobase");s=r.substring(0,r.indexOf("/",r.indexOf("//")+2))+(m||"/");m=e.history?dc:id}else s=Ia(r),m=ec;k=new m(s,"#"+b);k.$$parseLinkUrl(r,r);k.$$state=d.state();var A=/^\s*(javascript|mailto):/i;f.on("click",function(b){if(a.rewriteLinks&&!b.ctrlKey&&!b.metaKey&&!b.shiftKey&&2!=b.which&&2!=b.button){for(var e=z(b.target);"a"!==ta(e[0]);)if(e[0]===f[0]||!(e=e.parent())[0])return;var h=e.prop("href"),
l=e.attr("href")||e.attr("xlink:href");C(h)&&"[object SVGAnimatedString]"===h.toString()&&(h=Aa(h.animVal).href);A.test(h)||!h||e.attr("target")||b.isDefaultPrevented()||!k.$$parseLinkUrl(h,l)||(b.preventDefault(),k.absUrl()!=d.url()&&(c.$apply(),g.angular["ff-684208-preventDefault"]=!0))}});Bb(k.absUrl())!=Bb(r)&&d.url(k.absUrl(),!0);var H=!0;d.onUrlChange(function(a,b){c.$evalAsync(function(){var d=k.absUrl(),e=k.$$state,f;k.$$parse(a);k.$$state=b;f=c.$broadcast("$locationChangeStart",a,d,b,e).defaultPrevented;
k.absUrl()===a&&(f?(k.$$parse(d),k.$$state=e,h(d,!1,e)):(H=!1,l(d,e)))});c.$$phase||c.$digest()});c.$watch(function(){var a=Bb(d.url()),b=Bb(k.absUrl()),f=d.state(),g=k.$$replace,m=a!==b||k.$$html5&&e.history&&f!==k.$$state;if(H||m)H=!1,c.$evalAsync(function(){var b=k.absUrl(),d=c.$broadcast("$locationChangeStart",b,a,k.$$state,f).defaultPrevented;k.absUrl()===b&&(d?(k.$$parse(a),k.$$state=f):(m&&h(b,g,f===k.$$state?null:k.$$state),l(a,f)))});k.$$replace=!1});return k}]}function ff(){var b=!0,a=this;
this.debugEnabled=function(a){return y(a)?(b=a,this):b};this.$get=["$window",function(c){function d(a){a instanceof Error&&(a.stack?a=a.message&&-1===a.stack.indexOf(a.message)?"Error: "+a.message+"\n"+a.stack:a.stack:a.sourceURL&&(a=a.message+"\n"+a.sourceURL+":"+a.line));return a}function e(a){var b=c.console||{},e=b[a]||b.log||w;a=!1;try{a=!!e.apply}catch(l){}return a?function(){var a=[];n(arguments,function(b){a.push(d(b))});return e.apply(b,a)}:function(a,b){e(a,null==b?"":b)}}return{log:e("log"),
info:e("info"),warn:e("warn"),error:e("error"),debug:function(){var c=e("debug");return function(){b&&c.apply(a,arguments)}}()}}]}function Ba(b,a){if("__defineGetter__"===b||"__defineSetter__"===b||"__lookupGetter__"===b||"__lookupSetter__"===b||"__proto__"===b)throw ca("isecfld",a);return b}function na(b,a){if(b){if(b.constructor===b)throw ca("isecfn",a);if(b.window===b)throw ca("isecwindow",a);if(b.children&&(b.nodeName||b.prop&&b.attr&&b.find))throw ca("isecdom",a);if(b===Object)throw ca("isecobj",
a);}return b}function kd(b,a){if(b){if(b.constructor===b)throw ca("isecfn",a);if(b===Tf||b===Uf||b===Vf)throw ca("isecff",a);}}function Wf(b,a){return"undefined"!==typeof b?b:a}function ld(b,a){return"undefined"===typeof b?a:"undefined"===typeof a?b:b+a}function U(b,a){var c,d;switch(b.type){case q.Program:c=!0;n(b.body,function(b){U(b.expression,a);c=c&&b.expression.constant});b.constant=c;break;case q.Literal:b.constant=!0;b.toWatch=[];break;case q.UnaryExpression:U(b.argument,a);b.constant=b.argument.constant;
b.toWatch=b.argument.toWatch;break;case q.BinaryExpression:U(b.left,a);U(b.right,a);b.constant=b.left.constant&&b.right.constant;b.toWatch=b.left.toWatch.concat(b.right.toWatch);break;case q.LogicalExpression:U(b.left,a);U(b.right,a);b.constant=b.left.constant&&b.right.constant;b.toWatch=b.constant?[]:[b];break;case q.ConditionalExpression:U(b.test,a);U(b.alternate,a);U(b.consequent,a);b.constant=b.test.constant&&b.alternate.constant&&b.consequent.constant;b.toWatch=b.constant?[]:[b];break;case q.Identifier:b.constant=
!1;b.toWatch=[b];break;case q.MemberExpression:U(b.object,a);b.computed&&U(b.property,a);b.constant=b.object.constant&&(!b.computed||b.property.constant);b.toWatch=[b];break;case q.CallExpression:c=b.filter?!a(b.callee.name).$stateful:!1;d=[];n(b.arguments,function(b){U(b,a);c=c&&b.constant;b.constant||d.push.apply(d,b.toWatch)});b.constant=c;b.toWatch=b.filter&&!a(b.callee.name).$stateful?d:[b];break;case q.AssignmentExpression:U(b.left,a);U(b.right,a);b.constant=b.left.constant&&b.right.constant;
b.toWatch=[b];break;case q.ArrayExpression:c=!0;d=[];n(b.elements,function(b){U(b,a);c=c&&b.constant;b.constant||d.push.apply(d,b.toWatch)});b.constant=c;b.toWatch=d;break;case q.ObjectExpression:c=!0;d=[];n(b.properties,function(b){U(b.value,a);c=c&&b.value.constant;b.value.constant||d.push.apply(d,b.value.toWatch)});b.constant=c;b.toWatch=d;break;case q.ThisExpression:b.constant=!1,b.toWatch=[]}}function md(b){if(1==b.length){b=b[0].expression;var a=b.toWatch;return 1!==a.length?a:a[0]!==b?a:u}}
function nd(b){return b.type===q.Identifier||b.type===q.MemberExpression}function od(b){if(1===b.body.length&&nd(b.body[0].expression))return{type:q.AssignmentExpression,left:b.body[0].expression,right:{type:q.NGValueParameter},operator:"="}}function pd(b){return 0===b.body.length||1===b.body.length&&(b.body[0].expression.type===q.Literal||b.body[0].expression.type===q.ArrayExpression||b.body[0].expression.type===q.ObjectExpression)}function qd(b,a){this.astBuilder=b;this.$filter=a}function rd(b,
a){this.astBuilder=b;this.$filter=a}function Eb(b,a,c,d){na(b,d);a=a.split(".");for(var e,f=0;1<a.length;f++){e=Ba(a.shift(),d);var g=na(b[e],d);g||(g={},b[e]=g);b=g}e=Ba(a.shift(),d);na(b[e],d);return b[e]=c}function Fb(b){return"constructor"==b}function fc(b){return G(b.valueOf)?b.valueOf():Xf.call(b)}function gf(){var b=ga(),a=ga();this.$get=["$filter","$sniffer",function(c,d){function e(a,b){return null==a||null==b?a===b:"object"===typeof a&&(a=fc(a),"object"===typeof a)?!1:a===b||a!==a&&b!==
b}function f(a,b,c,d,f){var g=d.inputs,h;if(1===g.length){var l=e,g=g[0];return a.$watch(function(a){var b=g(a);e(b,l)||(h=d(a,u,u,[b]),l=b&&fc(b));return h},b,c,f)}for(var k=[],m=[],r=0,n=g.length;r<n;r++)k[r]=e,m[r]=null;return a.$watch(function(a){for(var b=!1,c=0,f=g.length;c<f;c++){var l=g[c](a);if(b||(b=!e(l,k[c])))m[c]=l,k[c]=l&&fc(l)}b&&(h=d(a,u,u,m));return h},b,c,f)}function g(a,b,c,d){var e,f;return e=a.$watch(function(a){return d(a)},function(a,c,d){f=a;G(b)&&b.apply(this,arguments);y(a)&&
d.$$postDigest(function(){y(f)&&e()})},c)}function h(a,b,c,d){function e(a){var b=!0;n(a,function(a){y(a)||(b=!1)});return b}var f,g;return f=a.$watch(function(a){return d(a)},function(a,c,d){g=a;G(b)&&b.call(this,a,c,d);e(a)&&d.$$postDigest(function(){e(g)&&f()})},c)}function l(a,b,c,d){var e;return e=a.$watch(function(a){return d(a)},function(a,c,d){G(b)&&b.apply(this,arguments);e()},c)}function k(a,b){if(!b)return a;var c=a.$$watchDelegate,c=c!==h&&c!==g?function(c,d,e,f){e=a(c,d,e,f);return b(e,
c,d)}:function(c,d,e,f){e=a(c,d,e,f);c=b(e,c,d);return y(e)?c:e};a.$$watchDelegate&&a.$$watchDelegate!==f?c.$$watchDelegate=a.$$watchDelegate:b.$stateful||(c.$$watchDelegate=f,c.inputs=a.inputs?a.inputs:[a]);return c}var m={csp:d.csp,expensiveChecks:!1},r={csp:d.csp,expensiveChecks:!0};return function(d,e,H){var n,t,p;switch(typeof d){case "string":p=d=d.trim();var q=H?a:b;n=q[p];n||(":"===d.charAt(0)&&":"===d.charAt(1)&&(t=!0,d=d.substring(2)),H=H?r:m,n=new gc(H),n=(new hc(n,c,H)).parse(d),n.constant?
n.$$watchDelegate=l:t?n.$$watchDelegate=n.literal?h:g:n.inputs&&(n.$$watchDelegate=f),q[p]=n);return k(n,e);case "function":return k(d,e);default:return w}}}]}function jf(){this.$get=["$rootScope","$exceptionHandler",function(b,a){return sd(function(a){b.$evalAsync(a)},a)}]}function kf(){this.$get=["$browser","$exceptionHandler",function(b,a){return sd(function(a){b.defer(a)},a)}]}function sd(b,a){function c(a,b,c){function d(b){return function(c){e||(e=!0,b.call(a,c))}}var e=!1;return[d(b),d(c)]}
function d(){this.$$state={status:0}}function e(a,b){return function(c){b.call(a,c)}}function f(c){!c.processScheduled&&c.pending&&(c.processScheduled=!0,b(function(){var b,d,e;e=c.pending;c.processScheduled=!1;c.pending=u;for(var f=0,g=e.length;f<g;++f){d=e[f][0];b=e[f][c.status];try{G(b)?d.resolve(b(c.value)):1===c.status?d.resolve(c.value):d.reject(c.value)}catch(h){d.reject(h),a(h)}}}))}function g(){this.promise=new d;this.resolve=e(this,this.resolve);this.reject=e(this,this.reject);this.notify=
e(this,this.notify)}var h=F("$q",TypeError);d.prototype={then:function(a,b,c){var d=new g;this.$$state.pending=this.$$state.pending||[];this.$$state.pending.push([d,a,b,c]);0<this.$$state.status&&f(this.$$state);return d.promise},"catch":function(a){return this.then(null,a)},"finally":function(a,b){return this.then(function(b){return k(b,!0,a)},function(b){return k(b,!1,a)},b)}};g.prototype={resolve:function(a){this.promise.$$state.status||(a===this.promise?this.$$reject(h("qcycle",a)):this.$$resolve(a))},
$$resolve:function(b){var d,e;e=c(this,this.$$resolve,this.$$reject);try{if(C(b)||G(b))d=b&&b.then;G(d)?(this.promise.$$state.status=-1,d.call(b,e[0],e[1],this.notify)):(this.promise.$$state.value=b,this.promise.$$state.status=1,f(this.promise.$$state))}catch(g){e[1](g),a(g)}},reject:function(a){this.promise.$$state.status||this.$$reject(a)},$$reject:function(a){this.promise.$$state.value=a;this.promise.$$state.status=2;f(this.promise.$$state)},notify:function(c){var d=this.promise.$$state.pending;
0>=this.promise.$$state.status&&d&&d.length&&b(function(){for(var b,e,f=0,g=d.length;f<g;f++){e=d[f][0];b=d[f][3];try{e.notify(G(b)?b(c):c)}catch(h){a(h)}}})}};var l=function(a,b){var c=new g;b?c.resolve(a):c.reject(a);return c.promise},k=function(a,b,c){var d=null;try{G(c)&&(d=c())}catch(e){return l(e,!1)}return d&&G(d.then)?d.then(function(){return l(a,b)},function(a){return l(a,!1)}):l(a,b)},m=function(a,b,c,d){var e=new g;e.resolve(a);return e.promise.then(b,c,d)},r=function A(a){if(!G(a))throw h("norslvr",
a);if(!(this instanceof A))return new A(a);var b=new g;a(function(a){b.resolve(a)},function(a){b.reject(a)});return b.promise};r.defer=function(){return new g};r.reject=function(a){var b=new g;b.reject(a);return b.promise};r.when=m;r.all=function(a){var b=new g,c=0,d=K(a)?[]:{};n(a,function(a,e){c++;m(a).then(function(a){d.hasOwnProperty(e)||(d[e]=a,--c||b.resolve(d))},function(a){d.hasOwnProperty(e)||b.reject(a)})});0===c&&b.resolve(d);return b.promise};return r}function tf(){this.$get=["$window",
"$timeout",function(b,a){function c(){for(var a=0;a<m.length;a++){var b=m[a];b&&(m[a]=null,b())}k=m.length=0}function d(a){var b=m.length;k++;m.push(a);0===b&&(l=h(c));return function(){0<=b&&(b=m[b]=null,0===--k&&l&&(l(),l=null,m.length=0))}}var e=b.requestAnimationFrame||b.webkitRequestAnimationFrame,f=b.cancelAnimationFrame||b.webkitCancelAnimationFrame||b.webkitCancelRequestAnimationFrame,g=!!e,h=g?function(a){var b=e(a);return function(){f(b)}}:function(b){var c=a(b,16.66,!1);return function(){a.cancel(c)}};
d.supported=g;var l,k=0,m=[];return d}]}function hf(){function b(a){function b(){this.$$watchers=this.$$nextSibling=this.$$childHead=this.$$childTail=null;this.$$listeners={};this.$$listenerCount={};this.$$watchersCount=0;this.$id=++lb;this.$$ChildScope=null}b.prototype=a;return b}var a=10,c=F("$rootScope"),d=null,e=null;this.digestTtl=function(b){arguments.length&&(a=b);return a};this.$get=["$injector","$exceptionHandler","$parse","$browser",function(f,g,h,l){function k(a){a.currentScope.$$destroyed=
!0}function m(){this.$id=++lb;this.$$phase=this.$parent=this.$$watchers=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null;this.$root=this;this.$$destroyed=!1;this.$$listeners={};this.$$listenerCount={};this.$$watchersCount=0;this.$$isolateBindings=null}function r(a){if(p.$$phase)throw c("inprog",p.$$phase);p.$$phase=a}function s(a,b){do a.$$watchersCount+=b;while(a=a.$parent)}function A(a,b,c){do a.$$listenerCount[c]-=b,0===a.$$listenerCount[c]&&delete a.$$listenerCount[c];
while(a=a.$parent)}function q(){}function u(){for(;I.length;)try{I.shift()()}catch(a){g(a)}e=null}function t(){null===e&&(e=l.defer(function(){p.$apply(u)}))}m.prototype={constructor:m,$new:function(a,c){var d;c=c||this;a?(d=new m,d.$root=this.$root):(this.$$ChildScope||(this.$$ChildScope=b(this)),d=new this.$$ChildScope);d.$parent=c;d.$$prevSibling=c.$$childTail;c.$$childHead?(c.$$childTail.$$nextSibling=d,c.$$childTail=d):c.$$childHead=c.$$childTail=d;(a||c!=this)&&d.$on("$destroy",k);return d},
$watch:function(a,b,c,e){var f=h(a);if(f.$$watchDelegate)return f.$$watchDelegate(this,b,c,f,a);var g=this,l=g.$$watchers,k={fn:b,last:q,get:f,exp:e||a,eq:!!c};d=null;G(b)||(k.fn=w);l||(l=g.$$watchers=[]);l.unshift(k);s(this,1);return function(){0<=Ya(l,k)&&s(g,-1);d=null}},$watchGroup:function(a,b){function c(){h=!1;l?(l=!1,b(e,e,g)):b(e,d,g)}var d=Array(a.length),e=Array(a.length),f=[],g=this,h=!1,l=!0;if(!a.length){var k=!0;g.$evalAsync(function(){k&&b(e,e,g)});return function(){k=!1}}if(1===a.length)return this.$watch(a[0],
function(a,c,f){e[0]=a;d[0]=c;b(e,a===c?e:d,f)});n(a,function(a,b){var l=g.$watch(a,function(a,f){e[b]=a;d[b]=f;h||(h=!0,g.$evalAsync(c))});f.push(l)});return function(){for(;f.length;)f.shift()()}},$watchCollection:function(a,b){function c(a){e=a;var b,d,g,h;if(!v(e)){if(C(e))if(Da(e))for(f!==r&&(f=r,n=f.length=0,k++),a=e.length,n!==a&&(k++,f.length=n=a),b=0;b<a;b++)h=f[b],g=e[b],d=h!==h&&g!==g,d||h===g||(k++,f[b]=g);else{f!==s&&(f=s={},n=0,k++);a=0;for(b in e)e.hasOwnProperty(b)&&(a++,g=e[b],h=
f[b],b in f?(d=h!==h&&g!==g,d||h===g||(k++,f[b]=g)):(n++,f[b]=g,k++));if(n>a)for(b in k++,f)e.hasOwnProperty(b)||(n--,delete f[b])}else f!==e&&(f=e,k++);return k}}c.$stateful=!0;var d=this,e,f,g,l=1<b.length,k=0,m=h(a,c),r=[],s={},p=!0,n=0;return this.$watch(m,function(){p?(p=!1,b(e,e,d)):b(e,g,d);if(l)if(C(e))if(Da(e)){g=Array(e.length);for(var a=0;a<e.length;a++)g[a]=e[a]}else for(a in g={},e)kb.call(e,a)&&(g[a]=e[a]);else g=e})},$digest:function(){var b,f,h,k,m,s,n=a,A,t=[],I,v;r("$digest");l.$$checkUrlChange();
this===p&&null!==e&&(l.defer.cancel(e),u());d=null;do{s=!1;for(A=this;x.length;){try{v=x.shift(),v.scope.$eval(v.expression,v.locals)}catch(w){g(w)}d=null}a:do{if(k=A.$$watchers)for(m=k.length;m--;)try{if(b=k[m])if((f=b.get(A))!==(h=b.last)&&!(b.eq?ka(f,h):"number"===typeof f&&"number"===typeof h&&isNaN(f)&&isNaN(h)))s=!0,d=b,b.last=b.eq?ua(f,null):f,b.fn(f,h===q?f:h,A),5>n&&(I=4-n,t[I]||(t[I]=[]),t[I].push({msg:G(b.exp)?"fn: "+(b.exp.name||b.exp.toString()):b.exp,newVal:f,oldVal:h}));else if(b===
d){s=!1;break a}}catch(z){g(z)}if(!(k=A.$$watchersCount&&A.$$childHead||A!==this&&A.$$nextSibling))for(;A!==this&&!(k=A.$$nextSibling);)A=A.$parent}while(A=k);if((s||x.length)&&!n--)throw p.$$phase=null,c("infdig",a,t);}while(s||x.length);for(p.$$phase=null;y.length;)try{y.shift()()}catch(C){g(C)}},$destroy:function(){if(!this.$$destroyed){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;this===p&&l.$$applicationDestroyed();s(this,-this.$$watchersCount);for(var b in this.$$listenerCount)A(this,
this.$$listenerCount[b],b);a&&a.$$childHead==this&&(a.$$childHead=this.$$nextSibling);a&&a.$$childTail==this&&(a.$$childTail=this.$$prevSibling);this.$$prevSibling&&(this.$$prevSibling.$$nextSibling=this.$$nextSibling);this.$$nextSibling&&(this.$$nextSibling.$$prevSibling=this.$$prevSibling);this.$destroy=this.$digest=this.$apply=this.$evalAsync=this.$applyAsync=w;this.$on=this.$watch=this.$watchGroup=function(){return w};this.$$listeners={};this.$parent=this.$$nextSibling=this.$$prevSibling=this.$$childHead=
this.$$childTail=this.$root=this.$$watchers=null}},$eval:function(a,b){return h(a)(this,b)},$evalAsync:function(a,b){p.$$phase||x.length||l.defer(function(){x.length&&p.$digest()});x.push({scope:this,expression:a,locals:b})},$$postDigest:function(a){y.push(a)},$apply:function(a){try{return r("$apply"),this.$eval(a)}catch(b){g(b)}finally{p.$$phase=null;try{p.$digest()}catch(c){throw g(c),c;}}},$applyAsync:function(a){function b(){c.$eval(a)}var c=this;a&&I.push(b);t()},$on:function(a,b){var c=this.$$listeners[a];
c||(this.$$listeners[a]=c=[]);c.push(b);var d=this;do d.$$listenerCount[a]||(d.$$listenerCount[a]=0),d.$$listenerCount[a]++;while(d=d.$parent);var e=this;return function(){var d=c.indexOf(b);-1!==d&&(c[d]=null,A(e,1,a))}},$emit:function(a,b){var c=[],d,e=this,f=!1,h={name:a,targetScope:e,stopPropagation:function(){f=!0},preventDefault:function(){h.defaultPrevented=!0},defaultPrevented:!1},l=Za([h],arguments,1),k,m;do{d=e.$$listeners[a]||c;h.currentScope=e;k=0;for(m=d.length;k<m;k++)if(d[k])try{d[k].apply(null,
l)}catch(r){g(r)}else d.splice(k,1),k--,m--;if(f)return h.currentScope=null,h;e=e.$parent}while(e);h.currentScope=null;return h},$broadcast:function(a,b){var c=this,d=this,e={name:a,targetScope:this,preventDefault:function(){e.defaultPrevented=!0},defaultPrevented:!1};if(!this.$$listenerCount[a])return e;for(var f=Za([e],arguments,1),h,l;c=d;){e.currentScope=c;d=c.$$listeners[a]||[];h=0;for(l=d.length;h<l;h++)if(d[h])try{d[h].apply(null,f)}catch(k){g(k)}else d.splice(h,1),h--,l--;if(!(d=c.$$listenerCount[a]&&
c.$$childHead||c!==this&&c.$$nextSibling))for(;c!==this&&!(d=c.$$nextSibling);)c=c.$parent}e.currentScope=null;return e}};var p=new m,x=p.$$asyncQueue=[],y=p.$$postDigestQueue=[],I=p.$$applyAsyncQueue=[];return p}]}function ge(){var b=/^\s*(https?|ftp|mailto|tel|file):/,a=/^\s*((https?|ftp|file|blob):|data:image\/)/;this.aHrefSanitizationWhitelist=function(a){return y(a)?(b=a,this):b};this.imgSrcSanitizationWhitelist=function(b){return y(b)?(a=b,this):a};this.$get=function(){return function(c,d){var e=
d?a:b,f;f=Aa(c).href;return""===f||f.match(e)?c:"unsafe:"+f}}}function Yf(b){if("self"===b)return b;if(L(b)){if(-1<b.indexOf("***"))throw Ca("iwcard",b);b=td(b).replace("\\*\\*",".*").replace("\\*","[^:/.?&;]*");return new RegExp("^"+b+"$")}if(Va(b))return new RegExp("^"+b.source+"$");throw Ca("imatcher");}function ud(b){var a=[];y(b)&&n(b,function(b){a.push(Yf(b))});return a}function mf(){this.SCE_CONTEXTS=oa;var b=["self"],a=[];this.resourceUrlWhitelist=function(a){arguments.length&&(b=ud(a));return b};
this.resourceUrlBlacklist=function(b){arguments.length&&(a=ud(b));return a};this.$get=["$injector",function(c){function d(a,b){return"self"===a?fd(b):!!a.exec(b.href)}function e(a){var b=function(a){this.$$unwrapTrustedValue=function(){return a}};a&&(b.prototype=new a);b.prototype.valueOf=function(){return this.$$unwrapTrustedValue()};b.prototype.toString=function(){return this.$$unwrapTrustedValue().toString()};return b}var f=function(a){throw Ca("unsafe");};c.has("$sanitize")&&(f=c.get("$sanitize"));
var g=e(),h={};h[oa.HTML]=e(g);h[oa.CSS]=e(g);h[oa.URL]=e(g);h[oa.JS]=e(g);h[oa.RESOURCE_URL]=e(h[oa.URL]);return{trustAs:function(a,b){var c=h.hasOwnProperty(a)?h[a]:null;if(!c)throw Ca("icontext",a,b);if(null===b||b===u||""===b)return b;if("string"!==typeof b)throw Ca("itype",a);return new c(b)},getTrusted:function(c,e){if(null===e||e===u||""===e)return e;var g=h.hasOwnProperty(c)?h[c]:null;if(g&&e instanceof g)return e.$$unwrapTrustedValue();if(c===oa.RESOURCE_URL){var g=Aa(e.toString()),r,s,n=
!1;r=0;for(s=b.length;r<s;r++)if(d(b[r],g)){n=!0;break}if(n)for(r=0,s=a.length;r<s;r++)if(d(a[r],g)){n=!1;break}if(n)return e;throw Ca("insecurl",e.toString());}if(c===oa.HTML)return f(e);throw Ca("unsafe");},valueOf:function(a){return a instanceof g?a.$$unwrapTrustedValue():a}}}]}function lf(){var b=!0;this.enabled=function(a){arguments.length&&(b=!!a);return b};this.$get=["$parse","$sceDelegate",function(a,c){if(b&&8>gb)throw Ca("iequirks");var d=fa(oa);d.isEnabled=function(){return b};d.trustAs=
c.trustAs;d.getTrusted=c.getTrusted;d.valueOf=c.valueOf;b||(d.trustAs=d.getTrusted=function(a,b){return b},d.valueOf=Ua);d.parseAs=function(b,c){var e=a(c);return e.literal&&e.constant?e:a(c,function(a){return d.getTrusted(b,a)})};var e=d.parseAs,f=d.getTrusted,g=d.trustAs;n(oa,function(a,b){var c=E(b);d[eb("parse_as_"+c)]=function(b){return e(a,b)};d[eb("get_trusted_"+c)]=function(b){return f(a,b)};d[eb("trust_as_"+c)]=function(b){return g(a,b)}});return d}]}function nf(){this.$get=["$window","$document",
function(b,a){var c={},d=Y((/android (\d+)/.exec(E((b.navigator||{}).userAgent))||[])[1]),e=/Boxee/i.test((b.navigator||{}).userAgent),f=a[0]||{},g,h=/^(Moz|webkit|ms)(?=[A-Z])/,l=f.body&&f.body.style,k=!1,m=!1;if(l){for(var r in l)if(k=h.exec(r)){g=k[0];g=g.substr(0,1).toUpperCase()+g.substr(1);break}g||(g="WebkitOpacity"in l&&"webkit");k=!!("transition"in l||g+"Transition"in l);m=!!("animation"in l||g+"Animation"in l);!d||k&&m||(k=L(l.webkitTransition),m=L(l.webkitAnimation))}return{history:!(!b.history||
!b.history.pushState||4>d||e),hasEvent:function(a){if("input"===a&&11>=gb)return!1;if(v(c[a])){var b=f.createElement("div");c[a]="on"+a in b}return c[a]},csp:cb(),vendorPrefix:g,transitions:k,animations:m,android:d}}]}function pf(){this.$get=["$templateCache","$http","$q",function(b,a,c){function d(e,f){d.totalPendingRequests++;var g=a.defaults&&a.defaults.transformResponse;K(g)?g=g.filter(function(a){return a!==$b}):g===$b&&(g=null);return a.get(e,{cache:b,transformResponse:g})["finally"](function(){d.totalPendingRequests--}).then(function(a){b.put(e,
a.data);return a.data},function(a){if(!f)throw ea("tpload",e,a.status,a.statusText);return c.reject(a)})}d.totalPendingRequests=0;return d}]}function qf(){this.$get=["$rootScope","$browser","$location",function(b,a,c){return{findBindings:function(a,b,c){a=a.getElementsByClassName("ng-binding");var g=[];n(a,function(a){var d=aa.element(a).data("$binding");d&&n(d,function(d){c?(new RegExp("(^|\\s)"+td(b)+"(\\s|\\||$)")).test(d)&&g.push(a):-1!=d.indexOf(b)&&g.push(a)})});return g},findModels:function(a,
b,c){for(var g=["ng-","data-ng-","ng\\:"],h=0;h<g.length;++h){var l=a.querySelectorAll("["+g[h]+"model"+(c?"=":"*=")+'"'+b+'"]');if(l.length)return l}},getLocation:function(){return c.url()},setLocation:function(a){a!==c.url()&&(c.url(a),b.$digest())},whenStable:function(b){a.notifyWhenNoOutstandingRequests(b)}}}]}function rf(){this.$get=["$rootScope","$browser","$q","$$q","$exceptionHandler",function(b,a,c,d,e){function f(f,l,k){G(f)||(k=l,l=f,f=w);var m=ra.call(arguments,3),r=y(k)&&!k,s=(r?d:c).defer(),
n=s.promise,q;q=a.defer(function(){try{s.resolve(f.apply(null,m))}catch(a){s.reject(a),e(a)}finally{delete g[n.$$timeoutId]}r||b.$apply()},l);n.$$timeoutId=q;g[q]=s;return n}var g={};f.cancel=function(b){return b&&b.$$timeoutId in g?(g[b.$$timeoutId].reject("canceled"),delete g[b.$$timeoutId],a.defer.cancel(b.$$timeoutId)):!1};return f}]}function Aa(b){gb&&(Z.setAttribute("href",b),b=Z.href);Z.setAttribute("href",b);return{href:Z.href,protocol:Z.protocol?Z.protocol.replace(/:$/,""):"",host:Z.host,
search:Z.search?Z.search.replace(/^\?/,""):"",hash:Z.hash?Z.hash.replace(/^#/,""):"",hostname:Z.hostname,port:Z.port,pathname:"/"===Z.pathname.charAt(0)?Z.pathname:"/"+Z.pathname}}function fd(b){b=L(b)?Aa(b):b;return b.protocol===vd.protocol&&b.host===vd.host}function sf(){this.$get=qa(N)}function wd(b){function a(a){try{return decodeURIComponent(a)}catch(b){return a}}var c=b[0]||{},d={},e="";return function(){var b,g,h,l,k;b=c.cookie||"";if(b!==e)for(e=b,b=e.split("; "),d={},h=0;h<b.length;h++)g=
b[h],l=g.indexOf("="),0<l&&(k=a(g.substring(0,l)),d[k]===u&&(d[k]=a(g.substring(l+1))));return d}}function xf(){this.$get=wd}function Kc(b){function a(c,d){if(C(c)){var e={};n(c,function(b,c){e[c]=a(c,b)});return e}return b.factory(c+"Filter",d)}this.register=a;this.$get=["$injector",function(a){return function(b){return a.get(b+"Filter")}}];a("currency",xd);a("date",yd);a("filter",Zf);a("json",$f);a("limitTo",ag);a("lowercase",bg);a("number",zd);a("orderBy",Ad);a("uppercase",cg)}function Zf(){return function(b,
a,c){if(!Da(b)){if(null==b)return b;throw F("filter")("notarray",b);}var d;switch(ic(a)){case "function":break;case "boolean":case "null":case "number":case "string":d=!0;case "object":a=dg(a,c,d);break;default:return b}return Array.prototype.filter.call(b,a)}}function dg(b,a,c){var d=C(b)&&"$"in b;!0===a?a=ka:G(a)||(a=function(a,b){if(v(a))return!1;if(null===a||null===b)return a===b;var c;!(c=C(b))&&(c=C(a))&&(c=a,c=!(G(c.toString)&&c.toString!==Object.prototype.toString));if(c)return!1;a=E(""+a);
b=E(""+b);return-1!==a.indexOf(b)});return function(e){return d&&!C(e)?La(e,b.$,a,!1):La(e,b,a,c)}}function La(b,a,c,d,e){var f=ic(b),g=ic(a);if("string"===g&&"!"===a.charAt(0))return!La(b,a.substring(1),c,d);if(K(b))return b.some(function(b){return La(b,a,c,d)});switch(f){case "object":var h;if(d){for(h in b)if("$"!==h.charAt(0)&&La(b[h],a,c,!0))return!0;return e?!1:La(b,a,c,!1)}if("object"===g){for(h in a)if(e=a[h],!G(e)&&!v(e)&&(f="$"===h,!La(f?b:b[h],e,c,f,f)))return!1;return!0}return c(b,a);
case "function":return!1;default:return c(b,a)}}function ic(b){return null===b?"null":typeof b}function xd(b){var a=b.NUMBER_FORMATS;return function(b,d,e){v(d)&&(d=a.CURRENCY_SYM);v(e)&&(e=a.PATTERNS[1].maxFrac);return null==b?b:Bd(b,a.PATTERNS[1],a.GROUP_SEP,a.DECIMAL_SEP,e).replace(/\u00A4/g,d)}}function zd(b){var a=b.NUMBER_FORMATS;return function(b,d){return null==b?b:Bd(b,a.PATTERNS[0],a.GROUP_SEP,a.DECIMAL_SEP,d)}}function Bd(b,a,c,d,e){if(C(b))return"";var f=0>b;b=Math.abs(b);var g=Infinity===
b;if(!g&&!isFinite(b))return"";var h=b+"",l="",k=!1,m=[];g&&(l="\u221e");if(!g&&-1!==h.indexOf("e")){var r=h.match(/([\d\.]+)e(-?)(\d+)/);r&&"-"==r[2]&&r[3]>e+1?b=0:(l=h,k=!0)}if(g||k)0<e&&1>b&&(l=b.toFixed(e),b=parseFloat(l));else{g=(h.split(Cd)[1]||"").length;v(e)&&(e=Math.min(Math.max(a.minFrac,g),a.maxFrac));b=+(Math.round(+(b.toString()+"e"+e)).toString()+"e"+-e);var g=(""+b).split(Cd),h=g[0],g=g[1]||"",r=0,s=a.lgSize,n=a.gSize;if(h.length>=s+n)for(r=h.length-s,k=0;k<r;k++)0===(r-k)%n&&0!==k&&
(l+=c),l+=h.charAt(k);for(k=r;k<h.length;k++)0===(h.length-k)%s&&0!==k&&(l+=c),l+=h.charAt(k);for(;g.length<e;)g+="0";e&&"0"!==e&&(l+=d+g.substr(0,e))}0===b&&(f=!1);m.push(f?a.negPre:a.posPre,l,f?a.negSuf:a.posSuf);return m.join("")}function Gb(b,a,c){var d="";0>b&&(d="-",b=-b);for(b=""+b;b.length<a;)b="0"+b;c&&(b=b.substr(b.length-a));return d+b}function $(b,a,c,d){c=c||0;return function(e){e=e["get"+b]();if(0<c||e>-c)e+=c;0===e&&-12==c&&(e=12);return Gb(e,a,d)}}function Hb(b,a){return function(c,
d){var e=c["get"+b](),f=pb(a?"SHORT"+b:b);return d[f][e]}}function Dd(b){var a=(new Date(b,0,1)).getDay();return new Date(b,0,(4>=a?5:12)-a)}function Ed(b){return function(a){var c=Dd(a.getFullYear());a=+new Date(a.getFullYear(),a.getMonth(),a.getDate()+(4-a.getDay()))-+c;a=1+Math.round(a/6048E5);return Gb(a,b)}}function jc(b,a){return 0>=b.getFullYear()?a.ERAS[0]:a.ERAS[1]}function yd(b){function a(a){var b;if(b=a.match(c)){a=new Date(0);var f=0,g=0,h=b[8]?a.setUTCFullYear:a.setFullYear,l=b[8]?a.setUTCHours:
a.setHours;b[9]&&(f=Y(b[9]+b[10]),g=Y(b[9]+b[11]));h.call(a,Y(b[1]),Y(b[2])-1,Y(b[3]));f=Y(b[4]||0)-f;g=Y(b[5]||0)-g;h=Y(b[6]||0);b=Math.round(1E3*parseFloat("0."+(b[7]||0)));l.call(a,f,g,h,b)}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;return function(c,e,f){var g="",h=[],l,k;e=e||"mediumDate";e=b.DATETIME_FORMATS[e]||e;L(c)&&(c=eg.test(c)?Y(c):a(c));V(c)&&(c=new Date(c));if(!da(c)||!isFinite(c.getTime()))return c;for(;e;)(k=
fg.exec(e))?(h=Za(h,k,1),e=h.pop()):(h.push(e),e=null);var m=c.getTimezoneOffset();f&&(m=wc(f,c.getTimezoneOffset()),c=Pb(c,f,!0));n(h,function(a){l=gg[a];g+=l?l(c,b.DATETIME_FORMATS,m):a.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}function $f(){return function(b,a){v(a)&&(a=2);return $a(b,a)}}function ag(){return function(b,a,c){a=Infinity===Math.abs(Number(a))?Number(a):Y(a);if(isNaN(a))return b;V(b)&&(b=b.toString());if(!K(b)&&!L(b))return b;c=!c||isNaN(c)?0:Y(c);c=0>c&&c>=-b.length?
b.length+c:c;return 0<=a?b.slice(c,c+a):0===c?b.slice(a,b.length):b.slice(Math.max(0,c+a),c)}}function Ad(b){return function(a,c,d){function e(a,b){return b?function(b,c){return a(c,b)}:a}function f(a){switch(typeof a){case "number":case "boolean":case "string":return!0;default:return!1}}function g(a){return null===a?"null":"function"===typeof a.valueOf&&(a=a.valueOf(),f(a))||"function"===typeof a.toString&&(a=a.toString(),f(a))?a:""}function h(a,b){var c=typeof a,d=typeof b;c===d&&"object"===c&&
(a=g(a),b=g(b));return c===d?("string"===c&&(a=a.toLowerCase(),b=b.toLowerCase()),a===b?0:a<b?-1:1):c<d?-1:1}if(!Da(a))return a;c=K(c)?c:[c];0===c.length&&(c=["+"]);c=c.map(function(a){var c=!1,d=a||Ua;if(L(a)){if("+"==a.charAt(0)||"-"==a.charAt(0))c="-"==a.charAt(0),a=a.substring(1);if(""===a)return e(h,c);d=b(a);if(d.constant){var f=d();return e(function(a,b){return h(a[f],b[f])},c)}}return e(function(a,b){return h(d(a),d(b))},c)});return ra.call(a).sort(e(function(a,b){for(var d=0;d<c.length;d++){var e=
c[d](a,b);if(0!==e)return e}return 0},d))}}function Ma(b){G(b)&&(b={link:b});b.restrict=b.restrict||"AC";return qa(b)}function Fd(b,a,c,d,e){var f=this,g=[],h=f.$$parentForm=b.parent().controller("form")||Ib;f.$error={};f.$$success={};f.$pending=u;f.$name=e(a.name||a.ngForm||"")(c);f.$dirty=!1;f.$pristine=!0;f.$valid=!0;f.$invalid=!1;f.$submitted=!1;h.$addControl(f);f.$rollbackViewValue=function(){n(g,function(a){a.$rollbackViewValue()})};f.$commitViewValue=function(){n(g,function(a){a.$commitViewValue()})};
f.$addControl=function(a){Qa(a.$name,"input");g.push(a);a.$name&&(f[a.$name]=a)};f.$$renameControl=function(a,b){var c=a.$name;f[c]===a&&delete f[c];f[b]=a;a.$name=b};f.$removeControl=function(a){a.$name&&f[a.$name]===a&&delete f[a.$name];n(f.$pending,function(b,c){f.$setValidity(c,null,a)});n(f.$error,function(b,c){f.$setValidity(c,null,a)});n(f.$$success,function(b,c){f.$setValidity(c,null,a)});Ya(g,a)};Gd({ctrl:this,$element:b,set:function(a,b,c){var d=a[b];d?-1===d.indexOf(c)&&d.push(c):a[b]=
[c]},unset:function(a,b,c){var d=a[b];d&&(Ya(d,c),0===d.length&&delete a[b])},parentForm:h,$animate:d});f.$setDirty=function(){d.removeClass(b,Sa);d.addClass(b,Jb);f.$dirty=!0;f.$pristine=!1;h.$setDirty()};f.$setPristine=function(){d.setClass(b,Sa,Jb+" ng-submitted");f.$dirty=!1;f.$pristine=!0;f.$submitted=!1;n(g,function(a){a.$setPristine()})};f.$setUntouched=function(){n(g,function(a){a.$setUntouched()})};f.$setSubmitted=function(){d.addClass(b,"ng-submitted");f.$submitted=!0;h.$setSubmitted()}}
function kc(b){b.$formatters.push(function(a){return b.$isEmpty(a)?a:a.toString()})}function hb(b,a,c,d,e,f){var g=E(a[0].type);if(!e.android){var h=!1;a.on("compositionstart",function(a){h=!0});a.on("compositionend",function(){h=!1;l()})}var l=function(b){k&&(f.defer.cancel(k),k=null);if(!h){var e=a.val();b=b&&b.type;"password"===g||c.ngTrim&&"false"===c.ngTrim||(e=T(e));(d.$viewValue!==e||""===e&&d.$$hasNativeValidators)&&d.$setViewValue(e,b)}};if(e.hasEvent("input"))a.on("input",l);else{var k,
m=function(a,b,c){k||(k=f.defer(function(){k=null;b&&b.value===c||l(a)}))};a.on("keydown",function(a){var b=a.keyCode;91===b||15<b&&19>b||37<=b&&40>=b||m(a,this,this.value)});if(e.hasEvent("paste"))a.on("paste cut",m)}a.on("change",l);d.$render=function(){a.val(d.$isEmpty(d.$viewValue)?"":d.$viewValue)}}function Kb(b,a){return function(c,d){var e,f;if(da(c))return c;if(L(c)){'"'==c.charAt(0)&&'"'==c.charAt(c.length-1)&&(c=c.substring(1,c.length-1));if(hg.test(c))return new Date(c);b.lastIndex=0;if(e=
b.exec(c))return e.shift(),f=d?{yyyy:d.getFullYear(),MM:d.getMonth()+1,dd:d.getDate(),HH:d.getHours(),mm:d.getMinutes(),ss:d.getSeconds(),sss:d.getMilliseconds()/1E3}:{yyyy:1970,MM:1,dd:1,HH:0,mm:0,ss:0,sss:0},n(e,function(b,c){c<a.length&&(f[a[c]]=+b)}),new Date(f.yyyy,f.MM-1,f.dd,f.HH,f.mm,f.ss||0,1E3*f.sss||0)}return NaN}}function ib(b,a,c,d){return function(e,f,g,h,l,k,m){function r(a){return a&&!(a.getTime&&a.getTime()!==a.getTime())}function s(a){return y(a)?da(a)?a:c(a):u}Hd(e,f,g,h);hb(e,
f,g,h,l,k);var n=h&&h.$options&&h.$options.timezone,q;h.$$parserName=b;h.$parsers.push(function(b){return h.$isEmpty(b)?null:a.test(b)?(b=c(b,q),n&&(b=Pb(b,n)),b):u});h.$formatters.push(function(a){if(a&&!da(a))throw Lb("datefmt",a);if(r(a))return(q=a)&&n&&(q=Pb(q,n,!0)),m("date")(a,d,n);q=null;return""});if(y(g.min)||g.ngMin){var M;h.$validators.min=function(a){return!r(a)||v(M)||c(a)>=M};g.$observe("min",function(a){M=s(a);h.$validate()})}if(y(g.max)||g.ngMax){var t;h.$validators.max=function(a){return!r(a)||
v(t)||c(a)<=t};g.$observe("max",function(a){t=s(a);h.$validate()})}}}function Hd(b,a,c,d){(d.$$hasNativeValidators=C(a[0].validity))&&d.$parsers.push(function(b){var c=a.prop("validity")||{};return c.badInput&&!c.typeMismatch?u:b})}function Id(b,a,c,d,e){if(y(d)){b=b(d);if(!b.constant)throw F("ngModel")("constexpr",c,d);return b(a)}return e}function lc(b,a){b="ngClass"+b;return["$animate",function(c){function d(a,b){var c=[],d=0;a:for(;d<a.length;d++){for(var e=a[d],m=0;m<b.length;m++)if(e==b[m])continue a;
c.push(e)}return c}function e(a){var b=[];return K(a)?(n(a,function(a){b=b.concat(e(a))}),b):L(a)?a.split(" "):C(a)?(n(a,function(a,c){a&&(b=b.concat(c.split(" ")))}),b):a}return{restrict:"AC",link:function(f,g,h){function l(a,b){var c=g.data("$classCounts")||ga(),d=[];n(a,function(a){if(0<b||c[a])c[a]=(c[a]||0)+b,c[a]===+(0<b)&&d.push(a)});g.data("$classCounts",c);return d.join(" ")}function k(b){if(!0===a||f.$index%2===a){var k=e(b||[]);if(!m){var n=l(k,1);h.$addClass(n)}else if(!ka(b,m)){var q=
e(m),n=d(k,q),k=d(q,k),n=l(n,1),k=l(k,-1);n&&n.length&&c.addClass(g,n);k&&k.length&&c.removeClass(g,k)}}m=fa(b)}var m;f.$watch(h[b],k,!0);h.$observe("class",function(a){k(f.$eval(h[b]))});"ngClass"!==b&&f.$watch("$index",function(c,d){var g=c&1;if(g!==(d&1)){var k=e(f.$eval(h[b]));g===a?(g=l(k,1),h.$addClass(g)):(g=l(k,-1),h.$removeClass(g))}})}}}]}function Gd(b){function a(a,b){b&&!f[a]?(k.addClass(e,a),f[a]=!0):!b&&f[a]&&(k.removeClass(e,a),f[a]=!1)}function c(b,c){b=b?"-"+Ac(b,"-"):"";a(jb+b,!0===
c);a(Jd+b,!1===c)}var d=b.ctrl,e=b.$element,f={},g=b.set,h=b.unset,l=b.parentForm,k=b.$animate;f[Jd]=!(f[jb]=e.hasClass(jb));d.$setValidity=function(b,e,f){e===u?(d.$pending||(d.$pending={}),g(d.$pending,b,f)):(d.$pending&&h(d.$pending,b,f),Kd(d.$pending)&&(d.$pending=u));Xa(e)?e?(h(d.$error,b,f),g(d.$$success,b,f)):(g(d.$error,b,f),h(d.$$success,b,f)):(h(d.$error,b,f),h(d.$$success,b,f));d.$pending?(a(Ld,!0),d.$valid=d.$invalid=u,c("",null)):(a(Ld,!1),d.$valid=Kd(d.$error),d.$invalid=!d.$valid,c("",
d.$valid));e=d.$pending&&d.$pending[b]?u:d.$error[b]?!1:d.$$success[b]?!0:null;c(b,e);l.$setValidity(b,e,d)}}function Kd(b){if(b)for(var a in b)return!1;return!0}var ig=/^\/(.+)\/([a-z]*)$/,E=function(b){return L(b)?b.toLowerCase():b},kb=Object.prototype.hasOwnProperty,pb=function(b){return L(b)?b.toUpperCase():b},gb,z,la,ra=[].slice,Lf=[].splice,jg=[].push,sa=Object.prototype.toString,rc=Object.getPrototypeOf,Ea=F("ng"),aa=N.angular||(N.angular={}),db,lb=0;gb=W.documentMode;w.$inject=[];Ua.$inject=
[];var K=Array.isArray,tc=/^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/,T=function(b){return L(b)?b.trim():b},td=function(b){return b.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08")},cb=function(){if(y(cb.isActive_))return cb.isActive_;var b=!(!W.querySelector("[ng-csp]")&&!W.querySelector("[data-ng-csp]"));if(!b)try{new Function("")}catch(a){b=!0}return cb.isActive_=b},nb=function(){if(y(nb.name_))return nb.name_;var b,a,
c=Na.length,d,e;for(a=0;a<c;++a)if(d=Na[a],b=W.querySelector("["+d.replace(":","\\:")+"jq]")){e=b.getAttribute(d+"jq");break}return nb.name_=e},Na=["ng-","data-ng-","ng:","x-ng-"],ae=/[A-Z]/g,Bc=!1,Rb,pa=1,ab=3,ee={full:"1.4.0",major:1,minor:4,dot:0,codeName:"jaracimrman-existence"};R.expando="ng339";var ub=R.cache={},Df=1;R._data=function(b){return this.cache[b[this.expando]]||{}};var yf=/([\:\-\_]+(.))/g,zf=/^moz([A-Z])/,kg={mouseleave:"mouseout",mouseenter:"mouseover"},Ub=F("jqLite"),Cf=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,
Tb=/<|&#?\w+;/,Af=/<([\w:]+)/,Bf=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ma={option:[1,'<select multiple="multiple">',"</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ma.optgroup=ma.option;ma.tbody=ma.tfoot=ma.colgroup=ma.caption=ma.thead;ma.th=ma.td;var Oa=R.prototype={ready:function(b){function a(){c||(c=
!0,b())}var c=!1;"complete"===W.readyState?setTimeout(a):(this.on("DOMContentLoaded",a),R(N).on("load",a))},toString:function(){var b=[];n(this,function(a){b.push(""+a)});return"["+b.join(", ")+"]"},eq:function(b){return 0<=b?z(this[b]):z(this[this.length+b])},length:0,push:jg,sort:[].sort,splice:[].splice},zb={};n("multiple selected checked disabled readOnly required open".split(" "),function(b){zb[E(b)]=b});var Sc={};n("input select option textarea button form details".split(" "),function(b){Sc[b]=
!0});var Tc={ngMinlength:"minlength",ngMaxlength:"maxlength",ngMin:"min",ngMax:"max",ngPattern:"pattern"};n({data:Wb,removeData:sb},function(b,a){R[a]=b});n({data:Wb,inheritedData:yb,scope:function(b){return z.data(b,"$scope")||yb(b.parentNode||b,["$isolateScope","$scope"])},isolateScope:function(b){return z.data(b,"$isolateScope")||z.data(b,"$isolateScopeNoTemplate")},controller:Pc,injector:function(b){return yb(b,"$injector")},removeAttr:function(b,a){b.removeAttribute(a)},hasClass:vb,css:function(b,
a,c){a=eb(a);if(y(c))b.style[a]=c;else return b.style[a]},attr:function(b,a,c){var d=b.nodeType;if(d!==ab&&2!==d&&8!==d)if(d=E(a),zb[d])if(y(c))c?(b[a]=!0,b.setAttribute(a,d)):(b[a]=!1,b.removeAttribute(d));else return b[a]||(b.attributes.getNamedItem(a)||w).specified?d:u;else if(y(c))b.setAttribute(a,c);else if(b.getAttribute)return b=b.getAttribute(a,2),null===b?u:b},prop:function(b,a,c){if(y(c))b[a]=c;else return b[a]},text:function(){function b(a,b){if(v(b)){var d=a.nodeType;return d===pa||d===
ab?a.textContent:""}a.textContent=b}b.$dv="";return b}(),val:function(b,a){if(v(a)){if(b.multiple&&"select"===ta(b)){var c=[];n(b.options,function(a){a.selected&&c.push(a.value||a.text)});return 0===c.length?null:c}return b.value}b.value=a},html:function(b,a){if(v(a))return b.innerHTML;rb(b,!0);b.innerHTML=a},empty:Qc},function(b,a){R.prototype[a]=function(a,d){var e,f,g=this.length;if(b!==Qc&&(2==b.length&&b!==vb&&b!==Pc?a:d)===u){if(C(a)){for(e=0;e<g;e++)if(b===Wb)b(this[e],a);else for(f in a)b(this[e],
f,a[f]);return this}e=b.$dv;g=e===u?Math.min(g,1):g;for(f=0;f<g;f++){var h=b(this[f],a,d);e=e?e+h:h}return e}for(e=0;e<g;e++)b(this[e],a,d);return this}});n({removeData:sb,on:function a(c,d,e,f){if(y(f))throw Ub("onargs");if(Lc(c)){var g=tb(c,!0);f=g.events;var h=g.handle;h||(h=g.handle=Gf(c,f));for(var g=0<=d.indexOf(" ")?d.split(" "):[d],l=g.length;l--;){d=g[l];var k=f[d];k||(f[d]=[],"mouseenter"===d||"mouseleave"===d?a(c,kg[d],function(a){var c=a.relatedTarget;c&&(c===this||this.contains(c))||
h(a,d)}):"$destroy"!==d&&c.addEventListener(d,h,!1),k=f[d]);k.push(e)}}},off:Oc,one:function(a,c,d){a=z(a);a.on(c,function f(){a.off(c,d);a.off(c,f)});a.on(c,d)},replaceWith:function(a,c){var d,e=a.parentNode;rb(a);n(new R(c),function(c){d?e.insertBefore(c,d.nextSibling):e.replaceChild(c,a);d=c})},children:function(a){var c=[];n(a.childNodes,function(a){a.nodeType===pa&&c.push(a)});return c},contents:function(a){return a.contentDocument||a.childNodes||[]},append:function(a,c){var d=a.nodeType;if(d===
pa||11===d){c=new R(c);for(var d=0,e=c.length;d<e;d++)a.appendChild(c[d])}},prepend:function(a,c){if(a.nodeType===pa){var d=a.firstChild;n(new R(c),function(c){a.insertBefore(c,d)})}},wrap:function(a,c){c=z(c).eq(0).clone()[0];var d=a.parentNode;d&&d.replaceChild(c,a);c.appendChild(a)},remove:Xb,detach:function(a){Xb(a,!0)},after:function(a,c){var d=a,e=a.parentNode;c=new R(c);for(var f=0,g=c.length;f<g;f++){var h=c[f];e.insertBefore(h,d.nextSibling);d=h}},addClass:xb,removeClass:wb,toggleClass:function(a,
c,d){c&&n(c.split(" "),function(c){var f=d;v(f)&&(f=!vb(a,c));(f?xb:wb)(a,c)})},parent:function(a){return(a=a.parentNode)&&11!==a.nodeType?a:null},next:function(a){return a.nextElementSibling},find:function(a,c){return a.getElementsByTagName?a.getElementsByTagName(c):[]},clone:Vb,triggerHandler:function(a,c,d){var e,f,g=c.type||c,h=tb(a);if(h=(h=h&&h.events)&&h[g])e={preventDefault:function(){this.defaultPrevented=!0},isDefaultPrevented:function(){return!0===this.defaultPrevented},stopImmediatePropagation:function(){this.immediatePropagationStopped=
!0},isImmediatePropagationStopped:function(){return!0===this.immediatePropagationStopped},stopPropagation:w,type:g,target:a},c.type&&(e=Q(e,c)),c=fa(h),f=d?[e].concat(d):[e],n(c,function(c){e.isImmediatePropagationStopped()||c.apply(a,f)})}},function(a,c){R.prototype[c]=function(c,e,f){for(var g,h=0,l=this.length;h<l;h++)v(g)?(g=a(this[h],c,e,f),y(g)&&(g=z(g))):Nc(g,a(this[h],c,e,f));return y(g)?g:this};R.prototype.bind=R.prototype.on;R.prototype.unbind=R.prototype.off});Ra.prototype={put:function(a,
c){this[Fa(a,this.nextUid)]=c},get:function(a){return this[Fa(a,this.nextUid)]},remove:function(a){var c=this[a=Fa(a,this.nextUid)];delete this[a];return c}};var wf=[function(){this.$get=[function(){return Ra}]}],Vc=/^function\s*[^\(]*\(\s*([^\)]*)\)/m,lg=/,/,mg=/^\s*(_?)(\S+?)\1\s*$/,Uc=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,Ga=F("$injector");bb.$$annotate=function(a,c,d){var e;if("function"===typeof a){if(!(e=a.$inject)){e=[];if(a.length){if(c)throw L(d)&&d||(d=a.name||Hf(a)),Ga("strictdi",d);c=a.toString().replace(Uc,
"");c=c.match(Vc);n(c[1].split(lg),function(a){a.replace(mg,function(a,c,d){e.push(d)})})}a.$inject=e}}else K(a)?(c=a.length-1,Pa(a[c],"fn"),e=a.slice(0,c)):Pa(a,"fn",!0);return e};var Md=F("$animate"),Te=function(){this.$get=["$q","$$rAF",function(a,c){function d(){}d.all=w;d.chain=w;d.prototype={end:w,cancel:w,resume:w,pause:w,complete:w,then:function(d,f){return a(function(a){c(function(){a()})}).then(d,f)}};return d}]},Se=function(){var a=new Ra,c=[];this.$get=["$$AnimateRunner","$rootScope",
function(d,e){function f(d,f,l){var k=a.get(d);k||(a.put(d,k={}),c.push(d));f&&n(f.split(" "),function(a){a&&(k[a]=!0)});l&&n(l.split(" "),function(a){a&&(k[a]=!1)});1<c.length||e.$$postDigest(function(){n(c,function(c){var d=a.get(c);if(d){var e=If(c.attr("class")),f="",g="";n(d,function(a,c){a!==!!e[c]&&(a?f+=(f.length?" ":"")+c:g+=(g.length?" ":"")+c)});n(c,function(a){f&&xb(a,f);g&&wb(a,g)});a.remove(c)}});c.length=0})}return{enabled:w,on:w,off:w,pin:w,push:function(a,c,e,k){k&&k();e=e||{};e.from&&
a.css(e.from);e.to&&a.css(e.to);(e.addClass||e.removeClass)&&f(a,e.addClass,e.removeClass);return new d}}}]},Re=["$provide",function(a){var c=this;this.$$registeredAnimations=Object.create(null);this.register=function(d,e){if(d&&"."!==d.charAt(0))throw Md("notcsel",d);var f=d+"-animation";c.$$registeredAnimations[d.substr(1)]=f;a.factory(f,e)};this.classNameFilter=function(a){if(1===arguments.length&&(this.$$classNameFilter=a instanceof RegExp?a:null)&&/(\s+|\/)ng-animate(\s+|\/)/.test(this.$$classNameFilter.toString()))throw Md("nongcls",
"ng-animate");return this.$$classNameFilter};this.$get=["$$animateQueue",function(a){function c(a,d,e){if(e){var l;a:{for(l=0;l<e.length;l++){var k=e[l];if(1===k.nodeType){l=k;break a}}l=void 0}!l||l.parentNode||l.previousElementSibling||(e=null)}e?e.after(a):d.prepend(a)}return{on:a.on,off:a.off,pin:a.pin,enabled:a.enabled,cancel:function(a){a.end&&a.end()},enter:function(f,g,h,l){g=g&&z(g);h=h&&z(h);g=g||h.parent();c(f,g,h);return a.push(f,"enter",Ha(l))},move:function(f,g,h,l){g=g&&z(g);h=h&&z(h);
g=g||h.parent();c(f,g,h);return a.push(f,"move",Ha(l))},leave:function(c,e){return a.push(c,"leave",Ha(e),function(){c.remove()})},addClass:function(c,e,h){h=Ha(h);h.addClass=fb(h.addclass,e);return a.push(c,"addClass",h)},removeClass:function(c,e,h){h=Ha(h);h.removeClass=fb(h.removeClass,e);return a.push(c,"removeClass",h)},setClass:function(c,e,h,l){l=Ha(l);l.addClass=fb(l.addClass,e);l.removeClass=fb(l.removeClass,h);return a.push(c,"setClass",l)},animate:function(c,e,h,l,k){k=Ha(k);k.from=k.from?
Q(k.from,e):e;k.to=k.to?Q(k.to,h):h;k.tempClasses=fb(k.tempClasses,l||"ng-inline-animate");return a.push(c,"animate",k)}}}]}],ea=F("$compile");Dc.$inject=["$provide","$$sanitizeUriProvider"];var Yc=/^((?:x|data)[\:\-_])/i,Mf=F("$controller"),Wc=/^(\S+)(\s+as\s+(\w+))?$/,bd="application/json",ac={"Content-Type":bd+";charset=utf-8"},Of=/^\[|^\{(?!\{)/,Pf={"[":/]$/,"{":/}$/},Nf=/^\)\]\}',?\n/,Ka=aa.$interpolateMinErr=F("$interpolate");Ka.throwNoconcat=function(a){throw Ka("noconcat",a);};Ka.interr=function(a,
c){return Ka("interr",a,c.toString())};var ng=/^([^\?#]*)(\?([^#]*))?(#(.*))?$/,Sf={http:80,https:443,ftp:21},Cb=F("$location"),og={$$html5:!1,$$replace:!1,absUrl:Db("$$absUrl"),url:function(a){if(v(a))return this.$$url;var c=ng.exec(a);(c[1]||""===a)&&this.path(decodeURIComponent(c[1]));(c[2]||c[1]||""===a)&&this.search(c[3]||"");this.hash(c[5]||"");return this},protocol:Db("$$protocol"),host:Db("$$host"),port:Db("$$port"),path:jd("$$path",function(a){a=null!==a?a.toString():"";return"/"==a.charAt(0)?
a:"/"+a}),search:function(a,c){switch(arguments.length){case 0:return this.$$search;case 1:if(L(a)||V(a))a=a.toString(),this.$$search=yc(a);else if(C(a))a=ua(a,{}),n(a,function(c,e){null==c&&delete a[e]}),this.$$search=a;else throw Cb("isrcharg");break;default:v(c)||null===c?delete this.$$search[a]:this.$$search[a]=c}this.$$compose();return this},hash:jd("$$hash",function(a){return null!==a?a.toString():""}),replace:function(){this.$$replace=!0;return this}};n([id,ec,dc],function(a){a.prototype=Object.create(og);
a.prototype.state=function(c){if(!arguments.length)return this.$$state;if(a!==dc||!this.$$html5)throw Cb("nostate");this.$$state=v(c)?null:c;return this}});var ca=F("$parse"),Tf=Function.prototype.call,Uf=Function.prototype.apply,Vf=Function.prototype.bind,Mb=ga();n("+ - * / % === !== == != < > <= >= && || ! = |".split(" "),function(a){Mb[a]=!0});var pg={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'},gc=function(a){this.options=a};gc.prototype={constructor:gc,lex:function(a){this.text=a;this.index=
0;for(this.tokens=[];this.index<this.text.length;)if(a=this.text.charAt(this.index),'"'===a||"'"===a)this.readString(a);else if(this.isNumber(a)||"."===a&&this.isNumber(this.peek()))this.readNumber();else if(this.isIdent(a))this.readIdent();else if(this.is(a,"(){}[].,;:?"))this.tokens.push({index:this.index,text:a}),this.index++;else if(this.isWhitespace(a))this.index++;else{var c=a+this.peek(),d=c+this.peek(2),e=Mb[c],f=Mb[d];Mb[a]||e||f?(a=f?d:e?c:a,this.tokens.push({index:this.index,text:a,operator:!0}),
this.index+=a.length):this.throwError("Unexpected next character ",this.index,this.index+1)}return this.tokens},is:function(a,c){return-1!==c.indexOf(a)},peek:function(a){a=a||1;return this.index+a<this.text.length?this.text.charAt(this.index+a):!1},isNumber:function(a){return"0"<=a&&"9">=a&&"string"===typeof a},isWhitespace:function(a){return" "===a||"\r"===a||"\t"===a||"\n"===a||"\v"===a||"\u00a0"===a},isIdent:function(a){return"a"<=a&&"z">=a||"A"<=a&&"Z">=a||"_"===a||"$"===a},isExpOperator:function(a){return"-"===
a||"+"===a||this.isNumber(a)},throwError:function(a,c,d){d=d||this.index;c=y(c)?"s "+c+"-"+this.index+" ["+this.text.substring(c,d)+"]":" "+d;throw ca("lexerr",a,c,this.text);},readNumber:function(){for(var a="",c=this.index;this.index<this.text.length;){var d=E(this.text.charAt(this.index));if("."==d||this.isNumber(d))a+=d;else{var e=this.peek();if("e"==d&&this.isExpOperator(e))a+=d;else if(this.isExpOperator(d)&&e&&this.isNumber(e)&&"e"==a.charAt(a.length-1))a+=d;else if(!this.isExpOperator(d)||
e&&this.isNumber(e)||"e"!=a.charAt(a.length-1))break;else this.throwError("Invalid exponent")}this.index++}this.tokens.push({index:c,text:a,constant:!0,value:Number(a)})},readIdent:function(){for(var a=this.index;this.index<this.text.length;){var c=this.text.charAt(this.index);if(!this.isIdent(c)&&!this.isNumber(c))break;this.index++}this.tokens.push({index:a,text:this.text.slice(a,this.index),identifier:!0})},readString:function(a){var c=this.index;this.index++;for(var d="",e=a,f=!1;this.index<this.text.length;){var g=
this.text.charAt(this.index),e=e+g;if(f)"u"===g?(f=this.text.substring(this.index+1,this.index+5),f.match(/[\da-f]{4}/i)||this.throwError("Invalid unicode escape [\\u"+f+"]"),this.index+=4,d+=String.fromCharCode(parseInt(f,16))):d+=pg[g]||g,f=!1;else if("\\"===g)f=!0;else{if(g===a){this.index++;this.tokens.push({index:c,text:e,constant:!0,value:d});return}d+=g}this.index++}this.throwError("Unterminated quote",c)}};var q=function(a,c){this.lexer=a;this.options=c};q.Program="Program";q.ExpressionStatement=
"ExpressionStatement";q.AssignmentExpression="AssignmentExpression";q.ConditionalExpression="ConditionalExpression";q.LogicalExpression="LogicalExpression";q.BinaryExpression="BinaryExpression";q.UnaryExpression="UnaryExpression";q.CallExpression="CallExpression";q.MemberExpression="MemberExpression";q.Identifier="Identifier";q.Literal="Literal";q.ArrayExpression="ArrayExpression";q.Property="Property";q.ObjectExpression="ObjectExpression";q.ThisExpression="ThisExpression";q.NGValueParameter="NGValueParameter";
q.prototype={ast:function(a){this.text=a;this.tokens=this.lexer.lex(a);a=this.program();0!==this.tokens.length&&this.throwError("is an unexpected token",this.tokens[0]);return a},program:function(){for(var a=[];;)if(0<this.tokens.length&&!this.peek("}",")",";","]")&&a.push(this.expressionStatement()),!this.expect(";"))return{type:q.Program,body:a}},expressionStatement:function(){return{type:q.ExpressionStatement,expression:this.filterChain()}},filterChain:function(){for(var a=this.expression();this.expect("|");)a=
this.filter(a);return a},expression:function(){return this.assignment()},assignment:function(){var a=this.ternary();this.expect("=")&&(a={type:q.AssignmentExpression,left:a,right:this.assignment(),operator:"="});return a},ternary:function(){var a=this.logicalOR(),c,d;return this.expect("?")&&(c=this.expression(),this.consume(":"))?(d=this.expression(),{type:q.ConditionalExpression,test:a,alternate:c,consequent:d}):a},logicalOR:function(){for(var a=this.logicalAND();this.expect("||");)a={type:q.LogicalExpression,
operator:"||",left:a,right:this.logicalAND()};return a},logicalAND:function(){for(var a=this.equality();this.expect("&&");)a={type:q.LogicalExpression,operator:"&&",left:a,right:this.equality()};return a},equality:function(){for(var a=this.relational(),c;c=this.expect("==","!=","===","!==");)a={type:q.BinaryExpression,operator:c.text,left:a,right:this.relational()};return a},relational:function(){for(var a=this.additive(),c;c=this.expect("<",">","<=",">=");)a={type:q.BinaryExpression,operator:c.text,
left:a,right:this.additive()};return a},additive:function(){for(var a=this.multiplicative(),c;c=this.expect("+","-");)a={type:q.BinaryExpression,operator:c.text,left:a,right:this.multiplicative()};return a},multiplicative:function(){for(var a=this.unary(),c;c=this.expect("*","/","%");)a={type:q.BinaryExpression,operator:c.text,left:a,right:this.unary()};return a},unary:function(){var a;return(a=this.expect("+","-","!"))?{type:q.UnaryExpression,operator:a.text,prefix:!0,argument:this.unary()}:this.primary()},
primary:function(){var a;this.expect("(")?(a=this.filterChain(),this.consume(")")):this.expect("[")?a=this.arrayDeclaration():this.expect("{")?a=this.object():this.constants.hasOwnProperty(this.peek().text)?a=ua(this.constants[this.consume().text]):this.peek().identifier?a=this.identifier():this.peek().constant?a=this.constant():this.throwError("not a primary expression",this.peek());for(var c;c=this.expect("(","[",".");)"("===c.text?(a={type:q.CallExpression,callee:a,arguments:this.parseArguments()},
this.consume(")")):"["===c.text?(a={type:q.MemberExpression,object:a,property:this.expression(),computed:!0},this.consume("]")):"."===c.text?a={type:q.MemberExpression,object:a,property:this.identifier(),computed:!1}:this.throwError("IMPOSSIBLE");return a},filter:function(a){a=[a];for(var c={type:q.CallExpression,callee:this.identifier(),arguments:a,filter:!0};this.expect(":");)a.push(this.expression());return c},parseArguments:function(){var a=[];if(")"!==this.peekToken().text){do a.push(this.expression());
while(this.expect(","))}return a},identifier:function(){var a=this.consume();a.identifier||this.throwError("is not a valid identifier",a);return{type:q.Identifier,name:a.text}},constant:function(){return{type:q.Literal,value:this.consume().value}},arrayDeclaration:function(){var a=[];if("]"!==this.peekToken().text){do{if(this.peek("]"))break;a.push(this.expression())}while(this.expect(","))}this.consume("]");return{type:q.ArrayExpression,elements:a}},object:function(){var a=[],c;if("}"!==this.peekToken().text){do{if(this.peek("}"))break;
c={type:q.Property,kind:"init"};this.peek().constant?c.key=this.constant():this.peek().identifier?c.key=this.identifier():this.throwError("invalid key",this.peek());this.consume(":");c.value=this.expression();a.push(c)}while(this.expect(","))}this.consume("}");return{type:q.ObjectExpression,properties:a}},throwError:function(a,c){throw ca("syntax",c.text,a,c.index+1,this.text,this.text.substring(c.index));},consume:function(a){if(0===this.tokens.length)throw ca("ueoe",this.text);var c=this.expect(a);
c||this.throwError("is unexpected, expecting ["+a+"]",this.peek());return c},peekToken:function(){if(0===this.tokens.length)throw ca("ueoe",this.text);return this.tokens[0]},peek:function(a,c,d,e){return this.peekAhead(0,a,c,d,e)},peekAhead:function(a,c,d,e,f){if(this.tokens.length>a){a=this.tokens[a];var g=a.text;if(g===c||g===d||g===e||g===f||!(c||d||e||f))return a}return!1},expect:function(a,c,d,e){return(a=this.peek(a,c,d,e))?(this.tokens.shift(),a):!1},constants:{"true":{type:q.Literal,value:!0},
"false":{type:q.Literal,value:!1},"null":{type:q.Literal,value:null},undefined:{type:q.Literal,value:u},"this":{type:q.ThisExpression}}};qd.prototype={compile:function(a,c){var d=this,e=this.astBuilder.ast(a);this.state={nextId:0,filters:{},expensiveChecks:c,fn:{vars:[],body:[],own:{}},assign:{vars:[],body:[],own:{}},inputs:[]};U(e,d.$filter);var f="",g;this.stage="assign";if(g=od(e))this.state.computing="assign",f=this.nextId(),this.recurse(g,f),f="fn.assign="+this.generateFunction("assign","s,v,l");
g=md(e.body);d.stage="inputs";n(g,function(a,c){var e="fn"+c;d.state[e]={vars:[],body:[],own:{}};d.state.computing=e;var f=d.nextId();d.recurse(a,f);d.return_(f);d.state.inputs.push(e);a.watchId=c});this.state.computing="fn";this.stage="main";this.recurse(e);f='"'+this.USE+" "+this.STRICT+'";\n'+this.filterPrefix()+"var fn="+this.generateFunction("fn","s,l,a,i")+f+this.watchFns()+"return fn;";f=(new Function("$filter","ensureSafeMemberName","ensureSafeObject","ensureSafeFunction","ifDefined","plus",
"text",f))(this.$filter,Ba,na,kd,Wf,ld,a);this.state=this.stage=u;f.literal=pd(e);f.constant=e.constant;return f},USE:"use",STRICT:"strict",watchFns:function(){var a=[],c=this.state.inputs,d=this;n(c,function(c){a.push("var "+c+"="+d.generateFunction(c,"s"))});c.length&&a.push("fn.inputs=["+c.join(",")+"];");return a.join("")},generateFunction:function(a,c){return"function("+c+"){"+this.varsPrefix(a)+this.body(a)+"};"},filterPrefix:function(){var a=[],c=this;n(this.state.filters,function(d,e){a.push(d+
"=$filter("+c.escape(e)+")")});return a.length?"var "+a.join(",")+";":""},varsPrefix:function(a){return this.state[a].vars.length?"var "+this.state[a].vars.join(",")+";":""},body:function(a){return this.state[a].body.join("")},recurse:function(a,c,d,e,f,g){var h,l,k=this,m,r;e=e||w;if(!g&&y(a.watchId))c=c||this.nextId(),this.if_("i",this.lazyAssign(c,this.computedMember("i",a.watchId)),this.lazyRecurse(a,c,d,e,f,!0));else switch(a.type){case q.Program:n(a.body,function(c,d){k.recurse(c.expression,
u,u,function(a){l=a});d!==a.body.length-1?k.current().body.push(l,";"):k.return_(l)});break;case q.Literal:r=this.escape(a.value);this.assign(c,r);e(r);break;case q.UnaryExpression:this.recurse(a.argument,u,u,function(a){l=a});r=a.operator+"("+this.ifDefined(l,0)+")";this.assign(c,r);e(r);break;case q.BinaryExpression:this.recurse(a.left,u,u,function(a){h=a});this.recurse(a.right,u,u,function(a){l=a});r="+"===a.operator?this.plus(h,l):"-"===a.operator?this.ifDefined(h,0)+a.operator+this.ifDefined(l,
0):"("+h+")"+a.operator+"("+l+")";this.assign(c,r);e(r);break;case q.LogicalExpression:c=c||this.nextId();k.recurse(a.left,c);k.if_("&&"===a.operator?c:k.not(c),k.lazyRecurse(a.right,c));e(c);break;case q.ConditionalExpression:c=c||this.nextId();k.recurse(a.test,c);k.if_(c,k.lazyRecurse(a.alternate,c),k.lazyRecurse(a.consequent,c));e(c);break;case q.Identifier:c=c||this.nextId();d&&(d.context="inputs"===k.stage?"s":this.assign(this.nextId(),this.getHasOwnProperty("l",a.name)+"?l:s"),d.computed=!1,
d.name=a.name);Ba(a.name);k.if_("inputs"===k.stage||k.not(k.getHasOwnProperty("l",a.name)),function(){k.if_("inputs"===k.stage||"s",function(){f&&1!==f&&k.if_(k.not(k.nonComputedMember("s",a.name)),k.lazyAssign(k.nonComputedMember("s",a.name),"{}"));k.assign(c,k.nonComputedMember("s",a.name))})},c&&k.lazyAssign(c,k.nonComputedMember("l",a.name)));(k.state.expensiveChecks||Fb(a.name))&&k.addEnsureSafeObject(c);e(c);break;case q.MemberExpression:h=d&&(d.context=this.nextId())||this.nextId();c=c||this.nextId();
k.recurse(a.object,h,u,function(){k.if_(k.notNull(h),function(){if(a.computed)l=k.nextId(),k.recurse(a.property,l),k.addEnsureSafeMemberName(l),f&&1!==f&&k.if_(k.not(k.computedMember(h,l)),k.lazyAssign(k.computedMember(h,l),"{}")),r=k.ensureSafeObject(k.computedMember(h,l)),k.assign(c,r),d&&(d.computed=!0,d.name=l);else{Ba(a.property.name);f&&1!==f&&k.if_(k.not(k.nonComputedMember(h,a.property.name)),k.lazyAssign(k.nonComputedMember(h,a.property.name),"{}"));r=k.nonComputedMember(h,a.property.name);
if(k.state.expensiveChecks||Fb(a.property.name))r=k.ensureSafeObject(r);k.assign(c,r);d&&(d.computed=!1,d.name=a.property.name)}e(c)})},!!f);break;case q.CallExpression:c=c||this.nextId();a.filter?(l=k.filter(a.callee.name),m=[],n(a.arguments,function(a){var c=k.nextId();k.recurse(a,c);m.push(c)}),r=l+"("+m.join(",")+")",k.assign(c,r),e(c)):(l=k.nextId(),h={},m=[],k.recurse(a.callee,l,h,function(){k.if_(k.notNull(l),function(){k.addEnsureSafeFunction(l);n(a.arguments,function(a){k.recurse(a,k.nextId(),
u,function(a){m.push(k.ensureSafeObject(a))})});h.name?(k.state.expensiveChecks||k.addEnsureSafeObject(h.context),r=k.member(h.context,h.name,h.computed)+"("+m.join(",")+")"):r=l+"("+m.join(",")+")";r=k.ensureSafeObject(r);k.assign(c,r);e(c)})}));break;case q.AssignmentExpression:l=this.nextId();h={};if(!nd(a.left))throw ca("lval");this.recurse(a.left,u,h,function(){k.if_(k.notNull(h.context),function(){k.recurse(a.right,l);k.addEnsureSafeObject(k.member(h.context,h.name,h.computed));r=k.member(h.context,
h.name,h.computed)+a.operator+l;k.assign(c,r);e(c||r)})},1);break;case q.ArrayExpression:m=[];n(a.elements,function(a){k.recurse(a,k.nextId(),u,function(a){m.push(a)})});r="["+m.join(",")+"]";this.assign(c,r);e(r);break;case q.ObjectExpression:m=[];n(a.properties,function(a){k.recurse(a.value,k.nextId(),u,function(c){m.push(k.escape(a.key.type===q.Identifier?a.key.name:""+a.key.value)+":"+c)})});r="{"+m.join(",")+"}";this.assign(c,r);e(r);break;case q.ThisExpression:this.assign(c,"s");e("s");break;
case q.NGValueParameter:this.assign(c,"v"),e("v")}},getHasOwnProperty:function(a,c){var d=a+"."+c,e=this.current().own;e.hasOwnProperty(d)||(e[d]=this.nextId(!1,a+"&&("+this.escape(c)+" in "+a+")"));return e[d]},assign:function(a,c){if(a)return this.current().body.push(a,"=",c,";"),a},filter:function(a){this.state.filters.hasOwnProperty(a)||(this.state.filters[a]=this.nextId(!0));return this.state.filters[a]},ifDefined:function(a,c){return"ifDefined("+a+","+this.escape(c)+")"},plus:function(a,c){return"plus("+
a+","+c+")"},return_:function(a){this.current().body.push("return ",a,";")},if_:function(a,c,d){if(!0===a)c();else{var e=this.current().body;e.push("if(",a,"){");c();e.push("}");d&&(e.push("else{"),d(),e.push("}"))}},not:function(a){return"!("+a+")"},notNull:function(a){return a+"!=null"},nonComputedMember:function(a,c){return a+"."+c},computedMember:function(a,c){return a+"["+c+"]"},member:function(a,c,d){return d?this.computedMember(a,c):this.nonComputedMember(a,c)},addEnsureSafeObject:function(a){this.current().body.push(this.ensureSafeObject(a),
";")},addEnsureSafeMemberName:function(a){this.current().body.push(this.ensureSafeMemberName(a),";")},addEnsureSafeFunction:function(a){this.current().body.push(this.ensureSafeFunction(a),";")},ensureSafeObject:function(a){return"ensureSafeObject("+a+",text)"},ensureSafeMemberName:function(a){return"ensureSafeMemberName("+a+",text)"},ensureSafeFunction:function(a){return"ensureSafeFunction("+a+",text)"},lazyRecurse:function(a,c,d,e,f,g){var h=this;return function(){h.recurse(a,c,d,e,f,g)}},lazyAssign:function(a,
c){var d=this;return function(){d.assign(a,c)}},stringEscapeRegex:/[^ a-zA-Z0-9]/g,stringEscapeFn:function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)},escape:function(a){if(L(a))return"'"+a.replace(this.stringEscapeRegex,this.stringEscapeFn)+"'";if(V(a))return a.toString();if(!0===a)return"true";if(!1===a)return"false";if(null===a)return"null";if("undefined"===typeof a)return"undefined";throw ca("esc");},nextId:function(a,c){var d="v"+this.state.nextId++;a||this.current().vars.push(d+
(c?"="+c:""));return d},current:function(){return this.state[this.state.computing]}};rd.prototype={compile:function(a,c){var d=this,e=this.astBuilder.ast(a);this.expression=a;this.expensiveChecks=c;U(e,d.$filter);var f,g;if(f=od(e))g=this.recurse(f);f=md(e.body);var h;f&&(h=[],n(f,function(a,c){var e=d.recurse(a);a.input=e;h.push(e);a.watchId=c}));var l=[];n(e.body,function(a){l.push(d.recurse(a.expression))});f=0===e.body.length?function(){}:1===e.body.length?l[0]:function(a,c){var d;n(l,function(e){d=
e(a,c)});return d};g&&(f.assign=function(a,c,d){return g(a,d,c)});h&&(f.inputs=h);f.literal=pd(e);f.constant=e.constant;return f},recurse:function(a,c,d){var e,f,g=this,h;if(a.input)return this.inputs(a.input,a.watchId);switch(a.type){case q.Literal:return this.value(a.value,c);case q.UnaryExpression:return f=this.recurse(a.argument),this["unary"+a.operator](f,c);case q.BinaryExpression:return e=this.recurse(a.left),f=this.recurse(a.right),this["binary"+a.operator](e,f,c);case q.LogicalExpression:return e=
this.recurse(a.left),f=this.recurse(a.right),this["binary"+a.operator](e,f,c);case q.ConditionalExpression:return this["ternary?:"](this.recurse(a.test),this.recurse(a.alternate),this.recurse(a.consequent),c);case q.Identifier:return Ba(a.name,g.expression),g.identifier(a.name,g.expensiveChecks||Fb(a.name),c,d,g.expression);case q.MemberExpression:return e=this.recurse(a.object,!1,!!d),a.computed||(Ba(a.property.name,g.expression),f=a.property.name),a.computed&&(f=this.recurse(a.property)),a.computed?
this.computedMember(e,f,c,d,g.expression):this.nonComputedMember(e,f,g.expensiveChecks,c,d,g.expression);case q.CallExpression:return h=[],n(a.arguments,function(a){h.push(g.recurse(a))}),a.filter&&(f=this.$filter(a.callee.name)),a.filter||(f=this.recurse(a.callee,!0)),a.filter?function(a,d,e,g){for(var n=[],q=0;q<h.length;++q)n.push(h[q](a,d,e,g));a=f.apply(u,n,g);return c?{context:u,name:u,value:a}:a}:function(a,d,e,r){var n=f(a,d,e,r),q;if(null!=n.value){na(n.context,g.expression);kd(n.value,g.expression);
q=[];for(var u=0;u<h.length;++u)q.push(na(h[u](a,d,e,r),g.expression));q=na(n.value.apply(n.context,q),g.expression)}return c?{value:q}:q};case q.AssignmentExpression:return e=this.recurse(a.left,!0,1),f=this.recurse(a.right),function(a,d,h,n){var s=e(a,d,h,n);a=f(a,d,h,n);na(s.value,g.expression);s.context[s.name]=a;return c?{value:a}:a};case q.ArrayExpression:return h=[],n(a.elements,function(a){h.push(g.recurse(a))}),function(a,d,e,f){for(var g=[],n=0;n<h.length;++n)g.push(h[n](a,d,e,f));return c?
{value:g}:g};case q.ObjectExpression:return h=[],n(a.properties,function(a){h.push({key:a.key.type===q.Identifier?a.key.name:""+a.key.value,value:g.recurse(a.value)})}),function(a,d,e,f){for(var g={},n=0;n<h.length;++n)g[h[n].key]=h[n].value(a,d,e,f);return c?{value:g}:g};case q.ThisExpression:return function(a){return c?{value:a}:a};case q.NGValueParameter:return function(a,d,e,f){return c?{value:e}:e}}},"unary+":function(a,c){return function(d,e,f,g){d=a(d,e,f,g);d=y(d)?+d:0;return c?{value:d}:
d}},"unary-":function(a,c){return function(d,e,f,g){d=a(d,e,f,g);d=y(d)?-d:0;return c?{value:d}:d}},"unary!":function(a,c){return function(d,e,f,g){d=!a(d,e,f,g);return c?{value:d}:d}},"binary+":function(a,c,d){return function(e,f,g,h){var l=a(e,f,g,h);e=c(e,f,g,h);l=ld(l,e);return d?{value:l}:l}},"binary-":function(a,c,d){return function(e,f,g,h){var l=a(e,f,g,h);e=c(e,f,g,h);l=(y(l)?l:0)-(y(e)?e:0);return d?{value:l}:l}},"binary*":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)*c(e,f,g,h);
return d?{value:e}:e}},"binary/":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)/c(e,f,g,h);return d?{value:e}:e}},"binary%":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)%c(e,f,g,h);return d?{value:e}:e}},"binary===":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)===c(e,f,g,h);return d?{value:e}:e}},"binary!==":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)!==c(e,f,g,h);return d?{value:e}:e}},"binary==":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)==c(e,f,g,h);return d?
{value:e}:e}},"binary!=":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)!=c(e,f,g,h);return d?{value:e}:e}},"binary<":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)<c(e,f,g,h);return d?{value:e}:e}},"binary>":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)>c(e,f,g,h);return d?{value:e}:e}},"binary<=":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)<=c(e,f,g,h);return d?{value:e}:e}},"binary>=":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)>=c(e,f,g,h);return d?{value:e}:
e}},"binary&&":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)&&c(e,f,g,h);return d?{value:e}:e}},"binary||":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)||c(e,f,g,h);return d?{value:e}:e}},"ternary?:":function(a,c,d,e){return function(f,g,h,l){f=a(f,g,h,l)?c(f,g,h,l):d(f,g,h,l);return e?{value:f}:f}},value:function(a,c){return function(){return c?{context:u,name:u,value:a}:a}},identifier:function(a,c,d,e,f){return function(g,h,l,k){g=h&&a in h?h:g;e&&1!==e&&g&&!g[a]&&(g[a]={});h=g?
g[a]:u;c&&na(h,f);return d?{context:g,name:a,value:h}:h}},computedMember:function(a,c,d,e,f){return function(g,h,l,k){var m=a(g,h,l,k),n,s;null!=m&&(n=c(g,h,l,k),Ba(n,f),e&&1!==e&&m&&!m[n]&&(m[n]={}),s=m[n],na(s,f));return d?{context:m,name:n,value:s}:s}},nonComputedMember:function(a,c,d,e,f,g){return function(h,l,k,m){h=a(h,l,k,m);f&&1!==f&&h&&!h[c]&&(h[c]={});l=null!=h?h[c]:u;(d||Fb(c))&&na(l,g);return e?{context:h,name:c,value:l}:l}},inputs:function(a,c){return function(d,e,f,g){return g?g[c]:
a(d,e,f)}}};var hc=function(a,c,d){this.lexer=a;this.$filter=c;this.options=d;this.ast=new q(this.lexer);this.astCompiler=d.csp?new rd(this.ast,c):new qd(this.ast,c)};hc.prototype={constructor:hc,parse:function(a){return this.astCompiler.compile(a,this.options.expensiveChecks)}};ga();ga();var Xf=Object.prototype.valueOf,Ca=F("$sce"),oa={HTML:"html",CSS:"css",URL:"url",RESOURCE_URL:"resourceUrl",JS:"js"},ea=F("$compile"),Z=W.createElement("a"),vd=Aa(N.location.href);wd.$inject=["$document"];Kc.$inject=
["$provide"];xd.$inject=["$locale"];zd.$inject=["$locale"];var Cd=".",gg={yyyy:$("FullYear",4),yy:$("FullYear",2,0,!0),y:$("FullYear",1),MMMM:Hb("Month"),MMM:Hb("Month",!0),MM:$("Month",2,1),M:$("Month",1,1),dd:$("Date",2),d:$("Date",1),HH:$("Hours",2),H:$("Hours",1),hh:$("Hours",2,-12),h:$("Hours",1,-12),mm:$("Minutes",2),m:$("Minutes",1),ss:$("Seconds",2),s:$("Seconds",1),sss:$("Milliseconds",3),EEEE:Hb("Day"),EEE:Hb("Day",!0),a:function(a,c){return 12>a.getHours()?c.AMPMS[0]:c.AMPMS[1]},Z:function(a,
c,d){a=-1*d;return a=(0<=a?"+":"")+(Gb(Math[0<a?"floor":"ceil"](a/60),2)+Gb(Math.abs(a%60),2))},ww:Ed(2),w:Ed(1),G:jc,GG:jc,GGG:jc,GGGG:function(a,c){return 0>=a.getFullYear()?c.ERANAMES[0]:c.ERANAMES[1]}},fg=/((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,eg=/^\-?\d+$/;yd.$inject=["$locale"];var bg=qa(E),cg=qa(pb);Ad.$inject=["$parse"];var he=qa({restrict:"E",compile:function(a,c){if(!c.href&&!c.xlinkHref)return function(a,c){if("a"===c[0].nodeName.toLowerCase()){var f=
"[object SVGAnimatedString]"===sa.call(c.prop("href"))?"xlink:href":"href";c.on("click",function(a){c.attr(f)||a.preventDefault()})}}}}),qb={};n(zb,function(a,c){function d(a,d,f){a.$watch(f[e],function(a){f.$set(c,!!a)})}if("multiple"!=a){var e=xa("ng-"+c),f=d;"checked"===a&&(f=function(a,c,f){f.ngModel!==f[e]&&d(a,c,f)});qb[e]=function(){return{restrict:"A",priority:100,link:f}}}});n(Tc,function(a,c){qb[c]=function(){return{priority:100,link:function(a,e,f){if("ngPattern"===c&&"/"==f.ngPattern.charAt(0)&&
(e=f.ngPattern.match(ig))){f.$set("ngPattern",new RegExp(e[1],e[2]));return}a.$watch(f[c],function(a){f.$set(c,a)})}}}});n(["src","srcset","href"],function(a){var c=xa("ng-"+a);qb[c]=function(){return{priority:99,link:function(d,e,f){var g=a,h=a;"href"===a&&"[object SVGAnimatedString]"===sa.call(e.prop("href"))&&(h="xlinkHref",f.$attr[h]="xlink:href",g=null);f.$observe(c,function(c){c?(f.$set(h,c),gb&&g&&e.prop(g,f[h])):"href"===a&&f.$set(h,null)})}}}});var Ib={$addControl:w,$$renameControl:function(a,
c){a.$name=c},$removeControl:w,$setValidity:w,$setDirty:w,$setPristine:w,$setSubmitted:w};Fd.$inject=["$element","$attrs","$scope","$animate","$interpolate"];var Nd=function(a){return["$timeout",function(c){return{name:"form",restrict:a?"EAC":"E",controller:Fd,compile:function(d,e){d.addClass(Sa).addClass(jb);var f=e.name?"name":a&&e.ngForm?"ngForm":!1;return{pre:function(a,d,e,k){if(!("action"in e)){var m=function(c){a.$apply(function(){k.$commitViewValue();k.$setSubmitted()});c.preventDefault()};
d[0].addEventListener("submit",m,!1);d.on("$destroy",function(){c(function(){d[0].removeEventListener("submit",m,!1)},0,!1)})}var n=k.$$parentForm;f&&(Eb(a,k.$name,k,k.$name),e.$observe(f,function(c){k.$name!==c&&(Eb(a,k.$name,u,k.$name),n.$$renameControl(k,c),Eb(a,k.$name,k,k.$name))}));d.on("$destroy",function(){n.$removeControl(k);f&&Eb(a,e[f],u,k.$name);Q(k,Ib)})}}}}}]},ie=Nd(),ve=Nd(!0),hg=/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/,qg=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,
rg=/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i,sg=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/,Od=/^(\d{4})-(\d{2})-(\d{2})$/,Pd=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,mc=/^(\d{4})-W(\d\d)$/,Qd=/^(\d{4})-(\d\d)$/,Rd=/^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,Sd={text:function(a,c,d,e,f,g){hb(a,c,d,e,f,g);kc(e)},date:ib("date",Od,Kb(Od,["yyyy","MM","dd"]),"yyyy-MM-dd"),"datetime-local":ib("datetimelocal",Pd,Kb(Pd,"yyyy MM dd HH mm ss sss".split(" ")),
"yyyy-MM-ddTHH:mm:ss.sss"),time:ib("time",Rd,Kb(Rd,["HH","mm","ss","sss"]),"HH:mm:ss.sss"),week:ib("week",mc,function(a,c){if(da(a))return a;if(L(a)){mc.lastIndex=0;var d=mc.exec(a);if(d){var e=+d[1],f=+d[2],g=d=0,h=0,l=0,k=Dd(e),f=7*(f-1);c&&(d=c.getHours(),g=c.getMinutes(),h=c.getSeconds(),l=c.getMilliseconds());return new Date(e,0,k.getDate()+f,d,g,h,l)}}return NaN},"yyyy-Www"),month:ib("month",Qd,Kb(Qd,["yyyy","MM"]),"yyyy-MM"),number:function(a,c,d,e,f,g){Hd(a,c,d,e);hb(a,c,d,e,f,g);e.$$parserName=
"number";e.$parsers.push(function(a){return e.$isEmpty(a)?null:sg.test(a)?parseFloat(a):u});e.$formatters.push(function(a){if(!e.$isEmpty(a)){if(!V(a))throw Lb("numfmt",a);a=a.toString()}return a});if(y(d.min)||d.ngMin){var h;e.$validators.min=function(a){return e.$isEmpty(a)||v(h)||a>=h};d.$observe("min",function(a){y(a)&&!V(a)&&(a=parseFloat(a,10));h=V(a)&&!isNaN(a)?a:u;e.$validate()})}if(y(d.max)||d.ngMax){var l;e.$validators.max=function(a){return e.$isEmpty(a)||v(l)||a<=l};d.$observe("max",function(a){y(a)&&
!V(a)&&(a=parseFloat(a,10));l=V(a)&&!isNaN(a)?a:u;e.$validate()})}},url:function(a,c,d,e,f,g){hb(a,c,d,e,f,g);kc(e);e.$$parserName="url";e.$validators.url=function(a,c){var d=a||c;return e.$isEmpty(d)||qg.test(d)}},email:function(a,c,d,e,f,g){hb(a,c,d,e,f,g);kc(e);e.$$parserName="email";e.$validators.email=function(a,c){var d=a||c;return e.$isEmpty(d)||rg.test(d)}},radio:function(a,c,d,e){v(d.name)&&c.attr("name",++lb);c.on("click",function(a){c[0].checked&&e.$setViewValue(d.value,a&&a.type)});e.$render=
function(){c[0].checked=d.value==e.$viewValue};d.$observe("value",e.$render)},checkbox:function(a,c,d,e,f,g,h,l){var k=Id(l,a,"ngTrueValue",d.ngTrueValue,!0),m=Id(l,a,"ngFalseValue",d.ngFalseValue,!1);c.on("click",function(a){e.$setViewValue(c[0].checked,a&&a.type)});e.$render=function(){c[0].checked=e.$viewValue};e.$isEmpty=function(a){return!1===a};e.$formatters.push(function(a){return ka(a,k)});e.$parsers.push(function(a){return a?k:m})},hidden:w,button:w,submit:w,reset:w,file:w},Ec=["$browser",
"$sniffer","$filter","$parse",function(a,c,d,e){return{restrict:"E",require:["?ngModel"],link:{pre:function(f,g,h,l){l[0]&&(Sd[E(h.type)]||Sd.text)(f,g,h,l[0],c,a,d,e)}}}}],tg=/^(true|false|\d+)$/,Ne=function(){return{restrict:"A",priority:100,compile:function(a,c){return tg.test(c.ngValue)?function(a,c,f){f.$set("value",a.$eval(f.ngValue))}:function(a,c,f){a.$watch(f.ngValue,function(a){f.$set("value",a)})}}}},ne=["$compile",function(a){return{restrict:"AC",compile:function(c){a.$$addBindingClass(c);
return function(c,e,f){a.$$addBindingInfo(e,f.ngBind);e=e[0];c.$watch(f.ngBind,function(a){e.textContent=a===u?"":a})}}}}],pe=["$interpolate","$compile",function(a,c){return{compile:function(d){c.$$addBindingClass(d);return function(d,f,g){d=a(f.attr(g.$attr.ngBindTemplate));c.$$addBindingInfo(f,d.expressions);f=f[0];g.$observe("ngBindTemplate",function(a){f.textContent=a===u?"":a})}}}}],oe=["$sce","$parse","$compile",function(a,c,d){return{restrict:"A",compile:function(e,f){var g=c(f.ngBindHtml),
h=c(f.ngBindHtml,function(a){return(a||"").toString()});d.$$addBindingClass(e);return function(c,e,f){d.$$addBindingInfo(e,f.ngBindHtml);c.$watch(h,function(){e.html(a.getTrustedHtml(g(c))||"")})}}}}],Me=qa({restrict:"A",require:"ngModel",link:function(a,c,d,e){e.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),qe=lc("",!0),se=lc("Odd",0),re=lc("Even",1),te=Ma({compile:function(a,c){c.$set("ngCloak",u);a.removeClass("ng-cloak")}}),ue=[function(){return{restrict:"A",scope:!0,controller:"@",
priority:500}}],Jc={},ug={blur:!0,focus:!0};n("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "),function(a){var c=xa("ng-"+a);Jc[c]=["$parse","$rootScope",function(d,e){return{restrict:"A",compile:function(f,g){var h=d(g[c],null,!0);return function(c,d){d.on(a,function(d){var f=function(){h(c,{$event:d})};ug[a]&&e.$$phase?c.$evalAsync(f):c.$apply(f)})}}}}]});var xe=["$animate",function(a){return{multiElement:!0,
transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,link:function(c,d,e,f,g){var h,l,k;c.$watch(e.ngIf,function(c){c?l||g(function(c,f){l=f;c[c.length++]=W.createComment(" end ngIf: "+e.ngIf+" ");h={clone:c};a.enter(c,d.parent(),d)}):(k&&(k.remove(),k=null),l&&(l.$destroy(),l=null),h&&(k=ob(h.clone),a.leave(k).then(function(){k=null}),h=null))})}}}],ye=["$templateRequest","$anchorScroll","$animate","$sce",function(a,c,d,e){return{restrict:"ECA",priority:400,terminal:!0,transclude:"element",
controller:aa.noop,compile:function(f,g){var h=g.ngInclude||g.src,l=g.onload||"",k=g.autoscroll;return function(f,g,n,q,u){var v=0,t,p,x,w=function(){p&&(p.remove(),p=null);t&&(t.$destroy(),t=null);x&&(d.leave(x).then(function(){p=null}),p=x,x=null)};f.$watch(e.parseAsResourceUrl(h),function(e){var h=function(){!y(k)||k&&!f.$eval(k)||c()},n=++v;e?(a(e,!0).then(function(a){if(n===v){var c=f.$new();q.template=a;a=u(c,function(a){w();d.enter(a,null,g).then(h)});t=c;x=a;t.$emit("$includeContentLoaded",
e);f.$eval(l)}},function(){n===v&&(w(),f.$emit("$includeContentError",e))}),f.$emit("$includeContentRequested",e)):(w(),q.template=null)})}}}}],Pe=["$compile",function(a){return{restrict:"ECA",priority:-400,require:"ngInclude",link:function(c,d,e,f){/SVG/.test(d[0].toString())?(d.empty(),a(Mc(f.template,W).childNodes)(c,function(a){d.append(a)},{futureParentElement:d})):(d.html(f.template),a(d.contents())(c))}}}],ze=Ma({priority:450,compile:function(){return{pre:function(a,c,d){a.$eval(d.ngInit)}}}}),
Le=function(){return{restrict:"A",priority:100,require:"ngModel",link:function(a,c,d,e){var f=c.attr(d.$attr.ngList)||", ",g="false"!==d.ngTrim,h=g?T(f):f;e.$parsers.push(function(a){if(!v(a)){var c=[];a&&n(a.split(h),function(a){a&&c.push(g?T(a):a)});return c}});e.$formatters.push(function(a){return K(a)?a.join(f):u});e.$isEmpty=function(a){return!a||!a.length}}}},jb="ng-valid",Jd="ng-invalid",Sa="ng-pristine",Jb="ng-dirty",Ld="ng-pending",Lb=new F("ngModel"),vg=["$scope","$exceptionHandler","$attrs",
"$element","$parse","$animate","$timeout","$rootScope","$q","$interpolate",function(a,c,d,e,f,g,h,l,k,m){this.$modelValue=this.$viewValue=Number.NaN;this.$$rawModelValue=u;this.$validators={};this.$asyncValidators={};this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$untouched=!0;this.$touched=!1;this.$pristine=!0;this.$dirty=!1;this.$valid=!0;this.$invalid=!1;this.$error={};this.$$success={};this.$pending=u;this.$name=m(d.name||"",!1)(a);var r=f(d.ngModel),s=r.assign,q=r,H=s,
M=null,t,p=this;this.$$setOptions=function(a){if((p.$options=a)&&a.getterSetter){var c=f(d.ngModel+"()"),g=f(d.ngModel+"($$$p)");q=function(a){var d=r(a);G(d)&&(d=c(a));return d};H=function(a,c){G(r(a))?g(a,{$$$p:p.$modelValue}):s(a,p.$modelValue)}}else if(!r.assign)throw Lb("nonassign",d.ngModel,va(e));};this.$render=w;this.$isEmpty=function(a){return v(a)||""===a||null===a||a!==a};var x=e.inheritedData("$formController")||Ib,z=0;Gd({ctrl:this,$element:e,set:function(a,c){a[c]=!0},unset:function(a,
c){delete a[c]},parentForm:x,$animate:g});this.$setPristine=function(){p.$dirty=!1;p.$pristine=!0;g.removeClass(e,Jb);g.addClass(e,Sa)};this.$setDirty=function(){p.$dirty=!0;p.$pristine=!1;g.removeClass(e,Sa);g.addClass(e,Jb);x.$setDirty()};this.$setUntouched=function(){p.$touched=!1;p.$untouched=!0;g.setClass(e,"ng-untouched","ng-touched")};this.$setTouched=function(){p.$touched=!0;p.$untouched=!1;g.setClass(e,"ng-touched","ng-untouched")};this.$rollbackViewValue=function(){h.cancel(M);p.$viewValue=
p.$$lastCommittedViewValue;p.$render()};this.$validate=function(){if(!V(p.$modelValue)||!isNaN(p.$modelValue)){var a=p.$$rawModelValue,c=p.$valid,d=p.$modelValue,e=p.$options&&p.$options.allowInvalid;p.$$runValidators(a,p.$$lastCommittedViewValue,function(f){e||c===f||(p.$modelValue=f?a:u,p.$modelValue!==d&&p.$$writeModelToScope())})}};this.$$runValidators=function(a,c,d){function e(){var d=!0;n(p.$validators,function(e,f){var h=e(a,c);d=d&&h;g(f,h)});return d?!0:(n(p.$asyncValidators,function(a,
c){g(c,null)}),!1)}function f(){var d=[],e=!0;n(p.$asyncValidators,function(f,h){var k=f(a,c);if(!k||!G(k.then))throw Lb("$asyncValidators",k);g(h,u);d.push(k.then(function(){g(h,!0)},function(a){e=!1;g(h,!1)}))});d.length?k.all(d).then(function(){h(e)},w):h(!0)}function g(a,c){l===z&&p.$setValidity(a,c)}function h(a){l===z&&d(a)}z++;var l=z;(function(){var a=p.$$parserName||"parse";if(t===u)g(a,null);else return t||(n(p.$validators,function(a,c){g(c,null)}),n(p.$asyncValidators,function(a,c){g(c,
null)})),g(a,t),t;return!0})()?e()?f():h(!1):h(!1)};this.$commitViewValue=function(){var a=p.$viewValue;h.cancel(M);if(p.$$lastCommittedViewValue!==a||""===a&&p.$$hasNativeValidators)p.$$lastCommittedViewValue=a,p.$pristine&&this.$setDirty(),this.$$parseAndValidate()};this.$$parseAndValidate=function(){var c=p.$$lastCommittedViewValue;if(t=v(c)?u:!0)for(var d=0;d<p.$parsers.length;d++)if(c=p.$parsers[d](c),v(c)){t=!1;break}V(p.$modelValue)&&isNaN(p.$modelValue)&&(p.$modelValue=q(a));var e=p.$modelValue,
f=p.$options&&p.$options.allowInvalid;p.$$rawModelValue=c;f&&(p.$modelValue=c,p.$modelValue!==e&&p.$$writeModelToScope());p.$$runValidators(c,p.$$lastCommittedViewValue,function(a){f||(p.$modelValue=a?c:u,p.$modelValue!==e&&p.$$writeModelToScope())})};this.$$writeModelToScope=function(){H(a,p.$modelValue);n(p.$viewChangeListeners,function(a){try{a()}catch(d){c(d)}})};this.$setViewValue=function(a,c){p.$viewValue=a;p.$options&&!p.$options.updateOnDefault||p.$$debounceViewValueCommit(c)};this.$$debounceViewValueCommit=
function(c){var d=0,e=p.$options;e&&y(e.debounce)&&(e=e.debounce,V(e)?d=e:V(e[c])?d=e[c]:V(e["default"])&&(d=e["default"]));h.cancel(M);d?M=h(function(){p.$commitViewValue()},d):l.$$phase?p.$commitViewValue():a.$apply(function(){p.$commitViewValue()})};a.$watch(function(){var c=q(a);if(c!==p.$modelValue&&(p.$modelValue===p.$modelValue||c===c)){p.$modelValue=p.$$rawModelValue=c;t=u;for(var d=p.$formatters,e=d.length,f=c;e--;)f=d[e](f);p.$viewValue!==f&&(p.$viewValue=p.$$lastCommittedViewValue=f,p.$render(),
p.$$runValidators(c,f,w))}return c})}],Ke=["$rootScope",function(a){return{restrict:"A",require:["ngModel","^?form","^?ngModelOptions"],controller:vg,priority:1,compile:function(c){c.addClass(Sa).addClass("ng-untouched").addClass(jb);return{pre:function(a,c,f,g){var h=g[0],l=g[1]||Ib;h.$$setOptions(g[2]&&g[2].$options);l.$addControl(h);f.$observe("name",function(a){h.$name!==a&&l.$$renameControl(h,a)});a.$on("$destroy",function(){l.$removeControl(h)})},post:function(c,e,f,g){var h=g[0];if(h.$options&&
h.$options.updateOn)e.on(h.$options.updateOn,function(a){h.$$debounceViewValueCommit(a&&a.type)});e.on("blur",function(e){h.$touched||(a.$$phase?c.$evalAsync(h.$setTouched):c.$apply(h.$setTouched))})}}}}}],wg=/(\s+|^)default(\s+|$)/,Oe=function(){return{restrict:"A",controller:["$scope","$attrs",function(a,c){var d=this;this.$options=ua(a.$eval(c.ngModelOptions));this.$options.updateOn!==u?(this.$options.updateOnDefault=!1,this.$options.updateOn=T(this.$options.updateOn.replace(wg,function(){d.$options.updateOnDefault=
!0;return" "}))):this.$options.updateOnDefault=!0}]}},Ae=Ma({terminal:!0,priority:1E3}),xg=F("ngOptions"),yg=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/,Ie=["$compile","$parse",function(a,c){function d(a,d,e){function f(a,c,d,e,g){this.selectValue=a;this.viewValue=c;this.label=d;this.group=e;this.disabled=g}
var m=a.match(yg);if(!m)throw xg("iexp",a,va(d));var n=m[5]||m[7],s=m[6];a=/ as /.test(m[0])&&m[1];var q=m[9];d=c(m[2]?m[1]:n);var u=a&&c(a)||d,v=q&&c(q),t=q?function(a,c){return v(e,c)}:function(a){return Fa(a)},p=function(a,c){return t(a,D(a,c))},x=c(m[2]||m[1]),w=c(m[3]||""),y=c(m[4]||""),B=c(m[8]),z={},D=s?function(a,c){z[s]=c;z[n]=a;return z}:function(a){z[n]=a;return z};return{trackBy:q,getTrackByValue:p,getWatchables:c(B,function(a){var c=[];a=a||[];Object.keys(a).forEach(function(d){var f=
D(a[d],d);d=t(a[d],f);c.push(d);if(m[2]||m[1])d=x(e,f),c.push(d);m[4]&&(f=y(e,f),c.push(f))});return c}),getOptions:function(){var a=[],c={},d=B(e)||[],g;if(!s&&Da(d))g=d;else{g=[];for(var h in d)d.hasOwnProperty(h)&&"$"!==h.charAt(0)&&g.push(h)}h=g.length;for(var m=0;m<h;m++){var n=d===g?m:g[m],r=D(d[n],n),v=u(e,r),n=t(v,r),z=x(e,r),M=w(e,r),r=y(e,r),v=new f(n,v,z,M,r);a.push(v);c[n]=v}return{items:a,selectValueMap:c,getOptionFromViewValue:function(a){return c[p(a)]},getViewValueFromOption:function(a){return q?
aa.copy(a.viewValue):a.viewValue}}}}}var e=W.createElement("option"),f=W.createElement("optgroup");return{restrict:"A",terminal:!0,require:["select","?ngModel"],link:function(c,h,l,k){function m(a,c){a.element=c;c.disabled=a.disabled;a.value!==c.value&&(c.value=a.selectValue);a.label!==c.label&&(c.label=a.label,c.textContent=a.label)}function r(a,c,d,e){c&&E(c.nodeName)===d?d=c:(d=e.cloneNode(!1),c?a.insertBefore(d,c):a.appendChild(d));return d}function q(a){for(var c;a;)c=a.nextSibling,Xb(a),a=c}
function u(a){var c=p&&p[0],d=O&&O[0];if(c||d)for(;a&&(a===c||a===d);)a=a.nextSibling;return a}function v(){var a=D&&t.readValue();D=C.getOptions();var c={},d=h[0].firstChild;B&&h.prepend(p);d=u(d);D.items.forEach(function(a){var g,k;a.group?(g=c[a.group],g||(g=r(h[0],d,"optgroup",f),d=g.nextSibling,g.label=a.group,g=c[a.group]={groupElement:g,currentOptionElement:g.firstChild}),k=r(g.groupElement,g.currentOptionElement,"option",e),m(a,k),g.currentOptionElement=k.nextSibling):(k=r(h[0],d,"option",
e),m(a,k),d=k.nextSibling)});Object.keys(c).forEach(function(a){q(c[a].currentOptionElement)});q(d);w.$render();if(!w.$isEmpty(a)){var g=t.readValue();if(C.trackBy&&!ka(a,g)||a!==g)w.$setViewValue(g),w.$render()}}var w=k[1];if(w){var t=k[0];k=l.multiple;for(var p,x=0,y=h.children(),I=y.length;x<I;x++)if(""===y[x].value){p=y.eq(x);break}var B=!!p,O=z(e.cloneNode(!1));O.val("?");var D,C=d(l.ngOptions,h,c);k?(w.$isEmpty=function(a){return!a||0===a.length},t.writeValue=function(a){D.items.forEach(function(a){a.element.selected=
!1});a&&a.forEach(function(a){(a=D.getOptionFromViewValue(a))&&!a.disabled&&(a.element.selected=!0)})},t.readValue=function(){var a=h.val()||[],c=[];n(a,function(a){a=D.selectValueMap[a];a.disabled||c.push(D.getViewValueFromOption(a))});return c},C.trackBy&&c.$watchCollection(function(){if(K(w.$viewValue))return w.$viewValue.map(function(a){return C.getTrackByValue(a)})},function(){w.$render()})):(t.writeValue=function(a){var c=D.getOptionFromViewValue(a);c&&!c.disabled?h[0].value!==c.selectValue&&
(O.remove(),B||p.remove(),h[0].value=c.selectValue,c.element.selected=!0,c.element.setAttribute("selected","selected")):null===a||B?(O.remove(),B||h.prepend(p),h.val(""),p.prop("selected",!0),p.attr("selected",!0)):(B||p.remove(),h.prepend(O),h.val("?"),O.prop("selected",!0),O.attr("selected",!0))},t.readValue=function(){var a=D.selectValueMap[h.val()];return a&&!a.disabled?(B||p.remove(),O.remove(),D.getViewValueFromOption(a)):null},C.trackBy&&c.$watch(function(){return C.getTrackByValue(w.$viewValue)},
function(){w.$render()}));B?(p.remove(),a(p)(c),p.removeClass("ng-scope")):p=z(e.cloneNode(!1));v();c.$watchCollection(C.getWatchables,v)}}}}],Be=["$locale","$interpolate","$log",function(a,c,d){var e=/{}/g,f=/^when(Minus)?(.+)$/;return{link:function(g,h,l){function k(a){h.text(a||"")}var m=l.count,r=l.$attr.when&&h.attr(l.$attr.when),q=l.offset||0,u=g.$eval(r)||{},z={},y=c.startSymbol(),t=c.endSymbol(),p=y+m+"-"+q+t,x=aa.noop,C;n(l,function(a,c){var d=f.exec(c);d&&(d=(d[1]?"-":"")+E(d[2]),u[d]=h.attr(l.$attr[c]))});
n(u,function(a,d){z[d]=c(a.replace(e,p))});g.$watch(m,function(c){var e=parseFloat(c),f=isNaN(e);f||e in u||(e=a.pluralCat(e-q));e===C||f&&V(C)&&isNaN(C)||(x(),f=z[e],v(f)?(null!=c&&d.debug("ngPluralize: no rule defined for '"+e+"' in "+r),x=w,k()):x=g.$watch(f,k),C=e)})}}}],Ce=["$parse","$animate",function(a,c){var d=F("ngRepeat"),e=function(a,c,d,e,k,m,n){a[d]=e;k&&(a[k]=m);a.$index=c;a.$first=0===c;a.$last=c===n-1;a.$middle=!(a.$first||a.$last);a.$odd=!(a.$even=0===(c&1))};return{restrict:"A",
multiElement:!0,transclude:"element",priority:1E3,terminal:!0,$$tlb:!0,compile:function(f,g){var h=g.ngRepeat,l=W.createComment(" end ngRepeat: "+h+" "),k=h.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);if(!k)throw d("iexp",h);var m=k[1],r=k[2],q=k[3],v=k[4],k=m.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);if(!k)throw d("iidexp",m);var w=k[3]||k[1],y=k[2];if(q&&(!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(q)||/^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(q)))throw d("badident",
q);var t,p,x,C,I={$id:Fa};v?t=a(v):(x=function(a,c){return Fa(c)},C=function(a){return a});return function(a,f,g,k,m){t&&(p=function(c,d,e){y&&(I[y]=c);I[w]=d;I.$index=e;return t(a,I)});var v=ga();a.$watchCollection(r,function(g){var k,r,t=f[0],A,D=ga(),I,G,L,F,K,E,N;q&&(a[q]=g);if(Da(g))K=g,r=p||x;else for(N in r=p||C,K=[],g)g.hasOwnProperty(N)&&"$"!==N.charAt(0)&&K.push(N);I=K.length;N=Array(I);for(k=0;k<I;k++)if(G=g===K?k:K[k],L=g[G],F=r(G,L,k),v[F])E=v[F],delete v[F],D[F]=E,N[k]=E;else{if(D[F])throw n(N,
function(a){a&&a.scope&&(v[a.id]=a)}),d("dupes",h,F,L);N[k]={id:F,scope:u,clone:u};D[F]=!0}for(A in v){E=v[A];F=ob(E.clone);c.leave(F);if(F[0].parentNode)for(k=0,r=F.length;k<r;k++)F[k].$$NG_REMOVED=!0;E.scope.$destroy()}for(k=0;k<I;k++)if(G=g===K?k:K[k],L=g[G],E=N[k],E.scope){A=t;do A=A.nextSibling;while(A&&A.$$NG_REMOVED);E.clone[0]!=A&&c.move(ob(E.clone),null,z(t));t=E.clone[E.clone.length-1];e(E.scope,k,w,L,y,G,I)}else m(function(a,d){E.scope=d;var f=l.cloneNode(!1);a[a.length++]=f;c.enter(a,
null,z(t));t=f;E.clone=a;D[E.id]=E;e(E.scope,k,w,L,y,G,I)});v=D})}}}}],De=["$animate",function(a){return{restrict:"A",multiElement:!0,link:function(c,d,e){c.$watch(e.ngShow,function(c){a[c?"removeClass":"addClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],we=["$animate",function(a){return{restrict:"A",multiElement:!0,link:function(c,d,e){c.$watch(e.ngHide,function(c){a[c?"addClass":"removeClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],Ee=Ma(function(a,c,d){a.$watch(d.ngStyle,
function(a,d){d&&a!==d&&n(d,function(a,d){c.css(d,"")});a&&c.css(a)},!0)}),Fe=["$animate",function(a){return{require:"ngSwitch",controller:["$scope",function(){this.cases={}}],link:function(c,d,e,f){var g=[],h=[],l=[],k=[],m=function(a,c){return function(){a.splice(c,1)}};c.$watch(e.ngSwitch||e.on,function(c){var d,e;d=0;for(e=l.length;d<e;++d)a.cancel(l[d]);d=l.length=0;for(e=k.length;d<e;++d){var q=ob(h[d].clone);k[d].$destroy();(l[d]=a.leave(q)).then(m(l,d))}h.length=0;k.length=0;(g=f.cases["!"+
c]||f.cases["?"])&&n(g,function(c){c.transclude(function(d,e){k.push(e);var f=c.element;d[d.length++]=W.createComment(" end ngSwitchWhen: ");h.push({clone:d});a.enter(d,f.parent(),f)})})})}}}],Ge=Ma({transclude:"element",priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,c,d,e,f){e.cases["!"+d.ngSwitchWhen]=e.cases["!"+d.ngSwitchWhen]||[];e.cases["!"+d.ngSwitchWhen].push({transclude:f,element:c})}}),He=Ma({transclude:"element",priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,
c,d,e,f){e.cases["?"]=e.cases["?"]||[];e.cases["?"].push({transclude:f,element:c})}}),Je=Ma({restrict:"EAC",link:function(a,c,d,e,f){if(!f)throw F("ngTransclude")("orphan",va(c));f(function(a){c.empty();c.append(a)})}}),je=["$templateCache",function(a){return{restrict:"E",terminal:!0,compile:function(c,d){"text/ng-template"==d.type&&a.put(d.id,c[0].text)}}}],zg={$setViewValue:w,$render:w},Ag=["$element","$scope","$attrs",function(a,c,d){var e=this,f=new Ra;e.ngModelCtrl=zg;e.unknownOption=z(W.createElement("option"));
e.renderUnknownOption=function(c){c="? "+Fa(c)+" ?";e.unknownOption.val(c);a.prepend(e.unknownOption);a.val(c)};c.$on("$destroy",function(){e.renderUnknownOption=w});e.removeUnknownOption=function(){e.unknownOption.parent()&&e.unknownOption.remove()};e.readValue=function(){e.removeUnknownOption();return a.val()};e.writeValue=function(c){e.hasOption(c)?(e.removeUnknownOption(),a.val(c),""===c&&e.emptyOption.prop("selected",!0)):null==c&&e.emptyOption?(e.removeUnknownOption(),a.val("")):e.renderUnknownOption(c)};
e.addOption=function(a,c){Qa(a,'"option value"');""===a&&(e.emptyOption=c);var d=f.get(a)||0;f.put(a,d+1)};e.removeOption=function(a){var c=f.get(a);c&&(1===c?(f.remove(a),""===a&&(e.emptyOption=u)):f.put(a,c-1))};e.hasOption=function(a){return!!f.get(a)}}],ke=function(){return{restrict:"E",require:["select","?ngModel"],controller:Ag,link:function(a,c,d,e){var f=e[1];if(f){var g=e[0];g.ngModelCtrl=f;f.$render=function(){g.writeValue(f.$viewValue)};c.on("change",function(){a.$apply(function(){f.$setViewValue(g.readValue())})});
if(d.multiple){g.readValue=function(){var a=[];n(c.find("option"),function(c){c.selected&&a.push(c.value)});return a};g.writeValue=function(a){var d=new Ra(a);n(c.find("option"),function(a){a.selected=y(d.get(a.value))})};var h,l=NaN;a.$watch(function(){l!==f.$viewValue||ka(h,f.$viewValue)||(h=fa(f.$viewValue),f.$render());l=f.$viewValue});f.$isEmpty=function(a){return!a||0===a.length}}}}}},me=["$interpolate",function(a){function c(a){a[0].hasAttribute("selected")&&(a[0].selected=!0)}return{restrict:"E",
priority:100,compile:function(d,e){if(v(e.value)){var f=a(d.text(),!0);f||e.$set("value",d.text())}return function(a,d,e){var k=d.parent(),m=k.data("$selectController")||k.parent().data("$selectController");m&&m.ngModelCtrl&&(f?a.$watch(f,function(a,f){e.$set("value",a);f!==a&&m.removeOption(f);m.addOption(a,d);m.ngModelCtrl.$render();c(d)}):(m.addOption(e.value,d),m.ngModelCtrl.$render(),c(d)),d.on("$destroy",function(){m.removeOption(e.value);m.ngModelCtrl.$render()}))}}}}],le=qa({restrict:"E",
terminal:!1}),Gc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){e&&(d.required=!0,e.$validators.required=function(a,c){return!d.required||!e.$isEmpty(c)},d.$observe("required",function(){e.$validate()}))}}},Fc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f,g=d.ngPattern||d.pattern;d.$observe("pattern",function(a){L(a)&&0<a.length&&(a=new RegExp("^"+a+"$"));if(a&&!a.test)throw F("ngPattern")("noregexp",g,a,va(c));f=a||u;e.$validate()});
e.$validators.pattern=function(a){return e.$isEmpty(a)||v(f)||f.test(a)}}}}},Ic=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f=-1;d.$observe("maxlength",function(a){a=Y(a);f=isNaN(a)?-1:a;e.$validate()});e.$validators.maxlength=function(a,c){return 0>f||e.$isEmpty(c)||c.length<=f}}}}},Hc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f=0;d.$observe("minlength",function(a){f=Y(a)||0;e.$validate()});e.$validators.minlength=function(a,
c){return e.$isEmpty(c)||c.length>=f}}}}};N.angular.bootstrap?console.log("WARNING: Tried to load angular more than once."):(be(),de(aa),z(W).ready(function(){Yd(W,zc)}))})(window,document);!window.angular.$$csp()&&window.angular.element(document).find("head").prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');
//# sourceMappingURL=angular.min.js.map
;
/**
 * @license AngularJS v1.3.16
 * (c) 2010-2014 Google, Inc. http://angularjs.org
 * License: MIT
 */
(function (window, angular, undefined) {
	'use strict';

	/**
	 * @ngdoc module
	 * @name ngRoute
	 * @description
	 *
	 * # ngRoute
	 *
	 * The `ngRoute` module provides routing and deeplinking services and directives for angular apps.
	 *
	 * ## Example
	 * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
	 *
	 *
	 * <div doc-module-components="ngRoute"></div>
	 */
	/* global -ngRouteModule */
	var ngRouteModule = angular.module('ngRoute', ['ng']).
							provider('$route', $RouteProvider),
		$routeMinErr = angular.$$minErr('ngRoute');

	/**
	 * @ngdoc provider
	 * @name $routeProvider
	 *
	 * @description
	 *
	 * Used for configuring routes.
	 *
	 * ## Example
	 * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
	 *
	 * ## Dependencies
	 * Requires the {@link ngRoute `ngRoute`} module to be installed.
	 */
	function $RouteProvider() {
		function inherit(parent, extra) {
			return angular.extend(Object.create(parent), extra);
		}

		var routes = {};

		/**
		 * @ngdoc method
		 * @name $routeProvider#when
		 *
		 * @param {string} path Route path (matched against `$location.path`). If `$location.path`
		 *    contains redundant trailing slash or is missing one, the route will still match and the
		 *    `$location.path` will be updated to add or drop the trailing slash to exactly match the
		 *    route definition.
		 *
		 *    * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up
		 *        to the next slash are matched and stored in `$routeParams` under the given `name`
		 *        when the route matches.
		 *    * `path` can contain named groups starting with a colon and ending with a star:
		 *        e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name`
		 *        when the route matches.
		 *    * `path` can contain optional named groups with a question mark: e.g.`:name?`.
		 *
		 *    For example, routes like `/color/:color/largecode/:largecode*\/edit` will match
		 *    `/color/brown/largecode/code/with/slashes/edit` and extract:
		 *
		 *    * `color: brown`
		 *    * `largecode: code/with/slashes`.
		 *
		 *
		 * @param {Object} route Mapping information to be assigned to `$route.current` on route
		 *    match.
		 *
		 *    Object properties:
		 *
		 *    - `controller` â€“ `{(string|function()=}` â€“ Controller fn that should be associated with
		 *      newly created scope or the name of a {@link angular.Module#controller registered
		 *      controller} if passed as a string.
		 *    - `controllerAs` â€“ `{string=}` â€“ A controller alias name. If present the controller will be
		 *      published to scope under the `controllerAs` name.
		 *    - `template` â€“ `{string=|function()=}` â€“ html template as a string or a function that
		 *      returns an html template as a string which should be used by {@link
		 *      ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives.
		 *      This property takes precedence over `templateUrl`.
		 *
		 *      If `template` is a function, it will be called with the following parameters:
		 *
		 *      - `{Array.<Object>}` - route parameters extracted from the current
		 *        `$location.path()` by applying the current route
		 *
		 *    - `templateUrl` â€“ `{string=|function()=}` â€“ path or function that returns a path to an html
		 *      template that should be used by {@link ngRoute.directive:ngView ngView}.
		 *
		 *      If `templateUrl` is a function, it will be called with the following parameters:
		 *
		 *      - `{Array.<Object>}` - route parameters extracted from the current
		 *        `$location.path()` by applying the current route
		 *
		 *    - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
		 *      be injected into the controller. If any of these dependencies are promises, the router
		 *      will wait for them all to be resolved or one to be rejected before the controller is
		 *      instantiated.
		 *      If all the promises are resolved successfully, the values of the resolved promises are
		 *      injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is
		 *      fired. If any of the promises are rejected the
		 *      {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object
		 *      is:
		 *
		 *      - `key` â€“ `{string}`: a name of a dependency to be injected into the controller.
		 *      - `factory` - `{string|function}`: If `string` then it is an alias for a service.
		 *        Otherwise if function, then it is {@link auto.$injector#invoke injected}
		 *        and the return value is treated as the dependency. If the result is a promise, it is
		 *        resolved before its value is injected into the controller. Be aware that
		 *        `ngRoute.$routeParams` will still refer to the previous route within these resolve
		 *        functions.  Use `$route.current.params` to access the new route parameters, instead.
		 *
		 *    - `redirectTo` â€“ {(string|function())=} â€“ value to update
		 *      {@link ng.$location $location} path with and trigger route redirection.
		 *
		 *      If `redirectTo` is a function, it will be called with the following parameters:
		 *
		 *      - `{Object.<string>}` - route parameters extracted from the current
		 *        `$location.path()` by applying the current route templateUrl.
		 *      - `{string}` - current `$location.path()`
		 *      - `{Object}` - current `$location.search()`
		 *
		 *      The custom `redirectTo` function is expected to return a string which will be used
		 *      to update `$location.path()` and `$location.search()`.
		 *
		 *    - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()`
		 *      or `$location.hash()` changes.
		 *
		 *      If the option is set to `false` and url in the browser changes, then
		 *      `$routeUpdate` event is broadcasted on the root scope.
		 *
		 *    - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive
		 *
		 *      If the option is set to `true`, then the particular route can be matched without being
		 *      case sensitive
		 *
		 * @returns {Object} self
		 *
		 * @description
		 * Adds a new route definition to the `$route` service.
		 */
		this.when = function (path, route) {
			//copy original route object to preserve params inherited from proto chain
			var routeCopy = angular.copy(route);
			if (angular.isUndefined(routeCopy.reloadOnSearch)) {
				routeCopy.reloadOnSearch = true;
			}
			if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) {
				routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch;
			}
			routes[path] = angular.extend(
			  routeCopy,
			  path && pathRegExp(path, routeCopy)
			);

			// create redirection for trailing slashes
			if (path) {
				var redirectPath = (path[path.length - 1] == '/')
					  ? path.substr(0, path.length - 1)
					  : path + '/';

				routes[redirectPath] = angular.extend(
				  { redirectTo: path },
				  pathRegExp(redirectPath, routeCopy)
				);
			}

			return this;
		};

		/**
		 * @ngdoc property
		 * @name $routeProvider#caseInsensitiveMatch
		 * @description
		 *
		 * A boolean property indicating if routes defined
		 * using this provider should be matched using a case insensitive
		 * algorithm. Defaults to `false`.
		 */
		this.caseInsensitiveMatch = false;

		/**
		 * @param path {string} path
		 * @param opts {Object} options
		 * @return {?Object}
		 *
		 * @description
		 * Normalizes the given path, returning a regular expression
		 * and the original path.
		 *
		 * Inspired by pathRexp in visionmedia/express/lib/utils.js.
		 */
		function pathRegExp(path, opts) {
			var insensitive = opts.caseInsensitiveMatch,
				ret = {
					originalPath: path,
					regexp: path
				},
				keys = ret.keys = [];

			path = path
			  .replace(/([().])/g, '\\$1')
			  .replace(/(\/)?:(\w+)([\?\*])?/g, function (_, slash, key, option) {
			  	var optional = option === '?' ? option : null;
			  	var star = option === '*' ? option : null;
			  	keys.push({ name: key, optional: !!optional });
			  	slash = slash || '';
			  	return ''
				  + (optional ? '' : slash)
				  + '(?:'
				  + (optional ? slash : '')
				  + (star && '(.+?)' || '([^/]+)')
				  + (optional || '')
				  + ')'
				  + (optional || '');
			  })
			  .replace(/([\/$\*])/g, '\\$1');

			ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
			return ret;
		}

		/**
		 * @ngdoc method
		 * @name $routeProvider#otherwise
		 *
		 * @description
		 * Sets route definition that will be used on route change when no other route definition
		 * is matched.
		 *
		 * @param {Object|string} params Mapping information to be assigned to `$route.current`.
		 * If called with a string, the value maps to `redirectTo`.
		 * @returns {Object} self
		 */
		this.otherwise = function (params) {
			if (typeof params === 'string') {
				params = { redirectTo: params };
			}
			this.when(null, params);
			return this;
		};


		this.$get = ['$rootScope',
					 '$location',
					 '$routeParams',
					 '$q',
					 '$injector',
					 '$templateRequest',
					 '$sce',
			function ($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce) {

				/**
				 * @ngdoc service
				 * @name $route
				 * @requires $location
				 * @requires $routeParams
				 *
				 * @property {Object} current Reference to the current route definition.
				 * The route definition contains:
				 *
				 *   - `controller`: The controller constructor as define in route definition.
				 *   - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
				 *     controller instantiation. The `locals` contain
				 *     the resolved values of the `resolve` map. Additionally the `locals` also contain:
				 *
				 *     - `$scope` - The current route scope.
				 *     - `$template` - The current route template HTML.
				 *
				 * @property {Object} routes Object with all route configuration Objects as its properties.
				 *
				 * @description
				 * `$route` is used for deep-linking URLs to controllers and views (HTML partials).
				 * It watches `$location.url()` and tries to map the path to an existing route definition.
				 *
				 * Requires the {@link ngRoute `ngRoute`} module to be installed.
				 *
				 * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API.
				 *
				 * The `$route` service is typically used in conjunction with the
				 * {@link ngRoute.directive:ngView `ngView`} directive and the
				 * {@link ngRoute.$routeParams `$routeParams`} service.
				 *
				 * @example
				 * This example shows how changing the URL hash causes the `$route` to match a route against the
				 * URL, and the `ngView` pulls in the partial.
				 *
				 * <example name="$route-service" module="ngRouteExample"
				 *          deps="angular-route.js" fixBase="true">
				 *   <file name="index.html">
				 *     <div ng-controller="MainController">
				 *       Choose:
				 *       <a href="Book/Moby">Moby</a> |
				 *       <a href="Book/Moby/ch/1">Moby: Ch1</a> |
				 *       <a href="Book/Gatsby">Gatsby</a> |
				 *       <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
				 *       <a href="Book/Scarlet">Scarlet Letter</a><br/>
				 *
				 *       <div ng-view></div>
				 *
				 *       <hr />
				 *
				 *       <pre>$location.path() = {{$location.path()}}</pre>
				 *       <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
				 *       <pre>$route.current.params = {{$route.current.params}}</pre>
				 *       <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
				 *       <pre>$routeParams = {{$routeParams}}</pre>
				 *     </div>
				 *   </file>
				 *
				 *   <file name="book.html">
				 *     controller: {{name}}<br />
				 *     Book Id: {{params.bookId}}<br />
				 *   </file>
				 *
				 *   <file name="chapter.html">
				 *     controller: {{name}}<br />
				 *     Book Id: {{params.bookId}}<br />
				 *     Chapter Id: {{params.chapterId}}
				 *   </file>
				 *
				 *   <file name="script.js">
				 *     angular.module('ngRouteExample', ['ngRoute'])
				 *
				 *      .controller('MainController', function($scope, $route, $routeParams, $location) {
				 *          $scope.$route = $route;
				 *          $scope.$location = $location;
				 *          $scope.$routeParams = $routeParams;
				 *      })
				 *
				 *      .controller('BookController', function($scope, $routeParams) {
				 *          $scope.name = "BookController";
				 *          $scope.params = $routeParams;
				 *      })
				 *
				 *      .controller('ChapterController', function($scope, $routeParams) {
				 *          $scope.name = "ChapterController";
				 *          $scope.params = $routeParams;
				 *      })
				 *
				 *     .config(function($routeProvider, $locationProvider) {
				 *       $routeProvider
				 *        .when('/Book/:bookId', {
				 *         templateUrl: 'book.html',
				 *         controller: 'BookController',
				 *         resolve: {
				 *           // I will cause a 1 second delay
				 *           delay: function($q, $timeout) {
				 *             var delay = $q.defer();
				 *             $timeout(delay.resolve, 1000);
				 *             return delay.promise;
				 *           }
				 *         }
				 *       })
				 *       .when('/Book/:bookId/ch/:chapterId', {
				 *         templateUrl: 'chapter.html',
				 *         controller: 'ChapterController'
				 *       });
				 *
				 *       // configure html5 to get links working on jsfiddle
				 *       $locationProvider.html5Mode(true);
				 *     });
				 *
				 *   </file>
				 *
				 *   <file name="protractor.js" type="protractor">
				 *     it('should load and compile correct template', function() {
				 *       element(by.linkText('Moby: Ch1')).click();
				 *       var content = element(by.css('[ng-view]')).getText();
				 *       expect(content).toMatch(/controller\: ChapterController/);
				 *       expect(content).toMatch(/Book Id\: Moby/);
				 *       expect(content).toMatch(/Chapter Id\: 1/);
				 *
				 *       element(by.partialLinkText('Scarlet')).click();
				 *
				 *       content = element(by.css('[ng-view]')).getText();
				 *       expect(content).toMatch(/controller\: BookController/);
				 *       expect(content).toMatch(/Book Id\: Scarlet/);
				 *     });
				 *   </file>
				 * </example>
				 */

				/**
				 * @ngdoc event
				 * @name $route#$routeChangeStart
				 * @eventType broadcast on root scope
				 * @description
				 * Broadcasted before a route change. At this  point the route services starts
				 * resolving all of the dependencies needed for the route change to occur.
				 * Typically this involves fetching the view template as well as any dependencies
				 * defined in `resolve` route property. Once  all of the dependencies are resolved
				 * `$routeChangeSuccess` is fired.
				 *
				 * The route change (and the `$location` change that triggered it) can be prevented
				 * by calling `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on}
				 * for more details about event object.
				 *
				 * @param {Object} angularEvent Synthetic event object.
				 * @param {Route} next Future route information.
				 * @param {Route} current Current route information.
				 */

				/**
				 * @ngdoc event
				 * @name $route#$routeChangeSuccess
				 * @eventType broadcast on root scope
				 * @description
				 * Broadcasted after a route dependencies are resolved.
				 * {@link ngRoute.directive:ngView ngView} listens for the directive
				 * to instantiate the controller and render the view.
				 *
				 * @param {Object} angularEvent Synthetic event object.
				 * @param {Route} current Current route information.
				 * @param {Route|Undefined} previous Previous route information, or undefined if current is
				 * first route entered.
				 */

				/**
				 * @ngdoc event
				 * @name $route#$routeChangeError
				 * @eventType broadcast on root scope
				 * @description
				 * Broadcasted if any of the resolve promises are rejected.
				 *
				 * @param {Object} angularEvent Synthetic event object
				 * @param {Route} current Current route information.
				 * @param {Route} previous Previous route information.
				 * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
				 */

				/**
				 * @ngdoc event
				 * @name $route#$routeUpdate
				 * @eventType broadcast on root scope
				 * @description
				 * The `reloadOnSearch` property has been set to false, and we are reusing the same
				 * instance of the Controller.
				 *
				 * @param {Object} angularEvent Synthetic event object
				 * @param {Route} current Current/previous route information.
				 */

				var forceReload = false,
					preparedRoute,
					preparedRouteIsUpdateOnly,
					$route = {
						routes: routes,

						/**
						 * @ngdoc method
						 * @name $route#reload
						 *
						 * @description
						 * Causes `$route` service to reload the current route even if
						 * {@link ng.$location $location} hasn't changed.
						 *
						 * As a result of that, {@link ngRoute.directive:ngView ngView}
						 * creates new scope and reinstantiates the controller.
						 */
						reload: function () {
							forceReload = true;
							$rootScope.$evalAsync(function () {
								// Don't support cancellation of a reload for now...
								prepareRoute();
								commitRoute();
							});
						},

						/**
						 * @ngdoc method
						 * @name $route#updateParams
						 *
						 * @description
						 * Causes `$route` service to update the current URL, replacing
						 * current route parameters with those specified in `newParams`.
						 * Provided property names that match the route's path segment
						 * definitions will be interpolated into the location's path, while
						 * remaining properties will be treated as query params.
						 *
						 * @param {!Object<string, string>} newParams mapping of URL parameter names to values
						 */
						updateParams: function (newParams) {
							if (this.current && this.current.$$route) {
								newParams = angular.extend({}, this.current.params, newParams);
								$location.path(interpolate(this.current.$$route.originalPath, newParams));
								// interpolate modifies newParams, only query params are left
								$location.search(newParams);
							} else {
								throw $routeMinErr('norout', 'Tried updating route when with no current route');
							}
						}
					};

				$rootScope.$on('$locationChangeStart', prepareRoute);
				$rootScope.$on('$locationChangeSuccess', commitRoute);

				return $route;

				/////////////////////////////////////////////////////

				/**
				 * @param on {string} current url
				 * @param route {Object} route regexp to match the url against
				 * @return {?Object}
				 *
				 * @description
				 * Check if the route matches the current url.
				 *
				 * Inspired by match in
				 * visionmedia/express/lib/router/router.js.
				 */
				function switchRouteMatcher(on, route) {
					var keys = route.keys,
						params = {};

					if (!route.regexp) return null;

					var m = route.regexp.exec(on);
					if (!m) return null;

					for (var i = 1, len = m.length; i < len; ++i) {
						var key = keys[i - 1];

						var val = m[i];

						if (key && val) {
							params[key.name] = val;
						}
					}
					return params;
				}

				function prepareRoute($locationEvent) {
					var lastRoute = $route.current;

					preparedRoute = parseRoute();
					preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route
						&& angular.equals(preparedRoute.pathParams, lastRoute.pathParams)
						&& !preparedRoute.reloadOnSearch && !forceReload;

					if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) {
						if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) {
							if ($locationEvent) {
								$locationEvent.preventDefault();
							}
						}
					}
				}

				function commitRoute() {
					var lastRoute = $route.current;
					var nextRoute = preparedRoute;

					if (preparedRouteIsUpdateOnly) {
						lastRoute.params = nextRoute.params;
						angular.copy(lastRoute.params, $routeParams);
						$rootScope.$broadcast('$routeUpdate', lastRoute);
					} else if (nextRoute || lastRoute) {
						forceReload = false;
						$route.current = nextRoute;
						if (nextRoute) {
							if (nextRoute.redirectTo) {
								if (angular.isString(nextRoute.redirectTo)) {
									$location.path(interpolate(nextRoute.redirectTo, nextRoute.params)).search(nextRoute.params)
											 .replace();
								} else {
									$location.url(nextRoute.redirectTo(nextRoute.pathParams, $location.path(), $location.search()))
											 .replace();
								}
							}
						}

						$q.when(nextRoute).
						  then(function () {
						  	if (nextRoute) {
						  		var locals = angular.extend({}, nextRoute.resolve),
									template, templateUrl;

						  		angular.forEach(locals, function (value, key) {
						  			locals[key] = angular.isString(value) ?
										$injector.get(value) : $injector.invoke(value, null, null, key);
						  		});

						  		if (angular.isDefined(template = nextRoute.template)) {
						  			if (angular.isFunction(template)) {
						  				template = template(nextRoute.params);
						  			}
						  		} else if (angular.isDefined(templateUrl = nextRoute.templateUrl)) {
						  			if (angular.isFunction(templateUrl)) {
						  				templateUrl = templateUrl(nextRoute.params);
						  			}
						  			templateUrl = $sce.getTrustedResourceUrl(templateUrl);
						  			if (angular.isDefined(templateUrl)) {
						  				nextRoute.loadedTemplateUrl = templateUrl;
						  				template = $templateRequest(templateUrl);
						  			}
						  		}
						  		if (angular.isDefined(template)) {
						  			locals['$template'] = template;
						  		}
						  		return $q.all(locals);
						  	}
						  }).
						  // after route change
						  then(function (locals) {
						  	if (nextRoute == $route.current) {
						  		if (nextRoute) {
						  			nextRoute.locals = locals;
						  			angular.copy(nextRoute.params, $routeParams);
						  		}
						  		$rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute);
						  	}
						  }, function (error) {
						  	if (nextRoute == $route.current) {
						  		$rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error);
						  	}
						  });
					}
				}


				/**
				 * @returns {Object} the current active route, by matching it against the URL
				 */
				function parseRoute() {
					// Match a route
					var params, match;
					angular.forEach(routes, function (route, path) {
						if (!match && (params = switchRouteMatcher($location.path(), route))) {
							match = inherit(route, {
								params: angular.extend({}, $location.search(), params),
								pathParams: params
							});
							match.$$route = route;
						}
					});
					// No route matched; fallback to "otherwise" route
					return match || routes[null] && inherit(routes[null], { params: {}, pathParams: {} });
				}

				/**
				 * @returns {string} interpolation of the redirect path with the parameters
				 */
				function interpolate(string, params) {
					var result = [];
					angular.forEach((string || '').split(':'), function (segment, i) {
						if (i === 0) {
							result.push(segment);
						} else {
							var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/);
							var key = segmentMatch[1];
							result.push(params[key]);
							result.push(segmentMatch[2] || '');
							delete params[key];
						}
					});
					return result.join('');
				}
			}];
	}

	ngRouteModule.provider('$routeParams', $RouteParamsProvider);


	/**
	 * @ngdoc service
	 * @name $routeParams
	 * @requires $route
	 *
	 * @description
	 * The `$routeParams` service allows you to retrieve the current set of route parameters.
	 *
	 * Requires the {@link ngRoute `ngRoute`} module to be installed.
	 *
	 * The route parameters are a combination of {@link ng.$location `$location`}'s
	 * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
	 * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
	 *
	 * In case of parameter name collision, `path` params take precedence over `search` params.
	 *
	 * The service guarantees that the identity of the `$routeParams` object will remain unchanged
	 * (but its properties will likely change) even when a route change occurs.
	 *
	 * Note that the `$routeParams` are only updated *after* a route change completes successfully.
	 * This means that you cannot rely on `$routeParams` being correct in route resolve functions.
	 * Instead you can use `$route.current.params` to access the new route's parameters.
	 *
	 * @example
	 * ```js
	 *  // Given:
	 *  // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
	 *  // Route: /Chapter/:chapterId/Section/:sectionId
	 *  //
	 *  // Then
	 *  $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
	 * ```
	 */
	function $RouteParamsProvider() {
		this.$get = function () { return {}; };
	}

	ngRouteModule.directive('ngView', ngViewFactory);
	ngRouteModule.directive('ngView', ngViewFillContentFactory);


	/**
	 * @ngdoc directive
	 * @name ngView
	 * @restrict ECA
	 *
	 * @description
	 * # Overview
	 * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
	 * including the rendered template of the current route into the main layout (`index.html`) file.
	 * Every time the current route changes, the included view changes with it according to the
	 * configuration of the `$route` service.
	 *
	 * Requires the {@link ngRoute `ngRoute`} module to be installed.
	 *
	 * @animations
	 * enter - animation is used to bring new content into the browser.
	 * leave - animation is used to animate existing content away.
	 *
	 * The enter and leave animation occur concurrently.
	 *
	 * @scope
	 * @priority 400
	 * @param {string=} onload Expression to evaluate whenever the view updates.
	 *
	 * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
	 *                  $anchorScroll} to scroll the viewport after the view is updated.
	 *
	 *                  - If the attribute is not set, disable scrolling.
	 *                  - If the attribute is set without value, enable scrolling.
	 *                  - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
	 *                    as an expression yields a truthy value.
	 * @example
		<example name="ngView-directive" module="ngViewExample"
				 deps="angular-route.js;angular-animate.js"
				 animations="true" fixBase="true">
		  <file name="index.html">
			<div ng-controller="MainCtrl as main">
			  Choose:
			  <a href="Book/Moby">Moby</a> |
			  <a href="Book/Moby/ch/1">Moby: Ch1</a> |
			  <a href="Book/Gatsby">Gatsby</a> |
			  <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
			  <a href="Book/Scarlet">Scarlet Letter</a><br/>
	
			  <div class="view-animate-container">
				<div ng-view class="view-animate"></div>
			  </div>
			  <hr />
	
			  <pre>$location.path() = {{main.$location.path()}}</pre>
			  <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
			  <pre>$route.current.params = {{main.$route.current.params}}</pre>
			  <pre>$routeParams = {{main.$routeParams}}</pre>
			</div>
		  </file>
	
		  <file name="book.html">
			<div>
			  controller: {{book.name}}<br />
			  Book Id: {{book.params.bookId}}<br />
			</div>
		  </file>
	
		  <file name="chapter.html">
			<div>
			  controller: {{chapter.name}}<br />
			  Book Id: {{chapter.params.bookId}}<br />
			  Chapter Id: {{chapter.params.chapterId}}
			</div>
		  </file>
	
		  <file name="animations.css">
			.view-animate-container {
			  position:relative;
			  height:100px!important;
			  background:white;
			  border:1px solid black;
			  height:40px;
			  overflow:hidden;
			}
	
			.view-animate {
			  padding:10px;
			}
	
			.view-animate.ng-enter, .view-animate.ng-leave {
			  -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
			  transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
	
			  display:block;
			  width:100%;
			  border-left:1px solid black;
	
			  position:absolute;
			  top:0;
			  left:0;
			  right:0;
			  bottom:0;
			  padding:10px;
			}
	
			.view-animate.ng-enter {
			  left:100%;
			}
			.view-animate.ng-enter.ng-enter-active {
			  left:0;
			}
			.view-animate.ng-leave.ng-leave-active {
			  left:-100%;
			}
		  </file>
	
		  <file name="script.js">
			angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
			  .config(['$routeProvider', '$locationProvider',
				function($routeProvider, $locationProvider) {
				  $routeProvider
					.when('/Book/:bookId', {
					  templateUrl: 'book.html',
					  controller: 'BookCtrl',
					  controllerAs: 'book'
					})
					.when('/Book/:bookId/ch/:chapterId', {
					  templateUrl: 'chapter.html',
					  controller: 'ChapterCtrl',
					  controllerAs: 'chapter'
					});
	
				  $locationProvider.html5Mode(true);
			  }])
			  .controller('MainCtrl', ['$route', '$routeParams', '$location',
				function($route, $routeParams, $location) {
				  this.$route = $route;
				  this.$location = $location;
				  this.$routeParams = $routeParams;
			  }])
			  .controller('BookCtrl', ['$routeParams', function($routeParams) {
				this.name = "BookCtrl";
				this.params = $routeParams;
			  }])
			  .controller('ChapterCtrl', ['$routeParams', function($routeParams) {
				this.name = "ChapterCtrl";
				this.params = $routeParams;
			  }]);
	
		  </file>
	
		  <file name="protractor.js" type="protractor">
			it('should load and compile correct template', function() {
			  element(by.linkText('Moby: Ch1')).click();
			  var content = element(by.css('[ng-view]')).getText();
			  expect(content).toMatch(/controller\: ChapterCtrl/);
			  expect(content).toMatch(/Book Id\: Moby/);
			  expect(content).toMatch(/Chapter Id\: 1/);
	
			  element(by.partialLinkText('Scarlet')).click();
	
			  content = element(by.css('[ng-view]')).getText();
			  expect(content).toMatch(/controller\: BookCtrl/);
			  expect(content).toMatch(/Book Id\: Scarlet/);
			});
		  </file>
		</example>
	 */


	/**
	 * @ngdoc event
	 * @name ngView#$viewContentLoaded
	 * @eventType emit on the current ngView scope
	 * @description
	 * Emitted every time the ngView content is reloaded.
	 */
	ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
	function ngViewFactory($route, $anchorScroll, $animate) {
		return {
			restrict: 'ECA',
			terminal: true,
			priority: 400,
			transclude: 'element',
			link: function (scope, $element, attr, ctrl, $transclude) {
				var currentScope,
					currentElement,
					previousLeaveAnimation,
					autoScrollExp = attr.autoscroll,
					onloadExp = attr.onload || '';

				scope.$on('$routeChangeSuccess', update);
				update();

				function cleanupLastView() {
					if (previousLeaveAnimation) {
						$animate.cancel(previousLeaveAnimation);
						previousLeaveAnimation = null;
					}

					if (currentScope) {
						currentScope.$destroy();
						currentScope = null;
					}
					if (currentElement) {
						previousLeaveAnimation = $animate.leave(currentElement);
						previousLeaveAnimation.then(function () {
							previousLeaveAnimation = null;
						});
						currentElement = null;
					}
				}

				function update() {
					var locals = $route.current && $route.current.locals,
						template = locals && locals.$template;

					if (angular.isDefined(template)) {
						var newScope = scope.$new();
						var current = $route.current;

						// Note: This will also link all children of ng-view that were contained in the original
						// html. If that content contains controllers, ... they could pollute/change the scope.
						// However, using ng-view on an element with additional content does not make sense...
						// Note: We can't remove them in the cloneAttchFn of $transclude as that
						// function is called before linking the content, which would apply child
						// directives to non existing elements.
						var clone = $transclude(newScope, function (clone) {
							$animate.enter(clone, null, currentElement || $element).then(function onNgViewEnter() {
								if (angular.isDefined(autoScrollExp)
								  && (!autoScrollExp || scope.$eval(autoScrollExp))) {
									$anchorScroll();
								}
							});
							cleanupLastView();
						});

						currentElement = clone;
						currentScope = current.scope = newScope;
						currentScope.$emit('$viewContentLoaded');
						currentScope.$eval(onloadExp);
					} else {
						cleanupLastView();
					}
				}
			}
		};
	}

	// This directive is called during the $transclude call of the first `ngView` directive.
	// It will replace and compile the content of the element with the loaded template.
	// We need this directive so that the element content is already filled when
	// the link function of another directive on the same element as ngView
	// is called.
	ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
	function ngViewFillContentFactory($compile, $controller, $route) {
		return {
			restrict: 'ECA',
			priority: -400,
			link: function (scope, $element) {
				var current = $route.current,
					locals = current.locals;

				$element.html(locals.$template);

				var link = $compile($element.contents());

				if (current.controller) {
					locals.$scope = scope;
					var controller = $controller(current.controller, locals);
					if (current.controllerAs) {
						scope[current.controllerAs] = controller;
					}
					$element.data('$ngControllerController', controller);
					$element.children().data('$ngControllerController', controller);
				}

				link(scope);
			}
		};
	}


})(window, window.angular);;
/*
 AngularJS v1.4.0
 (c) 2010-2015 Google, Inc. http://angularjs.org
 License: MIT
*/
(function(F,t,W){'use strict';function ua(a,b,c){if(!a)throw ngMinErr("areq",b||"?",c||"required");return a}function va(a,b){if(!a&&!b)return"";if(!a)return b;if(!b)return a;X(a)&&(a=a.join(" "));X(b)&&(b=b.join(" "));return a+" "+b}function Ea(a){var b={};a&&(a.to||a.from)&&(b.to=a.to,b.from=a.from);return b}function ba(a,b,c){var d="";a=X(a)?a:a&&U(a)&&a.length?a.split(/\s+/):[];u(a,function(a,s){a&&0<a.length&&(d+=0<s?" ":"",d+=c?b+a:a+b)});return d}function Fa(a){if(a instanceof G)switch(a.length){case 0:return[];
case 1:if(1===a[0].nodeType)return a;break;default:return G(ka(a))}if(1===a.nodeType)return G(a)}function ka(a){if(!a[0])return a;for(var b=0;b<a.length;b++){var c=a[b];if(1==c.nodeType)return c}}function Ga(a,b,c){u(b,function(b){a.addClass(b,c)})}function Ha(a,b,c){u(b,function(b){a.removeClass(b,c)})}function ha(a){return function(b,c){c.addClass&&(Ga(a,b,c.addClass),c.addClass=null);c.removeClass&&(Ha(a,b,c.removeClass),c.removeClass=null)}}function ia(a){a=a||{};if(!a.$$prepared){var b=a.domOperation||
H;a.domOperation=function(){a.$$domOperationFired=!0;b();b=H};a.$$prepared=!0}return a}function ca(a,b){wa(a,b);xa(a,b)}function wa(a,b){b.from&&(a.css(b.from),b.from=null)}function xa(a,b){b.to&&(a.css(b.to),b.to=null)}function R(a,b,c){var d=(b.addClass||"")+" "+(c.addClass||""),e=(b.removeClass||"")+" "+(c.removeClass||"");a=Ia(a.attr("class"),d,e);ya(b,c);b.addClass=a.addClass?a.addClass:null;b.removeClass=a.removeClass?a.removeClass:null;return b}function Ia(a,b,c){function d(a){U(a)&&(a=a.split(" "));
var b={};u(a,function(a){a.length&&(b[a]=!0)});return b}var e={};a=d(a);b=d(b);u(b,function(a,b){e[b]=1});c=d(c);u(c,function(a,b){e[b]=1===e[b]?null:-1});var s={addClass:"",removeClass:""};u(e,function(b,c){var d,e;1===b?(d="addClass",e=!a[c]):-1===b&&(d="removeClass",e=a[c]);e&&(s[d].length&&(s[d]+=" "),s[d]+=c)});return s}function A(a){return a instanceof t.element?a[0]:a}function za(a,b,c){var d=Object.create(null),e=a.getComputedStyle(b)||{};u(c,function(a,b){var c=e[a];if(c){var l=c.charAt(0);
if("-"===l||"+"===l||0<=l)c=Ja(c);0===c&&(c=null);d[b]=c}});return d}function Ja(a){var b=0;a=a.split(/\s*,\s*/);u(a,function(a){"s"==a.charAt(a.length-1)&&(a=a.substring(0,a.length-1));a=parseFloat(a)||0;b=b?Math.max(a,b):a});return b}function la(a){return 0===a||null!=a}function Aa(a,b){var c=O,d=a+"s";b?c+="Duration":d+=" linear all";return[c,d]}function ja(a,b){var c=b?"-"+b+"s":"";da(a,[ea,c]);return[ea,c]}function ma(a,b){var c=b?"paused":"",d=V+"PlayState";da(a,[d,c]);return[d,c]}function da(a,
b){a.style[b[0]]=b[1]}function Ba(){var a=Object.create(null);return{flush:function(){a=Object.create(null)},count:function(b){return(b=a[b])?b.total:0},get:function(b){return(b=a[b])&&b.value},put:function(b,c){a[b]?a[b].total++:a[b]={total:1,value:c}}}}var H=t.noop,ya=t.extend,G=t.element,u=t.forEach,X=t.isArray,U=t.isString,na=t.isObject,Ka=t.isUndefined,La=t.isDefined,Ca=t.isFunction,oa=t.isElement,O,pa,V,qa;F.ontransitionend===W&&F.onwebkittransitionend!==W?(O="WebkitTransition",pa="webkitTransitionEnd transitionend"):
(O="transition",pa="transitionend");F.onanimationend===W&&F.onwebkitanimationend!==W?(V="WebkitAnimation",qa="webkitAnimationEnd animationend"):(V="animation",qa="animationend");var ra=V+"Delay",sa=V+"Duration",ea=O+"Delay";F=O+"Duration";var Ma={transitionDuration:F,transitionDelay:ea,transitionProperty:O+"Property",animationDuration:sa,animationDelay:ra,animationIterationCount:V+"IterationCount"},Na={transitionDuration:F,transitionDelay:ea,animationDuration:sa,animationDelay:ra};t.module("ngAnimate",
[]).directive("ngAnimateChildren",[function(){return function(a,b,c){a=c.ngAnimateChildren;t.isString(a)&&0===a.length?b.data("$$ngAnimateChildren",!0):c.$observe("ngAnimateChildren",function(a){b.data("$$ngAnimateChildren","on"===a||"true"===a)})}}]).factory("$$rAFMutex",["$$rAF",function(a){return function(){var b=!1;a(function(){b=!0});return function(c){b?c():a(c)}}}]).factory("$$rAFScheduler",["$$rAF",function(a){function b(a){d.push([].concat(a));c()}function c(){if(d.length){for(var b=[],n=
0;n<d.length;n++){var g=d[n];g.shift()();g.length&&b.push(g)}d=b;e||a(function(){e||c()})}}var d=[],e;b.waitUntilQuiet=function(b){e&&e();e=a(function(){e=null;b();c()})};return b}]).factory("$$AnimateRunner",["$q","$$rAFMutex",function(a,b){function c(a){this.setHost(a);this._doneCallbacks=[];this._runInAnimationFrame=b();this._state=0}c.chain=function(a,b){function c(){if(n===a.length)b(!0);else a[n](function(a){!1===a?b(!1):(n++,c())})}var n=0;c()};c.all=function(a,b){function c(s){g=g&&s;++n===
a.length&&b(g)}var n=0,g=!0;u(a,function(a){a.done(c)})};c.prototype={setHost:function(a){this.host=a||{}},done:function(a){2===this._state?a():this._doneCallbacks.push(a)},progress:H,getPromise:function(){if(!this.promise){var b=this;this.promise=a(function(a,c){b.done(function(b){!1===b?c():a()})})}return this.promise},then:function(a,b){return this.getPromise().then(a,b)},"catch":function(a){return this.getPromise()["catch"](a)},"finally":function(a){return this.getPromise()["finally"](a)},pause:function(){this.host.pause&&
this.host.pause()},resume:function(){this.host.resume&&this.host.resume()},end:function(){this.host.end&&this.host.end();this._resolve(!0)},cancel:function(){this.host.cancel&&this.host.cancel();this._resolve(!1)},complete:function(a){var b=this;0===b._state&&(b._state=1,b._runInAnimationFrame(function(){b._resolve(a)}))},_resolve:function(a){2!==this._state&&(u(this._doneCallbacks,function(b){b(a)}),this._doneCallbacks.length=0,this._state=2)}};return c}]).provider("$$animateQueue",["$animateProvider",
function(a){function b(a,b,c,g){return d[a].some(function(a){return a(b,c,g)})}function c(a,b){a=a||{};var c=0<(a.addClass||"").length,d=0<(a.removeClass||"").length;return b?c&&d:c||d}var d=this.rules={skip:[],cancel:[],join:[]};d.join.push(function(a,b,d){return!b.structural&&c(b.options)});d.skip.push(function(a,b,d){return!b.structural&&!c(b.options)});d.skip.push(function(a,b,c){return"leave"==c.event&&b.structural});d.skip.push(function(a,b,c){return c.structural&&!b.structural});d.cancel.push(function(a,
b,c){return c.structural&&b.structural});d.cancel.push(function(a,b,c){return 2===c.state&&b.structural});d.cancel.push(function(a,b,c){a=b.options;c=c.options;return a.addClass&&a.addClass===c.removeClass||a.removeClass&&a.removeClass===c.addClass});this.$get=["$$rAF","$rootScope","$rootElement","$document","$$HashMap","$$animation","$$AnimateRunner","$templateRequest","$$jqLite",function(d,s,n,g,l,D,z,Z,I){function w(a,b){var c=A(a),f=[],d=m[b];d&&u(d,function(a){a.node.contains(c)&&f.push(a.callback)});
return f}function B(a,b,c,f){d(function(){u(w(b,a),function(a){a(b,c,f)})})}function r(a,S,p){function d(b,c,f,p){B(c,a,f,p);b.progress(c,f,p)}function k(b){Da(a,p);ca(a,p);p.domOperation();m.complete(!b)}var P,E;if(a=Fa(a))P=A(a),E=a.parent();p=ia(p);var m=new z;if(!P)return k(),m;X(p.addClass)&&(p.addClass=p.addClass.join(" "));X(p.removeClass)&&(p.removeClass=p.removeClass.join(" "));p.from&&!na(p.from)&&(p.from=null);p.to&&!na(p.to)&&(p.to=null);var e=[P.className,p.addClass,p.removeClass].join(" ");
if(!v(e))return k(),m;var M=0<=["enter","move","leave"].indexOf(S),g=!x||L.get(P),e=!g&&h.get(P)||{},l=!!e.state;g||l&&1==e.state||(g=!ta(a,E,S));if(g)return k(),m;M&&K(a);g={structural:M,element:a,event:S,close:k,options:p,runner:m};if(l){if(b("skip",a,g,e)){if(2===e.state)return k(),m;R(a,e.options,p);return e.runner}if(b("cancel",a,g,e))2===e.state?e.runner.end():e.structural?e.close():R(a,g.options,e.options);else if(b("join",a,g,e))if(2===e.state)R(a,p,{});else return S=g.event=e.event,p=R(a,
e.options,g.options),m}else R(a,p,{});(l=g.structural)||(l="animate"===g.event&&0<Object.keys(g.options.to||{}).length||c(g.options));if(!l)return k(),C(a),m;M&&f(E);var r=(e.counter||0)+1;g.counter=r;ga(a,1,g);s.$$postDigest(function(){var b=h.get(P),v=!b,b=b||{},e=a.parent()||[],E=0<e.length&&("animate"===b.event||b.structural||c(b.options));if(v||b.counter!==r||!E){v&&(Da(a,p),ca(a,p));if(v||M&&b.event!==S)p.domOperation(),m.end();E||C(a)}else S=!b.structural&&c(b.options,!0)?"setClass":b.event,
b.structural&&f(e),ga(a,2),b=D(a,S,b.options),b.done(function(b){k(!b);(b=h.get(P))&&b.counter===r&&C(A(a));d(m,S,"close",{})}),m.setHost(b),d(m,S,"start",{})});return m}function K(a){a=A(a).querySelectorAll("[data-ng-animate]");u(a,function(a){var b=parseInt(a.getAttribute("data-ng-animate")),c=h.get(a);switch(b){case 2:c.runner.end();case 1:c&&h.remove(a)}})}function C(a){a=A(a);a.removeAttribute("data-ng-animate");h.remove(a)}function E(a,b){return A(a)===A(b)}function f(a){a=A(a);do{if(!a||1!==
a.nodeType)break;var b=h.get(a);if(b){var f=a;!b.structural&&c(b.options)&&(2===b.state&&b.runner.end(),C(f))}a=a.parentNode}while(1)}function ta(a,b,c){var f=c=!1,d=!1,v;for((a=a.data("$ngAnimatePin"))&&(b=a);b&&b.length;){f||(f=E(b,n));a=b[0];if(1!==a.nodeType)break;var e=h.get(a)||{};d||(d=e.structural||L.get(a));if(Ka(v)||!0===v)a=b.data("$$ngAnimateChildren"),La(a)&&(v=a);if(d&&!1===v)break;f||(f=E(b,n),f||(a=b.data("$ngAnimatePin"))&&(b=a));c||(c=E(b,k));b=b.parent()}return(!d||v)&&f&&c}function ga(a,
b,c){c=c||{};c.state=b;a=A(a);a.setAttribute("data-ng-animate",b);c=(b=h.get(a))?ya(b,c):c;h.put(a,c)}var h=new l,L=new l,x=null,M=s.$watch(function(){return 0===Z.totalPendingRequests},function(a){a&&(M(),s.$$postDigest(function(){s.$$postDigest(function(){null===x&&(x=!0)})}))}),k=G(g[0].body),m={},P=a.classNameFilter(),v=P?function(a){return P.test(a)}:function(){return!0},Da=ha(I);return{on:function(a,b,c){b=ka(b);m[a]=m[a]||[];m[a].push({node:b,callback:c})},off:function(a,b,c){function f(a,
b,c){var d=ka(b);return a.filter(function(a){return!(a.node===d&&(!c||a.callback===c))})}var d=m[a];d&&(m[a]=1===arguments.length?null:f(d,b,c))},pin:function(a,b){ua(oa(a),"element","not an element");ua(oa(b),"parentElement","not an element");a.data("$ngAnimatePin",b)},push:function(a,b,c,f){c=c||{};c.domOperation=f;return r(a,b,c)},enabled:function(a,b){var c=arguments.length;if(0===c)b=!!x;else if(oa(a)){var f=A(a),d=L.get(f);1===c?b=!d:(b=!!b)?d&&L.remove(f):L.put(f,!0)}else b=x=!!a;return b}}}]}]).provider("$$animation",
["$animateProvider",function(a){function b(a){return a.data("$$animationRunner")}var c=this.drivers=[];this.$get=["$$jqLite","$rootScope","$injector","$$AnimateRunner","$$rAFScheduler",function(a,e,s,n,g){var l=[],D=ha(a),z=0,Z=0,I=[];return function(w,B,r){function K(a){a=a.hasAttribute("ng-animate-ref")?[a]:a.querySelectorAll("[ng-animate-ref]");var b=[];u(a,function(a){var c=a.getAttribute("ng-animate-ref");c&&c.length&&b.push(a)});return b}function C(a){var b=[],c={};u(a,function(a,f){var d=A(a.element),
e=0<=["enter","move"].indexOf(a.event),d=a.structural?K(d):[];if(d.length){var h=e?"to":"from";u(d,function(a){var b=a.getAttribute("ng-animate-ref");c[b]=c[b]||{};c[b][h]={animationID:f,element:G(a)}})}else b.push(a)});var f={},d={};u(c,function(c,e){var h=c.from,k=c.to;if(h&&k){var m=a[h.animationID],g=a[k.animationID],x=h.animationID.toString();if(!d[x]){var B=d[x]={structural:!0,beforeStart:function(){m.beforeStart();g.beforeStart()},close:function(){m.close();g.close()},classes:E(m.classes,g.classes),
from:m,to:g,anchors:[]};B.classes.length?b.push(B):(b.push(m),b.push(g))}d[x].anchors.push({out:h.element,"in":k.element})}else h=h?h.animationID:k.animationID,k=h.toString(),f[k]||(f[k]=!0,b.push(a[h]))});return b}function E(a,b){a=a.split(" ");b=b.split(" ");for(var c=[],f=0;f<a.length;f++){var d=a[f];if("ng-"!==d.substring(0,3))for(var h=0;h<b.length;h++)if(d===b[h]){c.push(d);break}}return c.join(" ")}function f(a){for(var b=c.length-1;0<=b;b--){var f=c[b];if(s.has(f)&&(f=s.get(f)(a)))return f}}
function ta(a,c){a.from&&a.to?(b(a.from.element).setHost(c),b(a.to.element).setHost(c)):b(a.element).setHost(c)}function ga(){var a=b(w);!a||"leave"===B&&r.$$domOperationFired||a.end()}function h(b){w.off("$destroy",ga);w.removeData("$$animationRunner");D(w,r);ca(w,r);r.domOperation();k&&a.removeClass(w,k);w.removeClass("ng-animate");x.complete(!b)}r=ia(r);var L=0<=["enter","move","leave"].indexOf(B),x=new n({end:function(){h()},cancel:function(){h(!0)}});if(!c.length)return h(),x;w.data("$$animationRunner",
x);var M=va(w.attr("class"),va(r.addClass,r.removeClass)),k=r.tempClasses;k&&(M+=" "+k,r.tempClasses=null);var m;L||(m=z,z+=1);l.push({element:w,classes:M,event:B,classBasedIndex:m,structural:L,options:r,beforeStart:function(){w.addClass("ng-animate");k&&a.addClass(w,k)},close:h});w.on("$destroy",ga);if(1<l.length)return x;e.$$postDigest(function(){Z=z;z=0;I.length=0;var a=[];u(l,function(c){b(c.element)&&a.push(c)});l.length=0;u(C(a),function(a){function c(){a.beforeStart();var d,h=a.close;if(b(a.anchors?
a.from.element||a.to.element:a.element)){var k=f(a);k&&(d=k.start)}d?(d=d(),d.done(function(a){h(!a)}),ta(a,d)):h()}a.structural?c():(I.push({node:A(a.element),fn:c}),a.classBasedIndex===Z-1&&(I=I.sort(function(a,b){return b.node.contains(a.node)}).map(function(a){return a.fn}),g(I)))})});return x}}]}]).provider("$animateCss",["$animateProvider",function(a){var b=Ba(),c=Ba();this.$get=["$window","$$jqLite","$$AnimateRunner","$timeout","$document","$sniffer","$$rAFScheduler",function(a,e,s,n,g,l,D){function z(a,
b){var c=a.parentNode;return(c.$$ngAnimateParentKey||(c.$$ngAnimateParentKey=++r))+"-"+a.getAttribute("class")+"-"+b}function Z(g,f,B,l){var h;0<b.count(B)&&(h=c.get(B),h||(f=ba(f,"-stagger"),e.addClass(g,f),h=za(a,g,l),h.animationDuration=Math.max(h.animationDuration,0),h.transitionDuration=Math.max(h.transitionDuration,0),e.removeClass(g,f),c.put(B,h)));return h||{}}function I(a){C.push(a);D.waitUntilQuiet(function(){b.flush();c.flush();for(var a=K.offsetWidth+1,d=0;d<C.length;d++)C[d](a);C.length=
0})}function w(c,f,e){f=b.get(e);f||(f=za(a,c,Ma),"infinite"===f.animationIterationCount&&(f.animationIterationCount=1));b.put(e,f);c=f;e=c.animationDelay;f=c.transitionDelay;c.maxDelay=e&&f?Math.max(e,f):e||f;c.maxDuration=Math.max(c.animationDuration*c.animationIterationCount,c.transitionDuration);return c}var B=ha(e),r=0,K=A(g).body,C=[];return function(a,c){function d(){h()}function g(){h(!0)}function h(b){if(!(K||C&&D)){K=!0;D=!1;e.removeClass(a,Y);e.removeClass(a,W);ma(k,!1);ja(k,!1);u(m,function(a){k.style[a[0]]=
""});B(a,c);ca(a,c);if(c.onDone)c.onDone();p&&p.complete(!b)}}function L(a){q.blockTransition&&ja(k,a);q.blockKeyframeAnimation&&ma(k,!!a)}function x(){p=new s({end:d,cancel:g});h();return{$$willAnimate:!1,start:function(){return p},end:d}}function M(){function b(){if(!K){L(!1);u(m,function(a){k.style[a[0]]=a[1]});B(a,c);e.addClass(a,W);if(q.recalculateTimingStyles){fa=k.className+" "+Y;$=z(k,fa);y=w(k,fa,$);Q=y.maxDelay;H=Math.max(Q,0);J=y.maxDuration;if(0===J){h();return}q.hasTransitions=0<y.transitionDuration;
q.hasAnimations=0<y.animationDuration}if(q.applyTransitionDelay||q.applyAnimationDelay){Q="boolean"!==typeof c.delay&&la(c.delay)?parseFloat(c.delay):Q;H=Math.max(Q,0);var l;q.applyTransitionDelay&&(y.transitionDelay=Q,l=[ea,Q+"s"],m.push(l),k.style[l[0]]=l[1]);q.applyAnimationDelay&&(y.animationDelay=Q,l=[ra,Q+"s"],m.push(l),k.style[l[0]]=l[1])}F=1E3*H;G=1E3*J;if(c.easing){var r=c.easing;q.hasTransitions&&(l=O+"TimingFunction",m.push([l,r]),k.style[l]=r);q.hasAnimations&&(l=V+"TimingFunction",m.push([l,
r]),k.style[l]=r)}y.transitionDuration&&p.push(pa);y.animationDuration&&p.push(qa);x=Date.now();a.on(p.join(" "),g);n(d,F+1.5*G);xa(a,c)}}function d(){h()}function g(a){a.stopPropagation();var b=a.originalEvent||a;a=b.$manualTimeStamp||b.timeStamp||Date.now();b=parseFloat(b.elapsedTime.toFixed(3));Math.max(a-x,0)>=F&&b>=J&&(C=!0,h())}if(!K){var x,p=[],l=function(a){if(C)D&&a&&(D=!1,h());else if(D=!a,y.animationDuration)if(a=ma(k,D),D)m.push(a);else{var b=m,c=b.indexOf(a);0<=a&&b.splice(c,1)}},r=0<
U&&(y.transitionDuration&&0===T.transitionDuration||y.animationDuration&&0===T.animationDuration)&&Math.max(T.animationDelay,T.transitionDelay);r?n(b,Math.floor(r*U*1E3),!1):b();t.resume=function(){l(!0)};t.pause=function(){l(!1)}}}var k=A(a);c=ia(c);var m=[],r=a.attr("class"),v=Ea(c),K,D,C,p,t,H,F,J,G;if(0===c.duration||!l.animations&&!l.transitions)return x();var aa=c.event&&X(c.event)?c.event.join(" "):c.event,R="",N="";aa&&c.structural?R=ba(aa,"ng-",!0):aa&&(R=aa);c.addClass&&(N+=ba(c.addClass,
"-add"));c.removeClass&&(N.length&&(N+=" "),N+=ba(c.removeClass,"-remove"));c.applyClassesEarly&&N.length&&(B(a,c),N="");var Y=[R,N].join(" ").trim(),fa=r+" "+Y,W=ba(Y,"-active"),r=v.to&&0<Object.keys(v.to).length;if(!r&&!Y)return x();var $,T;0<c.stagger?(v=parseFloat(c.stagger),T={transitionDelay:v,animationDelay:v,transitionDuration:0,animationDuration:0}):($=z(k,fa),T=Z(k,Y,$,Na));e.addClass(a,Y);c.transitionStyle&&(v=[O,c.transitionStyle],da(k,v),m.push(v));0<=c.duration&&(v=0<k.style[O].length,
v=Aa(c.duration,v),da(k,v),m.push(v));c.keyframeStyle&&(v=[V,c.keyframeStyle],da(k,v),m.push(v));var U=T?0<=c.staggerIndex?c.staggerIndex:b.count($):0;(aa=0===U)&&ja(k,9999);var y=w(k,fa,$),Q=y.maxDelay;H=Math.max(Q,0);J=y.maxDuration;var q={};q.hasTransitions=0<y.transitionDuration;q.hasAnimations=0<y.animationDuration;q.hasTransitionAll=q.hasTransitions&&"all"==y.transitionProperty;q.applyTransitionDuration=r&&(q.hasTransitions&&!q.hasTransitionAll||q.hasAnimations&&!q.hasTransitions);q.applyAnimationDuration=
c.duration&&q.hasAnimations;q.applyTransitionDelay=la(c.delay)&&(q.applyTransitionDuration||q.hasTransitions);q.applyAnimationDelay=la(c.delay)&&q.hasAnimations;q.recalculateTimingStyles=0<N.length;if(q.applyTransitionDuration||q.applyAnimationDuration)J=c.duration?parseFloat(c.duration):J,q.applyTransitionDuration&&(q.hasTransitions=!0,y.transitionDuration=J,v=0<k.style[O+"Property"].length,m.push(Aa(J,v))),q.applyAnimationDuration&&(q.hasAnimations=!0,y.animationDuration=J,m.push([sa,J+"s"]));if(0===
J&&!q.recalculateTimingStyles)return x();null==c.duration&&0<y.transitionDuration&&(q.recalculateTimingStyles=q.recalculateTimingStyles||aa);F=1E3*H;G=1E3*J;c.skipBlocking||(q.blockTransition=0<y.transitionDuration,q.blockKeyframeAnimation=0<y.animationDuration&&0<T.animationDelay&&0===T.animationDuration);wa(a,c);q.blockTransition||ja(k,!1);L(J);return{$$willAnimate:!0,end:d,start:function(){if(!K)return t={end:d,cancel:g,resume:null,pause:null},p=new s(t),I(M),p}}}}]}]).provider("$$animateCssDriver",
["$$animationProvider",function(a){a.drivers.push("$$animateCssDriver");this.$get=["$animateCss","$rootScope","$$AnimateRunner","$rootElement","$document","$sniffer",function(a,c,d,e,s,n){function g(a){return a.replace(/\bng-\S+\b/g,"")}function l(a,b){U(a)&&(a=a.split(" "));U(b)&&(b=b.split(" "));return a.filter(function(a){return-1===b.indexOf(a)}).join(" ")}function D(c,e,z){function D(a){var b={},c=A(a).getBoundingClientRect();u(["width","height","top","left"],function(a){var d=c[a];switch(a){case "top":d+=
I.scrollTop;break;case "left":d+=I.scrollLeft}b[a]=Math.floor(d)+"px"});return b}function s(){var c=g(z.attr("class")||""),d=l(c,t),c=l(t,c),d=a(n,{to:D(z),addClass:"ng-anchor-in "+d,removeClass:"ng-anchor-out "+c,delay:!0});return d.$$willAnimate?d:null}function f(){n.remove();e.removeClass("ng-animate-shim");z.removeClass("ng-animate-shim")}var n=G(A(e).cloneNode(!0)),t=g(n.attr("class")||"");e.addClass("ng-animate-shim");z.addClass("ng-animate-shim");n.addClass("ng-anchor");w.append(n);var h;c=
function(){var c=a(n,{addClass:"ng-anchor-out",delay:!0,from:D(e)});return c.$$willAnimate?c:null}();if(!c&&(h=s(),!h))return f();var L=c||h;return{start:function(){function a(){c&&c.end()}var b,c=L.start();c.done(function(){c=null;if(!h&&(h=s()))return c=h.start(),c.done(function(){c=null;f();b.complete()}),c;f();b.complete()});return b=new d({end:a,cancel:a})}}}function z(a,b,c,e){var g=t(a),f=t(b),l=[];u(e,function(a){(a=D(c,a.out,a["in"]))&&l.push(a)});if(g||f||0!==l.length)return{start:function(){function a(){u(b,
function(a){a.end()})}var b=[];g&&b.push(g.start());f&&b.push(f.start());u(l,function(a){b.push(a.start())});var c=new d({end:a,cancel:a});d.all(b,function(a){c.complete(a)});return c}}}function t(c){var d=c.element,e=c.options||{};c.structural?(e.structural=e.applyClassesEarly=!0,e.event=c.event,"leave"===e.event&&(e.onDone=e.domOperation)):e.event=null;c=a(d,e);return c.$$willAnimate?c:null}if(!n.animations&&!n.transitions)return H;var I=A(s).body;c=A(e);var w=G(I.parentNode===c?I:c);return function(a){return a.from&&
a.to?z(a.from,a.to,a.classes,a.anchors):t(a)}}]}]).provider("$$animateJs",["$animateProvider",function(a){this.$get=["$injector","$$AnimateRunner","$$rAFMutex","$$jqLite",function(b,c,d,e){function s(c){c=X(c)?c:c.split(" ");for(var d=[],e={},z=0;z<c.length;z++){var n=c[z],s=a.$$registeredAnimations[n];s&&!e[n]&&(d.push(b.get(s)),e[n]=!0)}return d}var n=ha(e);return function(a,b,d,e){function t(){e.domOperation();n(a,e)}function A(a,b,d,e,f){switch(d){case "animate":b=[b,e.from,e.to,f];break;case "setClass":b=
[b,r,K,f];break;case "addClass":b=[b,r,f];break;case "removeClass":b=[b,K,f];break;default:b=[b,f]}b.push(e);if(a=a.apply(a,b))if(Ca(a.start)&&(a=a.start()),a instanceof c)a.done(f);else if(Ca(a))return a;return H}function w(a,b,d,e,f){var m=[];u(e,function(e){var g=e[f];g&&m.push(function(){var e,f,m=!1,k=function(a){m||(m=!0,(f||H)(a),e.complete(!a))};e=new c({end:function(){k()},cancel:function(){k(!0)}});f=A(g,a,b,d,function(a){k(!1===a)});return e})});return m}function B(a,b,d,e,f){var m=w(a,
b,d,e,f);if(0===m.length){var g,l;"beforeSetClass"===f?(g=w(a,"removeClass",d,e,"beforeRemoveClass"),l=w(a,"addClass",d,e,"beforeAddClass")):"setClass"===f&&(g=w(a,"removeClass",d,e,"removeClass"),l=w(a,"addClass",d,e,"addClass"));g&&(m=m.concat(g));l&&(m=m.concat(l))}if(0!==m.length)return function(a){var b=[];m.length&&u(m,function(a){b.push(a())});b.length?c.all(b,a):a();return function(a){u(b,function(b){a?b.cancel():b.end()})}}}3===arguments.length&&na(d)&&(e=d,d=null);e=ia(e);d||(d=a.attr("class")||
"",e.addClass&&(d+=" "+e.addClass),e.removeClass&&(d+=" "+e.removeClass));var r=e.addClass,K=e.removeClass,C=s(d),E,f;if(C.length){var F,G;"leave"==b?(G="leave",F="afterLeave"):(G="before"+b.charAt(0).toUpperCase()+b.substr(1),F=b);"enter"!==b&&"move"!==b&&(E=B(a,b,e,C,G));f=B(a,b,e,C,F)}if(E||f)return{start:function(){function b(c){n=!0;t();ca(a,e);k.complete(c)}var d,l=[];E&&l.push(function(a){d=E(a)});l.length?l.push(function(a){t();a(!0)}):t();f&&l.push(function(a){d=f(a)});var n=!1,k=new c({end:function(){n||
((d||H)(void 0),b(void 0))},cancel:function(){n||((d||H)(!0),b(!0))}});c.chain(l,b);return k}}}}]}]).provider("$$animateJsDriver",["$$animationProvider",function(a){a.drivers.push("$$animateJsDriver");this.$get=["$$animateJs","$$AnimateRunner",function(a,c){function d(c){return a(c.element,c.event,c.classes,c.options)}return function(a){if(a.from&&a.to){var b=d(a.from),n=d(a.to);if(b||n)return{start:function(){function a(){return function(){u(d,function(a){a.end()})}}var d=[];b&&d.push(b.start());
n&&d.push(n.start());c.all(d,function(a){e.complete(a)});var e=new c({end:a(),cancel:a()});return e}}}else return d(a)}}]}])})(window,window.angular);
//# sourceMappingURL=angular-animate.min.js.map
;
/*
 AngularJS v1.5.0-rc.2
 (c) 2010-2016 Google, Inc. http://angularjs.org
 License: MIT
*/
(function(A,e,B){'use strict';function C(a){var c=[];v(c,e.noop).chars(a);return c.join("")}function h(a,c){var b={},d=a.split(","),l;for(l=0;l<d.length;l++)b[c?e.lowercase(d[l]):d[l]]=!0;return b}function D(a,c){null===a||a===B?a="":"string"!==typeof a&&(a=""+a);g.innerHTML=a;var b=5;do{if(0===b)throw w("uinput");b--;11>=document.documentMode&&n(g);a=g.innerHTML;g.innerHTML=a}while(a!==g.innerHTML);for(b=g.firstChild;b;){switch(b.nodeType){case 1:c.start(b.nodeName.toLowerCase(),E(b.attributes));
break;case 3:c.chars(b.textContent)}var d;if(!(d=b.firstChild)&&(1==b.nodeType&&c.end(b.nodeName.toLowerCase()),d=b.nextSibling,!d))for(;null==d;){b=b.parentNode;if(b===g)break;d=b.nextSibling;1==b.nodeType&&c.end(b.nodeName.toLowerCase())}b=d}for(;b=g.firstChild;)g.removeChild(b)}function E(a){for(var c={},b=0,d=a.length;b<d;b++){var l=a[b];c[l.name]=l.value}return c}function x(a){return a.replace(/&/g,"&amp;").replace(F,function(a){var b=a.charCodeAt(0);a=a.charCodeAt(1);return"&#"+(1024*(b-55296)+
(a-56320)+65536)+";"}).replace(G,function(a){return"&#"+a.charCodeAt(0)+";"}).replace(/</g,"&lt;").replace(/>/g,"&gt;")}function v(a,c){var b=!1,d=e.bind(a,a.push);return{start:function(a,f){a=e.lowercase(a);!b&&H[a]&&(b=a);b||!0!==t[a]||(d("<"),d(a),e.forEach(f,function(b,f){var g=e.lowercase(f),h="img"===a&&"src"===g||"background"===g;!0!==I[g]||!0===y[g]&&!c(b,h)||(d(" "),d(f),d('="'),d(x(b)),d('"'))}),d(">"))},end:function(a){a=e.lowercase(a);b||!0!==t[a]||!0===z[a]||(d("</"),d(a),d(">"));a==
b&&(b=!1)},chars:function(a){b||d(x(a))}}}function n(a){if(a.nodeType===Node.ELEMENT_NODE)for(var c=a.attributes,b=0,d=c.length;b<d;b++){var e=c[b],f=e.name.toLowerCase();if("xmlns:ns1"===f||0===f.indexOf("ns1:"))a.removeAttributeNode(e),b--,d--}(c=a.firstChild)&&n(c);(c=a.nextSibling)&&n(c)}var w=e.$$minErr("$sanitize"),F=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,G=/([^\#-~ |!])/g,z=h("area,br,col,hr,img,wbr"),q=h("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),k=h("rp,rt"),u=e.extend({},k,q),q=e.extend({},
q,h("address,article,aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul")),k=e.extend({},k,h("a,abbr,acronym,b,bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var")),J=h("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,stop,svg,switch,text,title,tspan"),
H=h("script,style"),t=e.extend({},z,q,k,u),y=h("background,cite,href,longdesc,src,xlink:href"),u=h("abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,valign,value,vspace,width"),k=h("accent-height,accumulate,additive,alphabetic,arabic-form,ascent,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan",
!0),I=e.extend({},y,k,u),g;(function(a){if(a.document&&a.document.implementation)a=a.document.implementation.createHTMLDocument("inert");else throw w("noinert");var c=(a.documentElement||a.getDocumentElement()).getElementsByTagName("body");1===c.length?g=c[0]:(c=a.createElement("html"),g=a.createElement("body"),c.appendChild(g),a.appendChild(c))})(A);e.module("ngSanitize",[]).provider("$sanitize",function(){var a=!1;this.$get=["$$sanitizeUri",function(c){a&&e.extend(t,J);return function(a){var d=
[];D(a,v(d,function(a,b){return!/^unsafe:/.test(c(a,b))}));return d.join("")}}];this.enableSvg=function(c){return e.isDefined(c)?(a=c,this):a}});e.module("ngSanitize").filter("linky",["$sanitize",function(a){var c=/((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,b=/^mailto:/i,d=e.$$minErr("linky"),g=e.isString;return function(f,h,m){function k(a){a&&p.push(C(a))}function q(a,b){var c;p.push("<a ");e.isFunction(m)&&(m=m(a));if(e.isObject(m))for(c in m)p.push(c+
'="'+m[c]+'" ');else m={};!e.isDefined(h)||"target"in m||p.push('target="',h,'" ');p.push('href="',a.replace(/"/g,"&quot;"),'">');k(b);p.push("</a>")}if(null==f||""===f)return f;if(!g(f))throw d("notstring",f);for(var r=f,p=[],s,n;f=r.match(c);)s=f[0],f[2]||f[4]||(s=(f[3]?"http://":"mailto:")+s),n=f.index,k(r.substr(0,n)),q(s,f[0].replace(b,"")),r=r.substring(n+f[0].length);k(r);return a(p.join(""))}}])})(window,window.angular);
//# sourceMappingURL=angular-sanitize.min.js.map
;
/*
 * angular-ui-bootstrap
 * http://angular-ui.github.io/bootstrap/

 * Version: 2.1.4 - 2016-09-23
 * License: MIT
 */angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.collapse", "ui.bootstrap.tabindex", "ui.bootstrap.accordion", "ui.bootstrap.alert", "ui.bootstrap.buttons", "ui.bootstrap.carousel", "ui.bootstrap.dateparser", "ui.bootstrap.isClass", "ui.bootstrap.datepicker", "ui.bootstrap.position", "ui.bootstrap.datepickerPopup", "ui.bootstrap.debounce", "ui.bootstrap.dropdown", "ui.bootstrap.stackedMap", "ui.bootstrap.modal", "ui.bootstrap.paging", "ui.bootstrap.pager", "ui.bootstrap.pagination", "ui.bootstrap.tooltip", "ui.bootstrap.popover", "ui.bootstrap.progressbar", "ui.bootstrap.rating", "ui.bootstrap.tabs", "ui.bootstrap.timepicker", "ui.bootstrap.typeahead"]);
angular.module("ui.bootstrap.tpls", ["uib/template/accordion/accordion-group.html", "uib/template/accordion/accordion.html", "uib/template/alert/alert.html", "uib/template/carousel/carousel.html", "uib/template/carousel/slide.html", "uib/template/datepicker/datepicker.html", "uib/template/datepicker/day.html", "uib/template/datepicker/month.html", "uib/template/datepicker/year.html", "uib/template/datepickerPopup/popup.html", "uib/template/modal/window.html", "uib/template/pager/pager.html", "uib/template/pagination/pagination.html", "uib/template/tooltip/tooltip-html-popup.html", "uib/template/tooltip/tooltip-popup.html", "uib/template/tooltip/tooltip-template-popup.html", "uib/template/popover/popover-html.html", "uib/template/popover/popover-template.html", "uib/template/popover/popover.html", "uib/template/progressbar/bar.html", "uib/template/progressbar/progress.html", "uib/template/progressbar/progressbar.html", "uib/template/rating/rating.html", "uib/template/tabs/tab.html", "uib/template/tabs/tabset.html", "uib/template/timepicker/timepicker.html", "uib/template/typeahead/typeahead-match.html", "uib/template/typeahead/typeahead-popup.html"]);
angular.module('ui.bootstrap.collapse', [])

  .directive('uibCollapse', ['$animate', '$q', '$parse', '$injector', function ($animate, $q, $parse, $injector) {
  	var $animateCss = $injector.has('$animateCss') ? $injector.get('$animateCss') : null;
  	return {
  		link: function (scope, element, attrs) {
  			var expandingExpr = $parse(attrs.expanding),
			  expandedExpr = $parse(attrs.expanded),
			  collapsingExpr = $parse(attrs.collapsing),
			  collapsedExpr = $parse(attrs.collapsed),
			  horizontal = false,
			  css = {},
			  cssTo = {};

  			init();

  			function init() {
  				horizontal = !!('horizontal' in attrs);
  				if (horizontal) {
  					css = {
  						width: ''
  					};
  					cssTo = { width: '0' };
  				} else {
  					css = {
  						height: ''
  					};
  					cssTo = { height: '0' };
  				}
  				if (!scope.$eval(attrs.uibCollapse)) {
  					element.addClass('in')
					  .addClass('collapse')
					  .attr('aria-expanded', true)
					  .attr('aria-hidden', false)
					  .css(css);
  				}
  			}

  			function getScrollFromElement(element) {
  				if (horizontal) {
  					return { width: element.scrollWidth + 'px' };
  				}
  				return { height: element.scrollHeight + 'px' };
  			}

  			function expand() {
  				if (element.hasClass('collapse') && element.hasClass('in')) {
  					return;
  				}

  				$q.resolve(expandingExpr(scope))
				  .then(function () {
				  	element.removeClass('collapse')
					  .addClass('collapsing')
					  .attr('aria-expanded', true)
					  .attr('aria-hidden', false);

				  	if ($animateCss) {
				  		$animateCss(element, {
				  			addClass: 'in',
				  			easing: 'ease',
				  			css: {
				  				overflow: 'hidden'
				  			},
				  			to: getScrollFromElement(element[0])
				  		}).start()['finally'](expandDone);
				  	} else {
				  		$animate.addClass(element, 'in', {
				  			css: {
				  				overflow: 'hidden'
				  			},
				  			to: getScrollFromElement(element[0])
				  		}).then(expandDone);
				  	}
				  });
  			}

  			function expandDone() {
  				element.removeClass('collapsing')
				  .addClass('collapse')
				  .css(css);
  				expandedExpr(scope);
  			}

  			function collapse() {
  				if (!element.hasClass('collapse') && !element.hasClass('in')) {
  					return collapseDone();
  				}

  				$q.resolve(collapsingExpr(scope))
				  .then(function () {
				  	element
					// IMPORTANT: The width must be set before adding "collapsing" class.
					// Otherwise, the browser attempts to animate from width 0 (in
					// collapsing class) to the given width here.
					  .css(getScrollFromElement(element[0]))
					  // initially all panel collapse have the collapse class, this removal
					  // prevents the animation from jumping to collapsed state
					  .removeClass('collapse')
					  .addClass('collapsing')
					  .attr('aria-expanded', false)
					  .attr('aria-hidden', true);

				  	if ($animateCss) {
				  		$animateCss(element, {
				  			removeClass: 'in',
				  			to: cssTo
				  		}).start()['finally'](collapseDone);
				  	} else {
				  		$animate.removeClass(element, 'in', {
				  			to: cssTo
				  		}).then(collapseDone);
				  	}
				  });
  			}

  			function collapseDone() {
  				element.css(cssTo); // Required so that collapse works when animation is disabled
  				element.removeClass('collapsing')
				  .addClass('collapse');
  				collapsedExpr(scope);
  			}

  			scope.$watch(attrs.uibCollapse, function (shouldCollapse) {
  				if (shouldCollapse) {
  					collapse();
  				} else {
  					expand();
  				}
  			});
  		}
  	};
  }]);

angular.module('ui.bootstrap.tabindex', [])

.directive('uibTabindexToggle', function () {
	return {
		restrict: 'A',
		link: function (scope, elem, attrs) {
			attrs.$observe('disabled', function (disabled) {
				attrs.$set('tabindex', disabled ? -1 : null);
			});
		}
	};
});

angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse', 'ui.bootstrap.tabindex'])

.constant('uibAccordionConfig', {
	closeOthers: true
})

.controller('UibAccordionController', ['$scope', '$attrs', 'uibAccordionConfig', function ($scope, $attrs, accordionConfig) {
	// This array keeps track of the accordion groups
	this.groups = [];

	// Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to
	this.closeOthers = function (openGroup) {
		var closeOthers = angular.isDefined($attrs.closeOthers) ?
		  $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers;
		if (closeOthers) {
			angular.forEach(this.groups, function (group) {
				if (group !== openGroup) {
					group.isOpen = false;
				}
			});
		}
	};

	// This is called from the accordion-group directive to add itself to the accordion
	this.addGroup = function (groupScope) {
		var that = this;
		this.groups.push(groupScope);

		groupScope.$on('$destroy', function (event) {
			that.removeGroup(groupScope);
		});
	};

	// This is called from the accordion-group directive when to remove itself
	this.removeGroup = function (group) {
		var index = this.groups.indexOf(group);
		if (index !== -1) {
			this.groups.splice(index, 1);
		}
	};
}])

// The accordion directive simply sets up the directive controller
// and adds an accordion CSS class to itself element.
.directive('uibAccordion', function () {
	return {
		controller: 'UibAccordionController',
		controllerAs: 'accordion',
		transclude: true,
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/accordion/accordion.html';
		}
	};
})

// The accordion-group directive indicates a block of html that will expand and collapse in an accordion
.directive('uibAccordionGroup', function () {
	return {
		require: '^uibAccordion',         // We need this directive to be inside an accordion
		transclude: true,              // It transcludes the contents of the directive into the template
		restrict: 'A',
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/accordion/accordion-group.html';
		},
		scope: {
			heading: '@',               // Interpolate the heading attribute onto this scope
			panelClass: '@?',           // Ditto with panelClass
			isOpen: '=?',
			isDisabled: '=?'
		},
		controller: function () {
			this.setHeading = function (element) {
				this.heading = element;
			};
		},
		link: function (scope, element, attrs, accordionCtrl) {
			element.addClass('panel');
			accordionCtrl.addGroup(scope);

			scope.openClass = attrs.openClass || 'panel-open';
			scope.panelClass = attrs.panelClass || 'panel-default';
			scope.$watch('isOpen', function (value) {
				element.toggleClass(scope.openClass, !!value);
				if (value) {
					accordionCtrl.closeOthers(scope);
				}
			});

			scope.toggleOpen = function ($event) {
				if (!scope.isDisabled) {
					if (!$event || $event.which === 32) {
						scope.isOpen = !scope.isOpen;
					}
				}
			};

			var id = 'accordiongroup-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
			scope.headingId = id + '-tab';
			scope.panelId = id + '-panel';
		}
	};
})

// Use accordion-heading below an accordion-group to provide a heading containing HTML
.directive('uibAccordionHeading', function () {
	return {
		transclude: true,   // Grab the contents to be used as the heading
		template: '',       // In effect remove this element!
		replace: true,
		require: '^uibAccordionGroup',
		link: function (scope, element, attrs, accordionGroupCtrl, transclude) {
			// Pass the heading to the accordion-group controller
			// so that it can be transcluded into the right place in the template
			// [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]
			accordionGroupCtrl.setHeading(transclude(scope, angular.noop));
		}
	};
})

// Use in the accordion-group template to indicate where you want the heading to be transcluded
// You must provide the property on the accordion-group controller that will hold the transcluded element
.directive('uibAccordionTransclude', function () {
	return {
		require: '^uibAccordionGroup',
		link: function (scope, element, attrs, controller) {
			scope.$watch(function () { return controller[attrs.uibAccordionTransclude]; }, function (heading) {
				if (heading) {
					var elem = angular.element(element[0].querySelector(getHeaderSelectors()));
					elem.html('');
					elem.append(heading);
				}
			});
		}
	};

	function getHeaderSelectors() {
		return 'uib-accordion-header,' +
			'data-uib-accordion-header,' +
			'x-uib-accordion-header,' +
			'uib\\:accordion-header,' +
			'[uib-accordion-header],' +
			'[data-uib-accordion-header],' +
			'[x-uib-accordion-header]';
	}
});

angular.module('ui.bootstrap.alert', [])

.controller('UibAlertController', ['$scope', '$element', '$attrs', '$interpolate', '$timeout', function ($scope, $element, $attrs, $interpolate, $timeout) {
	$scope.closeable = !!$attrs.close;
	$element.addClass('alert');
	$attrs.$set('role', 'alert');
	if ($scope.closeable) {
		$element.addClass('alert-dismissible');
	}

	var dismissOnTimeout = angular.isDefined($attrs.dismissOnTimeout) ?
	  $interpolate($attrs.dismissOnTimeout)($scope.$parent) : null;

	if (dismissOnTimeout) {
		$timeout(function () {
			$scope.close();
		}, parseInt(dismissOnTimeout, 10));
	}
}])

.directive('uibAlert', function () {
	return {
		controller: 'UibAlertController',
		controllerAs: 'alert',
		restrict: 'A',
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/alert/alert.html';
		},
		transclude: true,
		scope: {
			close: '&'
		}
	};
});

angular.module('ui.bootstrap.buttons', [])

.constant('uibButtonConfig', {
	activeClass: 'active',
	toggleEvent: 'click'
})

.controller('UibButtonsController', ['uibButtonConfig', function (buttonConfig) {
	this.activeClass = buttonConfig.activeClass || 'active';
	this.toggleEvent = buttonConfig.toggleEvent || 'click';
}])

.directive('uibBtnRadio', ['$parse', function ($parse) {
	return {
		require: ['uibBtnRadio', 'ngModel'],
		controller: 'UibButtonsController',
		controllerAs: 'buttons',
		link: function (scope, element, attrs, ctrls) {
			var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
			var uncheckableExpr = $parse(attrs.uibUncheckable);

			element.find('input').css({ display: 'none' });

			//model -> UI
			ngModelCtrl.$render = function () {
				element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.uibBtnRadio)));
			};

			//ui->model
			element.on(buttonsCtrl.toggleEvent, function () {
				if (attrs.disabled) {
					return;
				}

				var isActive = element.hasClass(buttonsCtrl.activeClass);

				if (!isActive || angular.isDefined(attrs.uncheckable)) {
					scope.$apply(function () {
						ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.uibBtnRadio));
						ngModelCtrl.$render();
					});
				}
			});

			if (attrs.uibUncheckable) {
				scope.$watch(uncheckableExpr, function (uncheckable) {
					attrs.$set('uncheckable', uncheckable ? '' : undefined);
				});
			}
		}
	};
}])

.directive('uibBtnCheckbox', function () {
	return {
		require: ['uibBtnCheckbox', 'ngModel'],
		controller: 'UibButtonsController',
		controllerAs: 'button',
		link: function (scope, element, attrs, ctrls) {
			var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];

			element.find('input').css({ display: 'none' });

			function getTrueValue() {
				return getCheckboxValue(attrs.btnCheckboxTrue, true);
			}

			function getFalseValue() {
				return getCheckboxValue(attrs.btnCheckboxFalse, false);
			}

			function getCheckboxValue(attribute, defaultValue) {
				return angular.isDefined(attribute) ? scope.$eval(attribute) : defaultValue;
			}

			//model -> UI
			ngModelCtrl.$render = function () {
				element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));
			};

			//ui->model
			element.on(buttonsCtrl.toggleEvent, function () {
				if (attrs.disabled) {
					return;
				}

				scope.$apply(function () {
					ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
					ngModelCtrl.$render();
				});
			});
		}
	};
});

angular.module('ui.bootstrap.carousel', [])

.controller('UibCarouselController', ['$scope', '$element', '$interval', '$timeout', '$animate', function ($scope, $element, $interval, $timeout, $animate) {
	var self = this,
	  slides = self.slides = $scope.slides = [],
	  SLIDE_DIRECTION = 'uib-slideDirection',
	  currentIndex = $scope.active,
	  currentInterval, isPlaying, bufferedTransitions = [];

	var destroyed = false;
	$element.addClass('carousel');

	self.addSlide = function (slide, element) {
		slides.push({
			slide: slide,
			element: element
		});
		slides.sort(function (a, b) {
			return +a.slide.index - +b.slide.index;
		});
		//if this is the first slide or the slide is set to active, select it
		if (slide.index === $scope.active || slides.length === 1 && !angular.isNumber($scope.active)) {
			if ($scope.$currentTransition) {
				$scope.$currentTransition = null;
			}

			currentIndex = slide.index;
			$scope.active = slide.index;
			setActive(currentIndex);
			self.select(slides[findSlideIndex(slide)]);
			if (slides.length === 1) {
				$scope.play();
			}
		}
	};

	self.getCurrentIndex = function () {
		for (var i = 0; i < slides.length; i++) {
			if (slides[i].slide.index === currentIndex) {
				return i;
			}
		}
	};

	self.next = $scope.next = function () {
		var newIndex = (self.getCurrentIndex() + 1) % slides.length;

		if (newIndex === 0 && $scope.noWrap()) {
			$scope.pause();
			return;
		}

		return self.select(slides[newIndex], 'next');
	};

	self.prev = $scope.prev = function () {
		var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1;

		if ($scope.noWrap() && newIndex === slides.length - 1) {
			$scope.pause();
			return;
		}

		return self.select(slides[newIndex], 'prev');
	};

	self.removeSlide = function (slide) {
		var index = findSlideIndex(slide);

		var bufferedIndex = bufferedTransitions.indexOf(slides[index]);
		if (bufferedIndex !== -1) {
			bufferedTransitions.splice(bufferedIndex, 1);
		}

		//get the index of the slide inside the carousel
		slides.splice(index, 1);
		if (slides.length > 0 && currentIndex === index) {
			if (index >= slides.length) {
				currentIndex = slides.length - 1;
				$scope.active = currentIndex;
				setActive(currentIndex);
				self.select(slides[slides.length - 1]);
			} else {
				currentIndex = index;
				$scope.active = currentIndex;
				setActive(currentIndex);
				self.select(slides[index]);
			}
		} else if (currentIndex > index) {
			currentIndex--;
			$scope.active = currentIndex;
		}

		//clean the active value when no more slide
		if (slides.length === 0) {
			currentIndex = null;
			$scope.active = null;
			clearBufferedTransitions();
		}
	};

	/* direction: "prev" or "next" */
	self.select = $scope.select = function (nextSlide, direction) {
		var nextIndex = findSlideIndex(nextSlide.slide);
		//Decide direction if it's not given
		if (direction === undefined) {
			direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev';
		}
		//Prevent this user-triggered transition from occurring if there is already one in progress
		if (nextSlide.slide.index !== currentIndex &&
		  !$scope.$currentTransition) {
			goNext(nextSlide.slide, nextIndex, direction);
		} else if (nextSlide && nextSlide.slide.index !== currentIndex && $scope.$currentTransition) {
			bufferedTransitions.push(slides[nextIndex]);
		}
	};

	/* Allow outside people to call indexOf on slides array */
	$scope.indexOfSlide = function (slide) {
		return +slide.slide.index;
	};

	$scope.isActive = function (slide) {
		return $scope.active === slide.slide.index;
	};

	$scope.isPrevDisabled = function () {
		return $scope.active === 0 && $scope.noWrap();
	};

	$scope.isNextDisabled = function () {
		return $scope.active === slides.length - 1 && $scope.noWrap();
	};

	$scope.pause = function () {
		if (!$scope.noPause) {
			isPlaying = false;
			resetTimer();
		}
	};

	$scope.play = function () {
		if (!isPlaying) {
			isPlaying = true;
			restartTimer();
		}
	};

	$element.on('mouseenter', $scope.pause);
	$element.on('mouseleave', $scope.play);

	$scope.$on('$destroy', function () {
		destroyed = true;
		resetTimer();
	});

	$scope.$watch('noTransition', function (noTransition) {
		$animate.enabled($element, !noTransition);
	});

	$scope.$watch('interval', restartTimer);

	$scope.$watchCollection('slides', resetTransition);

	$scope.$watch('active', function (index) {
		if (angular.isNumber(index) && currentIndex !== index) {
			for (var i = 0; i < slides.length; i++) {
				if (slides[i].slide.index === index) {
					index = i;
					break;
				}
			}

			var slide = slides[index];
			if (slide) {
				setActive(index);
				self.select(slides[index]);
				currentIndex = index;
			}
		}
	});

	function clearBufferedTransitions() {
		while (bufferedTransitions.length) {
			bufferedTransitions.shift();
		}
	}

	function getSlideByIndex(index) {
		for (var i = 0, l = slides.length; i < l; ++i) {
			if (slides[i].index === index) {
				return slides[i];
			}
		}
	}

	function setActive(index) {
		for (var i = 0; i < slides.length; i++) {
			slides[i].slide.active = i === index;
		}
	}

	function goNext(slide, index, direction) {
		if (destroyed) {
			return;
		}

		angular.extend(slide, { direction: direction });
		angular.extend(slides[currentIndex].slide || {}, { direction: direction });
		if ($animate.enabled($element) && !$scope.$currentTransition &&
		  slides[index].element && self.slides.length > 1) {
			slides[index].element.data(SLIDE_DIRECTION, slide.direction);
			var currentIdx = self.getCurrentIndex();

			if (angular.isNumber(currentIdx) && slides[currentIdx].element) {
				slides[currentIdx].element.data(SLIDE_DIRECTION, slide.direction);
			}

			$scope.$currentTransition = true;
			$animate.on('addClass', slides[index].element, function (element, phase) {
				if (phase === 'close') {
					$scope.$currentTransition = null;
					$animate.off('addClass', element);
					if (bufferedTransitions.length) {
						var nextSlide = bufferedTransitions.pop().slide;
						var nextIndex = nextSlide.index;
						var nextDirection = nextIndex > self.getCurrentIndex() ? 'next' : 'prev';
						clearBufferedTransitions();

						goNext(nextSlide, nextIndex, nextDirection);
					}
				}
			});
		}

		$scope.active = slide.index;
		currentIndex = slide.index;
		setActive(index);

		//every time you change slides, reset the timer
		restartTimer();
	}

	function findSlideIndex(slide) {
		for (var i = 0; i < slides.length; i++) {
			if (slides[i].slide === slide) {
				return i;
			}
		}
	}

	function resetTimer() {
		if (currentInterval) {
			$interval.cancel(currentInterval);
			currentInterval = null;
		}
	}

	function resetTransition(slides) {
		if (!slides.length) {
			$scope.$currentTransition = null;
			clearBufferedTransitions();
		}
	}

	function restartTimer() {
		resetTimer();
		var interval = +$scope.interval;
		if (!isNaN(interval) && interval > 0) {
			currentInterval = $interval(timerFn, interval);
		}
	}

	function timerFn() {
		var interval = +$scope.interval;
		if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) {
			$scope.next();
		} else {
			$scope.pause();
		}
	}
}])

.directive('uibCarousel', function () {
	return {
		transclude: true,
		controller: 'UibCarouselController',
		controllerAs: 'carousel',
		restrict: 'A',
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/carousel/carousel.html';
		},
		scope: {
			active: '=',
			interval: '=',
			noTransition: '=',
			noPause: '=',
			noWrap: '&'
		}
	};
})

.directive('uibSlide', ['$animate', function ($animate) {
	return {
		require: '^uibCarousel',
		restrict: 'A',
		transclude: true,
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/carousel/slide.html';
		},
		scope: {
			actual: '=?',
			index: '=?'
		},
		link: function (scope, element, attrs, carouselCtrl) {
			element.addClass('item');
			carouselCtrl.addSlide(scope, element);
			//when the scope is destroyed then remove the slide from the current slides array
			scope.$on('$destroy', function () {
				carouselCtrl.removeSlide(scope);
			});

			scope.$watch('active', function (active) {
				$animate[active ? 'addClass' : 'removeClass'](element, 'active');
			});
		}
	};
}])

.animation('.item', ['$animateCss',
function ($animateCss) {
	var SLIDE_DIRECTION = 'uib-slideDirection';

	function removeClass(element, className, callback) {
		element.removeClass(className);
		if (callback) {
			callback();
		}
	}

	return {
		beforeAddClass: function (element, className, done) {
			if (className === 'active') {
				var stopped = false;
				var direction = element.data(SLIDE_DIRECTION);
				var directionClass = direction === 'next' ? 'left' : 'right';
				var removeClassFn = removeClass.bind(this, element,
				  directionClass + ' ' + direction, done);
				element.addClass(direction);

				$animateCss(element, { addClass: directionClass })
				  .start()
				  .done(removeClassFn);

				return function () {
					stopped = true;
				};
			}
			done();
		},
		beforeRemoveClass: function (element, className, done) {
			if (className === 'active') {
				var stopped = false;
				var direction = element.data(SLIDE_DIRECTION);
				var directionClass = direction === 'next' ? 'left' : 'right';
				var removeClassFn = removeClass.bind(this, element, directionClass, done);

				$animateCss(element, { addClass: directionClass })
				  .start()
				  .done(removeClassFn);

				return function () {
					stopped = true;
				};
			}
			done();
		}
	};
}]);

angular.module('ui.bootstrap.dateparser', [])

.service('uibDateParser', ['$log', '$locale', 'dateFilter', 'orderByFilter', function ($log, $locale, dateFilter, orderByFilter) {
	// Pulled from https://github.com/mbostock/d3/blob/master/src/format/requote.js
	var SPECIAL_CHARACTERS_REGEXP = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;

	var localeId;
	var formatCodeToRegex;

	this.init = function () {
		localeId = $locale.id;

		this.parsers = {};
		this.formatters = {};

		formatCodeToRegex = [
		  {
		  	key: 'yyyy',
		  	regex: '\\d{4}',
		  	apply: function (value) { this.year = +value; },
		  	formatter: function (date) {
		  		var _date = new Date();
		  		_date.setFullYear(Math.abs(date.getFullYear()));
		  		return dateFilter(_date, 'yyyy');
		  	}
		  },
		  {
		  	key: 'yy',
		  	regex: '\\d{2}',
		  	apply: function (value) { value = +value; this.year = value < 69 ? value + 2000 : value + 1900; },
		  	formatter: function (date) {
		  		var _date = new Date();
		  		_date.setFullYear(Math.abs(date.getFullYear()));
		  		return dateFilter(_date, 'yy');
		  	}
		  },
		  {
		  	key: 'y',
		  	regex: '\\d{1,4}',
		  	apply: function (value) { this.year = +value; },
		  	formatter: function (date) {
		  		var _date = new Date();
		  		_date.setFullYear(Math.abs(date.getFullYear()));
		  		return dateFilter(_date, 'y');
		  	}
		  },
		  {
		  	key: 'M!',
		  	regex: '0?[1-9]|1[0-2]',
		  	apply: function (value) { this.month = value - 1; },
		  	formatter: function (date) {
		  		var value = date.getMonth();
		  		if (/^[0-9]$/.test(value)) {
		  			return dateFilter(date, 'MM');
		  		}

		  		return dateFilter(date, 'M');
		  	}
		  },
		  {
		  	key: 'MMMM',
		  	regex: $locale.DATETIME_FORMATS.MONTH.join('|'),
		  	apply: function (value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); },
		  	formatter: function (date) { return dateFilter(date, 'MMMM'); }
		  },
		  {
		  	key: 'MMM',
		  	regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
		  	apply: function (value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); },
		  	formatter: function (date) { return dateFilter(date, 'MMM'); }
		  },
		  {
		  	key: 'MM',
		  	regex: '0[1-9]|1[0-2]',
		  	apply: function (value) { this.month = value - 1; },
		  	formatter: function (date) { return dateFilter(date, 'MM'); }
		  },
		  {
		  	key: 'M',
		  	regex: '[1-9]|1[0-2]',
		  	apply: function (value) { this.month = value - 1; },
		  	formatter: function (date) { return dateFilter(date, 'M'); }
		  },
		  {
		  	key: 'd!',
		  	regex: '[0-2]?[0-9]{1}|3[0-1]{1}',
		  	apply: function (value) { this.date = +value; },
		  	formatter: function (date) {
		  		var value = date.getDate();
		  		if (/^[1-9]$/.test(value)) {
		  			return dateFilter(date, 'dd');
		  		}

		  		return dateFilter(date, 'd');
		  	}
		  },
		  {
		  	key: 'dd',
		  	regex: '[0-2][0-9]{1}|3[0-1]{1}',
		  	apply: function (value) { this.date = +value; },
		  	formatter: function (date) { return dateFilter(date, 'dd'); }
		  },
		  {
		  	key: 'd',
		  	regex: '[1-2]?[0-9]{1}|3[0-1]{1}',
		  	apply: function (value) { this.date = +value; },
		  	formatter: function (date) { return dateFilter(date, 'd'); }
		  },
		  {
		  	key: 'EEEE',
		  	regex: $locale.DATETIME_FORMATS.DAY.join('|'),
		  	formatter: function (date) { return dateFilter(date, 'EEEE'); }
		  },
		  {
		  	key: 'EEE',
		  	regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|'),
		  	formatter: function (date) { return dateFilter(date, 'EEE'); }
		  },
		  {
		  	key: 'HH',
		  	regex: '(?:0|1)[0-9]|2[0-3]',
		  	apply: function (value) { this.hours = +value; },
		  	formatter: function (date) { return dateFilter(date, 'HH'); }
		  },
		  {
		  	key: 'hh',
		  	regex: '0[0-9]|1[0-2]',
		  	apply: function (value) { this.hours = +value; },
		  	formatter: function (date) { return dateFilter(date, 'hh'); }
		  },
		  {
		  	key: 'H',
		  	regex: '1?[0-9]|2[0-3]',
		  	apply: function (value) { this.hours = +value; },
		  	formatter: function (date) { return dateFilter(date, 'H'); }
		  },
		  {
		  	key: 'h',
		  	regex: '[0-9]|1[0-2]',
		  	apply: function (value) { this.hours = +value; },
		  	formatter: function (date) { return dateFilter(date, 'h'); }
		  },
		  {
		  	key: 'mm',
		  	regex: '[0-5][0-9]',
		  	apply: function (value) { this.minutes = +value; },
		  	formatter: function (date) { return dateFilter(date, 'mm'); }
		  },
		  {
		  	key: 'm',
		  	regex: '[0-9]|[1-5][0-9]',
		  	apply: function (value) { this.minutes = +value; },
		  	formatter: function (date) { return dateFilter(date, 'm'); }
		  },
		  {
		  	key: 'sss',
		  	regex: '[0-9][0-9][0-9]',
		  	apply: function (value) { this.milliseconds = +value; },
		  	formatter: function (date) { return dateFilter(date, 'sss'); }
		  },
		  {
		  	key: 'ss',
		  	regex: '[0-5][0-9]',
		  	apply: function (value) { this.seconds = +value; },
		  	formatter: function (date) { return dateFilter(date, 'ss'); }
		  },
		  {
		  	key: 's',
		  	regex: '[0-9]|[1-5][0-9]',
		  	apply: function (value) { this.seconds = +value; },
		  	formatter: function (date) { return dateFilter(date, 's'); }
		  },
		  {
		  	key: 'a',
		  	regex: $locale.DATETIME_FORMATS.AMPMS.join('|'),
		  	apply: function (value) {
		  		if (this.hours === 12) {
		  			this.hours = 0;
		  		}

		  		if (value === 'PM') {
		  			this.hours += 12;
		  		}
		  	},
		  	formatter: function (date) { return dateFilter(date, 'a'); }
		  },
		  {
		  	key: 'Z',
		  	regex: '[+-]\\d{4}',
		  	apply: function (value) {
		  		var matches = value.match(/([+-])(\d{2})(\d{2})/),
				  sign = matches[1],
				  hours = matches[2],
				  minutes = matches[3];
		  		this.hours += toInt(sign + hours);
		  		this.minutes += toInt(sign + minutes);
		  	},
		  	formatter: function (date) {
		  		return dateFilter(date, 'Z');
		  	}
		  },
		  {
		  	key: 'ww',
		  	regex: '[0-4][0-9]|5[0-3]',
		  	formatter: function (date) { return dateFilter(date, 'ww'); }
		  },
		  {
		  	key: 'w',
		  	regex: '[0-9]|[1-4][0-9]|5[0-3]',
		  	formatter: function (date) { return dateFilter(date, 'w'); }
		  },
		  {
		  	key: 'GGGG',
		  	regex: $locale.DATETIME_FORMATS.ERANAMES.join('|').replace(/\s/g, '\\s'),
		  	formatter: function (date) { return dateFilter(date, 'GGGG'); }
		  },
		  {
		  	key: 'GGG',
		  	regex: $locale.DATETIME_FORMATS.ERAS.join('|'),
		  	formatter: function (date) { return dateFilter(date, 'GGG'); }
		  },
		  {
		  	key: 'GG',
		  	regex: $locale.DATETIME_FORMATS.ERAS.join('|'),
		  	formatter: function (date) { return dateFilter(date, 'GG'); }
		  },
		  {
		  	key: 'G',
		  	regex: $locale.DATETIME_FORMATS.ERAS.join('|'),
		  	formatter: function (date) { return dateFilter(date, 'G'); }
		  }
		];
	};

	this.init();

	function createParser(format) {
		var map = [], regex = format.split('');

		// check for literal values
		var quoteIndex = format.indexOf('\'');
		if (quoteIndex > -1) {
			var inLiteral = false;
			format = format.split('');
			for (var i = quoteIndex; i < format.length; i++) {
				if (inLiteral) {
					if (format[i] === '\'') {
						if (i + 1 < format.length && format[i + 1] === '\'') { // escaped single quote
							format[i + 1] = '$';
							regex[i + 1] = '';
						} else { // end of literal
							regex[i] = '';
							inLiteral = false;
						}
					}
					format[i] = '$';
				} else {
					if (format[i] === '\'') { // start of literal
						format[i] = '$';
						regex[i] = '';
						inLiteral = true;
					}
				}
			}

			format = format.join('');
		}

		angular.forEach(formatCodeToRegex, function (data) {
			var index = format.indexOf(data.key);

			if (index > -1) {
				format = format.split('');

				regex[index] = '(' + data.regex + ')';
				format[index] = '$'; // Custom symbol to define consumed part of format
				for (var i = index + 1, n = index + data.key.length; i < n; i++) {
					regex[i] = '';
					format[i] = '$';
				}
				format = format.join('');

				map.push({
					index: index,
					key: data.key,
					apply: data.apply,
					matcher: data.regex
				});
			}
		});

		return {
			regex: new RegExp('^' + regex.join('') + '$'),
			map: orderByFilter(map, 'index')
		};
	}

	function createFormatter(format) {
		var formatters = [];
		var i = 0;
		var formatter, literalIdx;
		while (i < format.length) {
			if (angular.isNumber(literalIdx)) {
				if (format.charAt(i) === '\'') {
					if (i + 1 >= format.length || format.charAt(i + 1) !== '\'') {
						formatters.push(constructLiteralFormatter(format, literalIdx, i));
						literalIdx = null;
					}
				} else if (i === format.length) {
					while (literalIdx < format.length) {
						formatter = constructFormatterFromIdx(format, literalIdx);
						formatters.push(formatter);
						literalIdx = formatter.endIdx;
					}
				}

				i++;
				continue;
			}

			if (format.charAt(i) === '\'') {
				literalIdx = i;
				i++;
				continue;
			}

			formatter = constructFormatterFromIdx(format, i);

			formatters.push(formatter.parser);
			i = formatter.endIdx;
		}

		return formatters;
	}

	function constructLiteralFormatter(format, literalIdx, endIdx) {
		return function () {
			return format.substr(literalIdx + 1, endIdx - literalIdx - 1);
		};
	}

	function constructFormatterFromIdx(format, i) {
		var currentPosStr = format.substr(i);
		for (var j = 0; j < formatCodeToRegex.length; j++) {
			if (new RegExp('^' + formatCodeToRegex[j].key).test(currentPosStr)) {
				var data = formatCodeToRegex[j];
				return {
					endIdx: i + data.key.length,
					parser: data.formatter
				};
			}
		}

		return {
			endIdx: i + 1,
			parser: function () {
				return currentPosStr.charAt(0);
			}
		};
	}

	this.filter = function (date, format) {
		if (!angular.isDate(date) || isNaN(date) || !format) {
			return '';
		}

		format = $locale.DATETIME_FORMATS[format] || format;

		if ($locale.id !== localeId) {
			this.init();
		}

		if (!this.formatters[format]) {
			this.formatters[format] = createFormatter(format);
		}

		var formatters = this.formatters[format];

		return formatters.reduce(function (str, formatter) {
			return str + formatter(date);
		}, '');
	};

	this.parse = function (input, format, baseDate) {
		if (!angular.isString(input) || !format) {
			return input;
		}

		format = $locale.DATETIME_FORMATS[format] || format;
		format = format.replace(SPECIAL_CHARACTERS_REGEXP, '\\$&');

		if ($locale.id !== localeId) {
			this.init();
		}

		if (!this.parsers[format]) {
			this.parsers[format] = createParser(format, 'apply');
		}

		var parser = this.parsers[format],
			regex = parser.regex,
			map = parser.map,
			results = input.match(regex),
			tzOffset = false;
		if (results && results.length) {
			var fields, dt;
			if (angular.isDate(baseDate) && !isNaN(baseDate.getTime())) {
				fields = {
					year: baseDate.getFullYear(),
					month: baseDate.getMonth(),
					date: baseDate.getDate(),
					hours: baseDate.getHours(),
					minutes: baseDate.getMinutes(),
					seconds: baseDate.getSeconds(),
					milliseconds: baseDate.getMilliseconds()
				};
			} else {
				if (baseDate) {
					$log.warn('dateparser:', 'baseDate is not a valid date');
				}
				fields = { year: 1900, month: 0, date: 1, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 };
			}

			for (var i = 1, n = results.length; i < n; i++) {
				var mapper = map[i - 1];
				if (mapper.matcher === 'Z') {
					tzOffset = true;
				}

				if (mapper.apply) {
					mapper.apply.call(fields, results[i]);
				}
			}

			var datesetter = tzOffset ? Date.prototype.setUTCFullYear :
			  Date.prototype.setFullYear;
			var timesetter = tzOffset ? Date.prototype.setUTCHours :
			  Date.prototype.setHours;

			if (isValid(fields.year, fields.month, fields.date)) {
				if (angular.isDate(baseDate) && !isNaN(baseDate.getTime()) && !tzOffset) {
					dt = new Date(baseDate);
					datesetter.call(dt, fields.year, fields.month, fields.date);
					timesetter.call(dt, fields.hours, fields.minutes,
					  fields.seconds, fields.milliseconds);
				} else {
					dt = new Date(0);
					datesetter.call(dt, fields.year, fields.month, fields.date);
					timesetter.call(dt, fields.hours || 0, fields.minutes || 0,
					  fields.seconds || 0, fields.milliseconds || 0);
				}
			}

			return dt;
		}
	};

	// Check if date is valid for specific month (and year for February).
	// Month: 0 = Jan, 1 = Feb, etc
	function isValid(year, month, date) {
		if (date < 1) {
			return false;
		}

		if (month === 1 && date > 28) {
			return date === 29 && (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0);
		}

		if (month === 3 || month === 5 || month === 8 || month === 10) {
			return date < 31;
		}

		return true;
	}

	function toInt(str) {
		return parseInt(str, 10);
	}

	this.toTimezone = toTimezone;
	this.fromTimezone = fromTimezone;
	this.timezoneToOffset = timezoneToOffset;
	this.addDateMinutes = addDateMinutes;
	this.convertTimezoneToLocal = convertTimezoneToLocal;

	function toTimezone(date, timezone) {
		return date && timezone ? convertTimezoneToLocal(date, timezone) : date;
	}

	function fromTimezone(date, timezone) {
		return date && timezone ? convertTimezoneToLocal(date, timezone, true) : date;
	}

	//https://github.com/angular/angular.js/blob/622c42169699ec07fc6daaa19fe6d224e5d2f70e/src/Angular.js#L1207
	function timezoneToOffset(timezone, fallback) {
		timezone = timezone.replace(/:/g, '');
		var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
		return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
	}

	function addDateMinutes(date, minutes) {
		date = new Date(date.getTime());
		date.setMinutes(date.getMinutes() + minutes);
		return date;
	}

	function convertTimezoneToLocal(date, timezone, reverse) {
		reverse = reverse ? -1 : 1;
		var dateTimezoneOffset = date.getTimezoneOffset();
		var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
		return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
	}
}]);

// Avoiding use of ng-class as it creates a lot of watchers when a class is to be applied to
// at most one element.
angular.module('ui.bootstrap.isClass', [])
.directive('uibIsClass', [
         '$animate',
function ($animate) {
	//                    11111111          22222222
	var ON_REGEXP = /^\s*([\s\S]+?)\s+on\s+([\s\S]+?)\s*$/;
	//                    11111111           22222222
	var IS_REGEXP = /^\s*([\s\S]+?)\s+for\s+([\s\S]+?)\s*$/;

	var dataPerTracked = {};

	return {
		restrict: 'A',
		compile: function (tElement, tAttrs) {
			var linkedScopes = [];
			var instances = [];
			var expToData = {};
			var lastActivated = null;
			var onExpMatches = tAttrs.uibIsClass.match(ON_REGEXP);
			var onExp = onExpMatches[2];
			var expsStr = onExpMatches[1];
			var exps = expsStr.split(',');

			return linkFn;

			function linkFn(scope, element, attrs) {
				linkedScopes.push(scope);
				instances.push({
					scope: scope,
					element: element
				});

				exps.forEach(function (exp, k) {
					addForExp(exp, scope);
				});

				scope.$on('$destroy', removeScope);
			}

			function addForExp(exp, scope) {
				var matches = exp.match(IS_REGEXP);
				var clazz = scope.$eval(matches[1]);
				var compareWithExp = matches[2];
				var data = expToData[exp];
				if (!data) {
					var watchFn = function (compareWithVal) {
						var newActivated = null;
						instances.some(function (instance) {
							var thisVal = instance.scope.$eval(onExp);
							if (thisVal === compareWithVal) {
								newActivated = instance;
								return true;
							}
						});
						if (data.lastActivated !== newActivated) {
							if (data.lastActivated) {
								$animate.removeClass(data.lastActivated.element, clazz);
							}
							if (newActivated) {
								$animate.addClass(newActivated.element, clazz);
							}
							data.lastActivated = newActivated;
						}
					};
					expToData[exp] = data = {
						lastActivated: null,
						scope: scope,
						watchFn: watchFn,
						compareWithExp: compareWithExp,
						watcher: scope.$watch(compareWithExp, watchFn)
					};
				}
				data.watchFn(scope.$eval(compareWithExp));
			}

			function removeScope(e) {
				var removedScope = e.targetScope;
				var index = linkedScopes.indexOf(removedScope);
				linkedScopes.splice(index, 1);
				instances.splice(index, 1);
				if (linkedScopes.length) {
					var newWatchScope = linkedScopes[0];
					angular.forEach(expToData, function (data) {
						if (data.scope === removedScope) {
							data.watcher = newWatchScope.$watch(data.compareWithExp, data.watchFn);
							data.scope = newWatchScope;
						}
					});
				} else {
					expToData = {};
				}
			}
		}
	};
}]);
angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.isClass'])

.value('$datepickerSuppressError', false)

.value('$datepickerLiteralWarning', true)

.constant('uibDatepickerConfig', {
	datepickerMode: 'day',
	formatDay: 'dd',
	formatMonth: 'MMMM',
	formatYear: 'yyyy',
	formatDayHeader: 'EEE',
	formatDayTitle: 'MMMM yyyy',
	formatMonthTitle: 'yyyy',
	maxDate: null,
	maxMode: 'year',
	minDate: null,
	minMode: 'day',
	monthColumns: 3,
	ngModelOptions: {},
	shortcutPropagation: false,
	showWeeks: true,
	yearColumns: 5,
	yearRows: 4
})

.controller('UibDatepickerController', ['$scope', '$element', '$attrs', '$parse', '$interpolate', '$locale', '$log', 'dateFilter', 'uibDatepickerConfig', '$datepickerLiteralWarning', '$datepickerSuppressError', 'uibDateParser',
  function ($scope, $element, $attrs, $parse, $interpolate, $locale, $log, dateFilter, datepickerConfig, $datepickerLiteralWarning, $datepickerSuppressError, dateParser) {
  	var self = this,
		ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl;
		ngModelOptions = {},
		watchListeners = [];

  	$element.addClass('uib-datepicker');
  	$attrs.$set('role', 'application');

  	if (!$scope.datepickerOptions) {
  		$scope.datepickerOptions = {};
  	}

  	// Modes chain
  	this.modes = ['day', 'month', 'year'];

  	[
	  'customClass',
	  'dateDisabled',
	  'datepickerMode',
	  'formatDay',
	  'formatDayHeader',
	  'formatDayTitle',
	  'formatMonth',
	  'formatMonthTitle',
	  'formatYear',
	  'maxDate',
	  'maxMode',
	  'minDate',
	  'minMode',
	  'monthColumns',
	  'showWeeks',
	  'shortcutPropagation',
	  'startingDay',
	  'yearColumns',
	  'yearRows'
  	].forEach(function (key) {
  		switch (key) {
  			case 'customClass':
  			case 'dateDisabled':
  				$scope[key] = $scope.datepickerOptions[key] || angular.noop;
  				break;
  			case 'datepickerMode':
  				$scope.datepickerMode = angular.isDefined($scope.datepickerOptions.datepickerMode) ?
				  $scope.datepickerOptions.datepickerMode : datepickerConfig.datepickerMode;
  				break;
  			case 'formatDay':
  			case 'formatDayHeader':
  			case 'formatDayTitle':
  			case 'formatMonth':
  			case 'formatMonthTitle':
  			case 'formatYear':
  				self[key] = angular.isDefined($scope.datepickerOptions[key]) ?
				  $interpolate($scope.datepickerOptions[key])($scope.$parent) :
				  datepickerConfig[key];
  				break;
  			case 'monthColumns':
  			case 'showWeeks':
  			case 'shortcutPropagation':
  			case 'yearColumns':
  			case 'yearRows':
  				self[key] = angular.isDefined($scope.datepickerOptions[key]) ?
				  $scope.datepickerOptions[key] : datepickerConfig[key];
  				break;
  			case 'startingDay':
  				if (angular.isDefined($scope.datepickerOptions.startingDay)) {
  					self.startingDay = $scope.datepickerOptions.startingDay;
  				} else if (angular.isNumber(datepickerConfig.startingDay)) {
  					self.startingDay = datepickerConfig.startingDay;
  				} else {
  					self.startingDay = ($locale.DATETIME_FORMATS.FIRSTDAYOFWEEK + 8) % 7;
  				}

  				break;
  			case 'maxDate':
  			case 'minDate':
  				$scope.$watch('datepickerOptions.' + key, function (value) {
  					if (value) {
  						if (angular.isDate(value)) {
  							self[key] = dateParser.fromTimezone(new Date(value), ngModelOptions.timezone);
  						} else {
  							if ($datepickerLiteralWarning) {
  								$log.warn('Literal date support has been deprecated, please switch to date object usage');
  							}

  							self[key] = new Date(dateFilter(value, 'medium'));
  						}
  					} else {
  						self[key] = datepickerConfig[key] ?
						  dateParser.fromTimezone(new Date(datepickerConfig[key]), ngModelOptions.timezone) :
						  null;
  					}

  					self.refreshView();
  				});

  				break;
  			case 'maxMode':
  			case 'minMode':
  				if ($scope.datepickerOptions[key]) {
  					$scope.$watch(function () { return $scope.datepickerOptions[key]; }, function (value) {
  						self[key] = $scope[key] = angular.isDefined(value) ? value : $scope.datepickerOptions[key];
  						if (key === 'minMode' && self.modes.indexOf($scope.datepickerOptions.datepickerMode) < self.modes.indexOf(self[key]) ||
						  key === 'maxMode' && self.modes.indexOf($scope.datepickerOptions.datepickerMode) > self.modes.indexOf(self[key])) {
  							$scope.datepickerMode = self[key];
  							$scope.datepickerOptions.datepickerMode = self[key];
  						}
  					});
  				} else {
  					self[key] = $scope[key] = datepickerConfig[key] || null;
  				}

  				break;
  		}
  	});

  	$scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);

  	$scope.disabled = angular.isDefined($attrs.disabled) || false;
  	if (angular.isDefined($attrs.ngDisabled)) {
  		watchListeners.push($scope.$parent.$watch($attrs.ngDisabled, function (disabled) {
  			$scope.disabled = disabled;
  			self.refreshView();
  		}));
  	}

  	$scope.isActive = function (dateObject) {
  		if (self.compare(dateObject.date, self.activeDate) === 0) {
  			$scope.activeDateId = dateObject.uid;
  			return true;
  		}
  		return false;
  	};

  	this.init = function (ngModelCtrl_) {
  		ngModelCtrl = ngModelCtrl_;
  		ngModelOptions = ngModelCtrl_.$options ||
		  $scope.datepickerOptions.ngModelOptions ||
		  datepickerConfig.ngModelOptions;
  		if ($scope.datepickerOptions.initDate) {
  			self.activeDate = dateParser.fromTimezone($scope.datepickerOptions.initDate, ngModelOptions.timezone) || new Date();
  			$scope.$watch('datepickerOptions.initDate', function (initDate) {
  				if (initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)) {
  					self.activeDate = dateParser.fromTimezone(initDate, ngModelOptions.timezone);
  					self.refreshView();
  				}
  			});
  		} else {
  			self.activeDate = new Date();
  		}

  		var date = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : new Date();
  		this.activeDate = !isNaN(date) ?
		  dateParser.fromTimezone(date, ngModelOptions.timezone) :
		  dateParser.fromTimezone(new Date(), ngModelOptions.timezone);

  		ngModelCtrl.$render = function () {
  			self.render();
  		};
  	};

  	this.render = function () {
  		if (ngModelCtrl.$viewValue) {
  			var date = new Date(ngModelCtrl.$viewValue),
				isValid = !isNaN(date);

  			if (isValid) {
  				this.activeDate = dateParser.fromTimezone(date, ngModelOptions.timezone);
  			} else if (!$datepickerSuppressError) {
  				$log.error('Datepicker directive: "ng-model" value must be a Date object');
  			}
  		}
  		this.refreshView();
  	};

  	this.refreshView = function () {
  		if (this.element) {
  			$scope.selectedDt = null;
  			this._refreshView();
  			if ($scope.activeDt) {
  				$scope.activeDateId = $scope.activeDt.uid;
  			}

  			var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
  			date = dateParser.fromTimezone(date, ngModelOptions.timezone);
  			ngModelCtrl.$setValidity('dateDisabled', !date ||
			  this.element && !this.isDisabled(date));
  		}
  	};

  	this.createDateObject = function (date, format) {
  		var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
  		model = dateParser.fromTimezone(model, ngModelOptions.timezone);
  		var today = new Date();
  		today = dateParser.fromTimezone(today, ngModelOptions.timezone);
  		var time = this.compare(date, today);
  		var dt = {
  			date: date,
  			label: dateParser.filter(date, format),
  			selected: model && this.compare(date, model) === 0,
  			disabled: this.isDisabled(date),
  			past: time < 0,
  			current: time === 0,
  			future: time > 0,
  			customClass: this.customClass(date) || null
  		};

  		if (model && this.compare(date, model) === 0) {
  			$scope.selectedDt = dt;
  		}

  		if (self.activeDate && this.compare(dt.date, self.activeDate) === 0) {
  			$scope.activeDt = dt;
  		}

  		return dt;
  	};

  	this.isDisabled = function (date) {
  		return $scope.disabled ||
		  this.minDate && this.compare(date, this.minDate) < 0 ||
		  this.maxDate && this.compare(date, this.maxDate) > 0 ||
		  $scope.dateDisabled && $scope.dateDisabled({ date: date, mode: $scope.datepickerMode });
  	};

  	this.customClass = function (date) {
  		return $scope.customClass({ date: date, mode: $scope.datepickerMode });
  	};

  	// Split array into smaller arrays
  	this.split = function (arr, size) {
  		var arrays = [];
  		while (arr.length > 0) {
  			arrays.push(arr.splice(0, size));
  		}
  		return arrays;
  	};

  	$scope.select = function (date) {
  		if ($scope.datepickerMode === self.minMode) {
  			var dt = ngModelCtrl.$viewValue ? dateParser.fromTimezone(new Date(ngModelCtrl.$viewValue), ngModelOptions.timezone) : new Date(0, 0, 0, 0, 0, 0, 0);
  			dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
  			dt = dateParser.toTimezone(dt, ngModelOptions.timezone);
  			ngModelCtrl.$setViewValue(dt);
  			ngModelCtrl.$render();
  		} else {
  			self.activeDate = date;
  			setMode(self.modes[self.modes.indexOf($scope.datepickerMode) - 1]);

  			$scope.$emit('uib:datepicker.mode');
  		}

  		$scope.$broadcast('uib:datepicker.focus');
  	};

  	$scope.move = function (direction) {
  		var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),
			month = self.activeDate.getMonth() + direction * (self.step.months || 0);
  		self.activeDate.setFullYear(year, month, 1);
  		self.refreshView();
  	};

  	$scope.toggleMode = function (direction) {
  		direction = direction || 1;

  		if ($scope.datepickerMode === self.maxMode && direction === 1 ||
		  $scope.datepickerMode === self.minMode && direction === -1) {
  			return;
  		}

  		setMode(self.modes[self.modes.indexOf($scope.datepickerMode) + direction]);

  		$scope.$emit('uib:datepicker.mode');
  	};

  	// Key event mapper
  	$scope.keys = { 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down' };

  	var focusElement = function () {
  		self.element[0].focus();
  	};

  	// Listen for focus requests from popup directive
  	$scope.$on('uib:datepicker.focus', focusElement);

  	$scope.keydown = function (evt) {
  		var key = $scope.keys[evt.which];

  		if (!key || evt.shiftKey || evt.altKey || $scope.disabled) {
  			return;
  		}

  		evt.preventDefault();
  		if (!self.shortcutPropagation) {
  			evt.stopPropagation();
  		}

  		if (key === 'enter' || key === 'space') {
  			if (self.isDisabled(self.activeDate)) {
  				return; // do nothing
  			}
  			$scope.select(self.activeDate);
  		} else if (evt.ctrlKey && (key === 'up' || key === 'down')) {
  			$scope.toggleMode(key === 'up' ? 1 : -1);
  		} else {
  			self.handleKeyDown(key, evt);
  			self.refreshView();
  		}
  	};

  	$element.on('keydown', function (evt) {
  		$scope.$apply(function () {
  			$scope.keydown(evt);
  		});
  	});

  	$scope.$on('$destroy', function () {
  		//Clear all watch listeners on destroy
  		while (watchListeners.length) {
  			watchListeners.shift()();
  		}
  	});

  	function setMode(mode) {
  		$scope.datepickerMode = mode;
  		$scope.datepickerOptions.datepickerMode = mode;
  	}
  }])

.controller('UibDaypickerController', ['$scope', '$element', 'dateFilter', function (scope, $element, dateFilter) {
	var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

	this.step = { months: 1 };
	this.element = $element;
	function getDaysInMonth(year, month) {
		return month === 1 && year % 4 === 0 &&
		  (year % 100 !== 0 || year % 400 === 0) ? 29 : DAYS_IN_MONTH[month];
	}

	this.init = function (ctrl) {
		angular.extend(ctrl, this);
		scope.showWeeks = ctrl.showWeeks;
		ctrl.refreshView();
	};

	this.getDates = function (startDate, n) {
		var dates = new Array(n), current = new Date(startDate), i = 0, date;
		while (i < n) {
			date = new Date(current);
			dates[i++] = date;
			current.setDate(current.getDate() + 1);
		}
		return dates;
	};

	this._refreshView = function () {
		var year = this.activeDate.getFullYear(),
		  month = this.activeDate.getMonth(),
		  firstDayOfMonth = new Date(this.activeDate);

		firstDayOfMonth.setFullYear(year, month, 1);

		var difference = this.startingDay - firstDayOfMonth.getDay(),
		  numDisplayedFromPreviousMonth = difference > 0 ?
			7 - difference : -difference,
		  firstDate = new Date(firstDayOfMonth);

		if (numDisplayedFromPreviousMonth > 0) {
			firstDate.setDate(-numDisplayedFromPreviousMonth + 1);
		}

		// 42 is the number of days on a six-week calendar
		var days = this.getDates(firstDate, 42);
		for (var i = 0; i < 42; i++) {
			days[i] = angular.extend(this.createDateObject(days[i], this.formatDay), {
				secondary: days[i].getMonth() !== month,
				uid: scope.uniqueId + '-' + i
			});
		}

		scope.labels = new Array(7);
		for (var j = 0; j < 7; j++) {
			scope.labels[j] = {
				abbr: dateFilter(days[j].date, this.formatDayHeader),
				full: dateFilter(days[j].date, 'EEEE')
			};
		}

		scope.title = dateFilter(this.activeDate, this.formatDayTitle);
		scope.rows = this.split(days, 7);

		if (scope.showWeeks) {
			scope.weekNumbers = [];
			var thursdayIndex = (4 + 7 - this.startingDay) % 7,
				numWeeks = scope.rows.length;
			for (var curWeek = 0; curWeek < numWeeks; curWeek++) {
				scope.weekNumbers.push(
				  getISO8601WeekNumber(scope.rows[curWeek][thursdayIndex].date));
			}
		}
	};

	this.compare = function (date1, date2) {
		var _date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
		var _date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
		_date1.setFullYear(date1.getFullYear());
		_date2.setFullYear(date2.getFullYear());
		return _date1 - _date2;
	};

	function getISO8601WeekNumber(date) {
		var checkDate = new Date(date);
		checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday
		var time = checkDate.getTime();
		checkDate.setMonth(0); // Compare with Jan 1
		checkDate.setDate(1);
		return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
	}

	this.handleKeyDown = function (key, evt) {
		var date = this.activeDate.getDate();

		if (key === 'left') {
			date = date - 1;
		} else if (key === 'up') {
			date = date - 7;
		} else if (key === 'right') {
			date = date + 1;
		} else if (key === 'down') {
			date = date + 7;
		} else if (key === 'pageup' || key === 'pagedown') {
			var month = this.activeDate.getMonth() + (key === 'pageup' ? -1 : 1);
			this.activeDate.setMonth(month, 1);
			date = Math.min(getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth()), date);
		} else if (key === 'home') {
			date = 1;
		} else if (key === 'end') {
			date = getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth());
		}
		this.activeDate.setDate(date);
	};
}])

.controller('UibMonthpickerController', ['$scope', '$element', 'dateFilter', function (scope, $element, dateFilter) {
	this.step = { years: 1 };
	this.element = $element;

	this.init = function (ctrl) {
		angular.extend(ctrl, this);
		ctrl.refreshView();
	};

	this._refreshView = function () {
		var months = new Array(12),
			year = this.activeDate.getFullYear(),
			date;

		for (var i = 0; i < 12; i++) {
			date = new Date(this.activeDate);
			date.setFullYear(year, i, 1);
			months[i] = angular.extend(this.createDateObject(date, this.formatMonth), {
				uid: scope.uniqueId + '-' + i
			});
		}

		scope.title = dateFilter(this.activeDate, this.formatMonthTitle);
		scope.rows = this.split(months, this.monthColumns);
		scope.yearHeaderColspan = this.monthColumns > 3 ? this.monthColumns - 2 : 1;
	};

	this.compare = function (date1, date2) {
		var _date1 = new Date(date1.getFullYear(), date1.getMonth());
		var _date2 = new Date(date2.getFullYear(), date2.getMonth());
		_date1.setFullYear(date1.getFullYear());
		_date2.setFullYear(date2.getFullYear());
		return _date1 - _date2;
	};

	this.handleKeyDown = function (key, evt) {
		var date = this.activeDate.getMonth();

		if (key === 'left') {
			date = date - 1;
		} else if (key === 'up') {
			date = date - this.monthColumns;
		} else if (key === 'right') {
			date = date + 1;
		} else if (key === 'down') {
			date = date + this.monthColumns;
		} else if (key === 'pageup' || key === 'pagedown') {
			var year = this.activeDate.getFullYear() + (key === 'pageup' ? -1 : 1);
			this.activeDate.setFullYear(year);
		} else if (key === 'home') {
			date = 0;
		} else if (key === 'end') {
			date = 11;
		}
		this.activeDate.setMonth(date);
	};
}])

.controller('UibYearpickerController', ['$scope', '$element', 'dateFilter', function (scope, $element, dateFilter) {
	var columns, range;
	this.element = $element;

	function getStartingYear(year) {
		return parseInt((year - 1) / range, 10) * range + 1;
	}

	this.yearpickerInit = function () {
		columns = this.yearColumns;
		range = this.yearRows * columns;
		this.step = { years: range };
	};

	this._refreshView = function () {
		var years = new Array(range), date;

		for (var i = 0, start = getStartingYear(this.activeDate.getFullYear()) ; i < range; i++) {
			date = new Date(this.activeDate);
			date.setFullYear(start + i, 0, 1);
			years[i] = angular.extend(this.createDateObject(date, this.formatYear), {
				uid: scope.uniqueId + '-' + i
			});
		}

		scope.title = [years[0].label, years[range - 1].label].join(' - ');
		scope.rows = this.split(years, columns);
		scope.columns = columns;
	};

	this.compare = function (date1, date2) {
		return date1.getFullYear() - date2.getFullYear();
	};

	this.handleKeyDown = function (key, evt) {
		var date = this.activeDate.getFullYear();

		if (key === 'left') {
			date = date - 1;
		} else if (key === 'up') {
			date = date - columns;
		} else if (key === 'right') {
			date = date + 1;
		} else if (key === 'down') {
			date = date + columns;
		} else if (key === 'pageup' || key === 'pagedown') {
			date += (key === 'pageup' ? -1 : 1) * range;
		} else if (key === 'home') {
			date = getStartingYear(this.activeDate.getFullYear());
		} else if (key === 'end') {
			date = getStartingYear(this.activeDate.getFullYear()) + range - 1;
		}
		this.activeDate.setFullYear(date);
	};
}])

.directive('uibDatepicker', function () {
	return {
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/datepicker/datepicker.html';
		},
		scope: {
			datepickerOptions: '=?'
		},
		require: ['uibDatepicker', '^ngModel'],
		restrict: 'A',
		controller: 'UibDatepickerController',
		controllerAs: 'datepicker',
		link: function (scope, element, attrs, ctrls) {
			var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];

			datepickerCtrl.init(ngModelCtrl);
		}
	};
})

.directive('uibDaypicker', function () {
	return {
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/datepicker/day.html';
		},
		require: ['^uibDatepicker', 'uibDaypicker'],
		restrict: 'A',
		controller: 'UibDaypickerController',
		link: function (scope, element, attrs, ctrls) {
			var datepickerCtrl = ctrls[0],
			  daypickerCtrl = ctrls[1];

			daypickerCtrl.init(datepickerCtrl);
		}
	};
})

.directive('uibMonthpicker', function () {
	return {
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/datepicker/month.html';
		},
		require: ['^uibDatepicker', 'uibMonthpicker'],
		restrict: 'A',
		controller: 'UibMonthpickerController',
		link: function (scope, element, attrs, ctrls) {
			var datepickerCtrl = ctrls[0],
			  monthpickerCtrl = ctrls[1];

			monthpickerCtrl.init(datepickerCtrl);
		}
	};
})

.directive('uibYearpicker', function () {
	return {
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/datepicker/year.html';
		},
		require: ['^uibDatepicker', 'uibYearpicker'],
		restrict: 'A',
		controller: 'UibYearpickerController',
		link: function (scope, element, attrs, ctrls) {
			var ctrl = ctrls[0];
			angular.extend(ctrl, ctrls[1]);
			ctrl.yearpickerInit();

			ctrl.refreshView();
		}
	};
});

angular.module('ui.bootstrap.position', [])

/**
 * A set of utility methods for working with the DOM.
 * It is meant to be used where we need to absolute-position elements in
 * relation to another element (this is the case for tooltips, popovers,
 * typeahead suggestions etc.).
 */
  .factory('$uibPosition', ['$document', '$window', function ($document, $window) {
  	/**
     * Used by scrollbarWidth() function to cache scrollbar's width.
     * Do not access this variable directly, use scrollbarWidth() instead.
     */
  	var SCROLLBAR_WIDTH;
  	/**
     * scrollbar on body and html element in IE and Edge overlay
     * content and should be considered 0 width.
     */
  	var BODY_SCROLLBAR_WIDTH;
  	var OVERFLOW_REGEX = {
  		normal: /(auto|scroll)/,
  		hidden: /(auto|scroll|hidden)/
  	};
  	var PLACEMENT_REGEX = {
  		auto: /\s?auto?\s?/i,
  		primary: /^(top|bottom|left|right)$/,
  		secondary: /^(top|bottom|left|right|center)$/,
  		vertical: /^(top|bottom)$/
  	};
  	var BODY_REGEX = /(HTML|BODY)/;

  	return {

  		/**
		 * Provides a raw DOM element from a jQuery/jQLite element.
		 *
		 * @param {element} elem - The element to convert.
		 *
		 * @returns {element} A HTML element.
		 */
  		getRawNode: function (elem) {
  			return elem.nodeName ? elem : elem[0] || elem;
  		},

  		/**
		 * Provides a parsed number for a style property.  Strips
		 * units and casts invalid numbers to 0.
		 *
		 * @param {string} value - The style value to parse.
		 *
		 * @returns {number} A valid number.
		 */
  		parseStyle: function (value) {
  			value = parseFloat(value);
  			return isFinite(value) ? value : 0;
  		},

  		/**
		 * Provides the closest positioned ancestor.
		 *
		 * @param {element} element - The element to get the offest parent for.
		 *
		 * @returns {element} The closest positioned ancestor.
		 */
  		offsetParent: function (elem) {
  			elem = this.getRawNode(elem);

  			var offsetParent = elem.offsetParent || $document[0].documentElement;

  			function isStaticPositioned(el) {
  				return ($window.getComputedStyle(el).position || 'static') === 'static';
  			}

  			while (offsetParent && offsetParent !== $document[0].documentElement && isStaticPositioned(offsetParent)) {
  				offsetParent = offsetParent.offsetParent;
  			}

  			return offsetParent || $document[0].documentElement;
  		},

  		/**
		 * Provides the scrollbar width, concept from TWBS measureScrollbar()
		 * function in https://github.com/twbs/bootstrap/blob/master/js/modal.js
		 * In IE and Edge, scollbar on body and html element overlay and should
		 * return a width of 0.
		 *
		 * @returns {number} The width of the browser scollbar.
		 */
  		scrollbarWidth: function (isBody) {
  			if (isBody) {
  				if (angular.isUndefined(BODY_SCROLLBAR_WIDTH)) {
  					var bodyElem = $document.find('body');
  					bodyElem.addClass('uib-position-body-scrollbar-measure');
  					BODY_SCROLLBAR_WIDTH = $window.innerWidth - bodyElem[0].clientWidth;
  					BODY_SCROLLBAR_WIDTH = isFinite(BODY_SCROLLBAR_WIDTH) ? BODY_SCROLLBAR_WIDTH : 0;
  					bodyElem.removeClass('uib-position-body-scrollbar-measure');
  				}
  				return BODY_SCROLLBAR_WIDTH;
  			}

  			if (angular.isUndefined(SCROLLBAR_WIDTH)) {
  				var scrollElem = angular.element('<div class="uib-position-scrollbar-measure"></div>');
  				$document.find('body').append(scrollElem);
  				SCROLLBAR_WIDTH = scrollElem[0].offsetWidth - scrollElem[0].clientWidth;
  				SCROLLBAR_WIDTH = isFinite(SCROLLBAR_WIDTH) ? SCROLLBAR_WIDTH : 0;
  				scrollElem.remove();
  			}

  			return SCROLLBAR_WIDTH;
  		},

  		/**
		 * Provides the padding required on an element to replace the scrollbar.
		 *
		 * @returns {object} An object with the following properties:
		 *   <ul>
		 *     <li>**scrollbarWidth**: the width of the scrollbar</li>
		 *     <li>**widthOverflow**: whether the the width is overflowing</li>
		 *     <li>**right**: the amount of right padding on the element needed to replace the scrollbar</li>
		 *     <li>**rightOriginal**: the amount of right padding currently on the element</li>
		 *     <li>**heightOverflow**: whether the the height is overflowing</li>
		 *     <li>**bottom**: the amount of bottom padding on the element needed to replace the scrollbar</li>
		 *     <li>**bottomOriginal**: the amount of bottom padding currently on the element</li>
		 *   </ul>
		 */
  		scrollbarPadding: function (elem) {
  			elem = this.getRawNode(elem);

  			var elemStyle = $window.getComputedStyle(elem);
  			var paddingRight = this.parseStyle(elemStyle.paddingRight);
  			var paddingBottom = this.parseStyle(elemStyle.paddingBottom);
  			var scrollParent = this.scrollParent(elem, false, true);
  			var scrollbarWidth = this.scrollbarWidth(scrollParent, BODY_REGEX.test(scrollParent.tagName));

  			return {
  				scrollbarWidth: scrollbarWidth,
  				widthOverflow: scrollParent.scrollWidth > scrollParent.clientWidth,
  				right: paddingRight + scrollbarWidth,
  				originalRight: paddingRight,
  				heightOverflow: scrollParent.scrollHeight > scrollParent.clientHeight,
  				bottom: paddingBottom + scrollbarWidth,
  				originalBottom: paddingBottom
  			};
  		},

  		/**
		 * Checks to see if the element is scrollable.
		 *
		 * @param {element} elem - The element to check.
		 * @param {boolean=} [includeHidden=false] - Should scroll style of 'hidden' be considered,
		 *   default is false.
		 *
		 * @returns {boolean} Whether the element is scrollable.
		 */
  		isScrollable: function (elem, includeHidden) {
  			elem = this.getRawNode(elem);

  			var overflowRegex = includeHidden ? OVERFLOW_REGEX.hidden : OVERFLOW_REGEX.normal;
  			var elemStyle = $window.getComputedStyle(elem);
  			return overflowRegex.test(elemStyle.overflow + elemStyle.overflowY + elemStyle.overflowX);
  		},

  		/**
		 * Provides the closest scrollable ancestor.
		 * A port of the jQuery UI scrollParent method:
		 * https://github.com/jquery/jquery-ui/blob/master/ui/scroll-parent.js
		 *
		 * @param {element} elem - The element to find the scroll parent of.
		 * @param {boolean=} [includeHidden=false] - Should scroll style of 'hidden' be considered,
		 *   default is false.
		 * @param {boolean=} [includeSelf=false] - Should the element being passed be
		 * included in the scrollable llokup.
		 *
		 * @returns {element} A HTML element.
		 */
  		scrollParent: function (elem, includeHidden, includeSelf) {
  			elem = this.getRawNode(elem);

  			var overflowRegex = includeHidden ? OVERFLOW_REGEX.hidden : OVERFLOW_REGEX.normal;
  			var documentEl = $document[0].documentElement;
  			var elemStyle = $window.getComputedStyle(elem);
  			if (includeSelf && overflowRegex.test(elemStyle.overflow + elemStyle.overflowY + elemStyle.overflowX)) {
  				return elem;
  			}
  			var excludeStatic = elemStyle.position === 'absolute';
  			var scrollParent = elem.parentElement || documentEl;

  			if (scrollParent === documentEl || elemStyle.position === 'fixed') {
  				return documentEl;
  			}

  			while (scrollParent.parentElement && scrollParent !== documentEl) {
  				var spStyle = $window.getComputedStyle(scrollParent);
  				if (excludeStatic && spStyle.position !== 'static') {
  					excludeStatic = false;
  				}

  				if (!excludeStatic && overflowRegex.test(spStyle.overflow + spStyle.overflowY + spStyle.overflowX)) {
  					break;
  				}
  				scrollParent = scrollParent.parentElement;
  			}

  			return scrollParent;
  		},

  		/**
		 * Provides read-only equivalent of jQuery's position function:
		 * http://api.jquery.com/position/ - distance to closest positioned
		 * ancestor.  Does not account for margins by default like jQuery position.
		 *
		 * @param {element} elem - The element to caclulate the position on.
		 * @param {boolean=} [includeMargins=false] - Should margins be accounted
		 * for, default is false.
		 *
		 * @returns {object} An object with the following properties:
		 *   <ul>
		 *     <li>**width**: the width of the element</li>
		 *     <li>**height**: the height of the element</li>
		 *     <li>**top**: distance to top edge of offset parent</li>
		 *     <li>**left**: distance to left edge of offset parent</li>
		 *   </ul>
		 */
  		position: function (elem, includeMagins) {
  			elem = this.getRawNode(elem);

  			var elemOffset = this.offset(elem);
  			if (includeMagins) {
  				var elemStyle = $window.getComputedStyle(elem);
  				elemOffset.top -= this.parseStyle(elemStyle.marginTop);
  				elemOffset.left -= this.parseStyle(elemStyle.marginLeft);
  			}
  			var parent = this.offsetParent(elem);
  			var parentOffset = { top: 0, left: 0 };

  			if (parent !== $document[0].documentElement) {
  				parentOffset = this.offset(parent);
  				parentOffset.top += parent.clientTop - parent.scrollTop;
  				parentOffset.left += parent.clientLeft - parent.scrollLeft;
  			}

  			return {
  				width: Math.round(angular.isNumber(elemOffset.width) ? elemOffset.width : elem.offsetWidth),
  				height: Math.round(angular.isNumber(elemOffset.height) ? elemOffset.height : elem.offsetHeight),
  				top: Math.round(elemOffset.top - parentOffset.top),
  				left: Math.round(elemOffset.left - parentOffset.left)
  			};
  		},

  		/**
		 * Provides read-only equivalent of jQuery's offset function:
		 * http://api.jquery.com/offset/ - distance to viewport.  Does
		 * not account for borders, margins, or padding on the body
		 * element.
		 *
		 * @param {element} elem - The element to calculate the offset on.
		 *
		 * @returns {object} An object with the following properties:
		 *   <ul>
		 *     <li>**width**: the width of the element</li>
		 *     <li>**height**: the height of the element</li>
		 *     <li>**top**: distance to top edge of viewport</li>
		 *     <li>**right**: distance to bottom edge of viewport</li>
		 *   </ul>
		 */
  		offset: function (elem) {
  			elem = this.getRawNode(elem);

  			var elemBCR = elem.getBoundingClientRect();
  			return {
  				width: Math.round(angular.isNumber(elemBCR.width) ? elemBCR.width : elem.offsetWidth),
  				height: Math.round(angular.isNumber(elemBCR.height) ? elemBCR.height : elem.offsetHeight),
  				top: Math.round(elemBCR.top + ($window.pageYOffset || $document[0].documentElement.scrollTop)),
  				left: Math.round(elemBCR.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft))
  			};
  		},

  		/**
		 * Provides offset distance to the closest scrollable ancestor
		 * or viewport.  Accounts for border and scrollbar width.
		 *
		 * Right and bottom dimensions represent the distance to the
		 * respective edge of the viewport element.  If the element
		 * edge extends beyond the viewport, a negative value will be
		 * reported.
		 *
		 * @param {element} elem - The element to get the viewport offset for.
		 * @param {boolean=} [useDocument=false] - Should the viewport be the document element instead
		 * of the first scrollable element, default is false.
		 * @param {boolean=} [includePadding=true] - Should the padding on the offset parent element
		 * be accounted for, default is true.
		 *
		 * @returns {object} An object with the following properties:
		 *   <ul>
		 *     <li>**top**: distance to the top content edge of viewport element</li>
		 *     <li>**bottom**: distance to the bottom content edge of viewport element</li>
		 *     <li>**left**: distance to the left content edge of viewport element</li>
		 *     <li>**right**: distance to the right content edge of viewport element</li>
		 *   </ul>
		 */
  		viewportOffset: function (elem, useDocument, includePadding) {
  			elem = this.getRawNode(elem);
  			includePadding = includePadding !== false ? true : false;

  			var elemBCR = elem.getBoundingClientRect();
  			var offsetBCR = { top: 0, left: 0, bottom: 0, right: 0 };

  			var offsetParent = useDocument ? $document[0].documentElement : this.scrollParent(elem);
  			var offsetParentBCR = offsetParent.getBoundingClientRect();

  			offsetBCR.top = offsetParentBCR.top + offsetParent.clientTop;
  			offsetBCR.left = offsetParentBCR.left + offsetParent.clientLeft;
  			if (offsetParent === $document[0].documentElement) {
  				offsetBCR.top += $window.pageYOffset;
  				offsetBCR.left += $window.pageXOffset;
  			}
  			offsetBCR.bottom = offsetBCR.top + offsetParent.clientHeight;
  			offsetBCR.right = offsetBCR.left + offsetParent.clientWidth;

  			if (includePadding) {
  				var offsetParentStyle = $window.getComputedStyle(offsetParent);
  				offsetBCR.top += this.parseStyle(offsetParentStyle.paddingTop);
  				offsetBCR.bottom -= this.parseStyle(offsetParentStyle.paddingBottom);
  				offsetBCR.left += this.parseStyle(offsetParentStyle.paddingLeft);
  				offsetBCR.right -= this.parseStyle(offsetParentStyle.paddingRight);
  			}

  			return {
  				top: Math.round(elemBCR.top - offsetBCR.top),
  				bottom: Math.round(offsetBCR.bottom - elemBCR.bottom),
  				left: Math.round(elemBCR.left - offsetBCR.left),
  				right: Math.round(offsetBCR.right - elemBCR.right)
  			};
  		},

  		/**
		 * Provides an array of placement values parsed from a placement string.
		 * Along with the 'auto' indicator, supported placement strings are:
		 *   <ul>
		 *     <li>top: element on top, horizontally centered on host element.</li>
		 *     <li>top-left: element on top, left edge aligned with host element left edge.</li>
		 *     <li>top-right: element on top, lerightft edge aligned with host element right edge.</li>
		 *     <li>bottom: element on bottom, horizontally centered on host element.</li>
		 *     <li>bottom-left: element on bottom, left edge aligned with host element left edge.</li>
		 *     <li>bottom-right: element on bottom, right edge aligned with host element right edge.</li>
		 *     <li>left: element on left, vertically centered on host element.</li>
		 *     <li>left-top: element on left, top edge aligned with host element top edge.</li>
		 *     <li>left-bottom: element on left, bottom edge aligned with host element bottom edge.</li>
		 *     <li>right: element on right, vertically centered on host element.</li>
		 *     <li>right-top: element on right, top edge aligned with host element top edge.</li>
		 *     <li>right-bottom: element on right, bottom edge aligned with host element bottom edge.</li>
		 *   </ul>
		 * A placement string with an 'auto' indicator is expected to be
		 * space separated from the placement, i.e: 'auto bottom-left'  If
		 * the primary and secondary placement values do not match 'top,
		 * bottom, left, right' then 'top' will be the primary placement and
		 * 'center' will be the secondary placement.  If 'auto' is passed, true
		 * will be returned as the 3rd value of the array.
		 *
		 * @param {string} placement - The placement string to parse.
		 *
		 * @returns {array} An array with the following values
		 * <ul>
		 *   <li>**[0]**: The primary placement.</li>
		 *   <li>**[1]**: The secondary placement.</li>
		 *   <li>**[2]**: If auto is passed: true, else undefined.</li>
		 * </ul>
		 */
  		parsePlacement: function (placement) {
  			var autoPlace = PLACEMENT_REGEX.auto.test(placement);
  			if (autoPlace) {
  				placement = placement.replace(PLACEMENT_REGEX.auto, '');
  			}

  			placement = placement.split('-');

  			placement[0] = placement[0] || 'top';
  			if (!PLACEMENT_REGEX.primary.test(placement[0])) {
  				placement[0] = 'top';
  			}

  			placement[1] = placement[1] || 'center';
  			if (!PLACEMENT_REGEX.secondary.test(placement[1])) {
  				placement[1] = 'center';
  			}

  			if (autoPlace) {
  				placement[2] = true;
  			} else {
  				placement[2] = false;
  			}

  			return placement;
  		},

  		/**
		 * Provides coordinates for an element to be positioned relative to
		 * another element.  Passing 'auto' as part of the placement parameter
		 * will enable smart placement - where the element fits. i.e:
		 * 'auto left-top' will check to see if there is enough space to the left
		 * of the hostElem to fit the targetElem, if not place right (same for secondary
		 * top placement).  Available space is calculated using the viewportOffset
		 * function.
		 *
		 * @param {element} hostElem - The element to position against.
		 * @param {element} targetElem - The element to position.
		 * @param {string=} [placement=top] - The placement for the targetElem,
		 *   default is 'top'. 'center' is assumed as secondary placement for
		 *   'top', 'left', 'right', and 'bottom' placements.  Available placements are:
		 *   <ul>
		 *     <li>top</li>
		 *     <li>top-right</li>
		 *     <li>top-left</li>
		 *     <li>bottom</li>
		 *     <li>bottom-left</li>
		 *     <li>bottom-right</li>
		 *     <li>left</li>
		 *     <li>left-top</li>
		 *     <li>left-bottom</li>
		 *     <li>right</li>
		 *     <li>right-top</li>
		 *     <li>right-bottom</li>
		 *   </ul>
		 * @param {boolean=} [appendToBody=false] - Should the top and left values returned
		 *   be calculated from the body element, default is false.
		 *
		 * @returns {object} An object with the following properties:
		 *   <ul>
		 *     <li>**top**: Value for targetElem top.</li>
		 *     <li>**left**: Value for targetElem left.</li>
		 *     <li>**placement**: The resolved placement.</li>
		 *   </ul>
		 */
  		positionElements: function (hostElem, targetElem, placement, appendToBody) {
  			hostElem = this.getRawNode(hostElem);
  			targetElem = this.getRawNode(targetElem);

  			// need to read from prop to support tests.
  			var targetWidth = angular.isDefined(targetElem.offsetWidth) ? targetElem.offsetWidth : targetElem.prop('offsetWidth');
  			var targetHeight = angular.isDefined(targetElem.offsetHeight) ? targetElem.offsetHeight : targetElem.prop('offsetHeight');

  			placement = this.parsePlacement(placement);

  			var hostElemPos = appendToBody ? this.offset(hostElem) : this.position(hostElem);
  			var targetElemPos = { top: 0, left: 0, placement: '' };

  			if (placement[2]) {
  				var viewportOffset = this.viewportOffset(hostElem, appendToBody);

  				var targetElemStyle = $window.getComputedStyle(targetElem);
  				var adjustedSize = {
  					width: targetWidth + Math.round(Math.abs(this.parseStyle(targetElemStyle.marginLeft) + this.parseStyle(targetElemStyle.marginRight))),
  					height: targetHeight + Math.round(Math.abs(this.parseStyle(targetElemStyle.marginTop) + this.parseStyle(targetElemStyle.marginBottom)))
  				};

  				placement[0] = placement[0] === 'top' && adjustedSize.height > viewportOffset.top && adjustedSize.height <= viewportOffset.bottom ? 'bottom' :
							   placement[0] === 'bottom' && adjustedSize.height > viewportOffset.bottom && adjustedSize.height <= viewportOffset.top ? 'top' :
							   placement[0] === 'left' && adjustedSize.width > viewportOffset.left && adjustedSize.width <= viewportOffset.right ? 'right' :
							   placement[0] === 'right' && adjustedSize.width > viewportOffset.right && adjustedSize.width <= viewportOffset.left ? 'left' :
							   placement[0];

  				placement[1] = placement[1] === 'top' && adjustedSize.height - hostElemPos.height > viewportOffset.bottom && adjustedSize.height - hostElemPos.height <= viewportOffset.top ? 'bottom' :
							   placement[1] === 'bottom' && adjustedSize.height - hostElemPos.height > viewportOffset.top && adjustedSize.height - hostElemPos.height <= viewportOffset.bottom ? 'top' :
							   placement[1] === 'left' && adjustedSize.width - hostElemPos.width > viewportOffset.right && adjustedSize.width - hostElemPos.width <= viewportOffset.left ? 'right' :
							   placement[1] === 'right' && adjustedSize.width - hostElemPos.width > viewportOffset.left && adjustedSize.width - hostElemPos.width <= viewportOffset.right ? 'left' :
							   placement[1];

  				if (placement[1] === 'center') {
  					if (PLACEMENT_REGEX.vertical.test(placement[0])) {
  						var xOverflow = hostElemPos.width / 2 - targetWidth / 2;
  						if (viewportOffset.left + xOverflow < 0 && adjustedSize.width - hostElemPos.width <= viewportOffset.right) {
  							placement[1] = 'left';
  						} else if (viewportOffset.right + xOverflow < 0 && adjustedSize.width - hostElemPos.width <= viewportOffset.left) {
  							placement[1] = 'right';
  						}
  					} else {
  						var yOverflow = hostElemPos.height / 2 - adjustedSize.height / 2;
  						if (viewportOffset.top + yOverflow < 0 && adjustedSize.height - hostElemPos.height <= viewportOffset.bottom) {
  							placement[1] = 'top';
  						} else if (viewportOffset.bottom + yOverflow < 0 && adjustedSize.height - hostElemPos.height <= viewportOffset.top) {
  							placement[1] = 'bottom';
  						}
  					}
  				}
  			}

  			switch (placement[0]) {
  				case 'top':
  					targetElemPos.top = hostElemPos.top - targetHeight;
  					break;
  				case 'bottom':
  					targetElemPos.top = hostElemPos.top + hostElemPos.height;
  					break;
  				case 'left':
  					targetElemPos.left = hostElemPos.left - targetWidth;
  					break;
  				case 'right':
  					targetElemPos.left = hostElemPos.left + hostElemPos.width;
  					break;
  			}

  			switch (placement[1]) {
  				case 'top':
  					targetElemPos.top = hostElemPos.top;
  					break;
  				case 'bottom':
  					targetElemPos.top = hostElemPos.top + hostElemPos.height - targetHeight;
  					break;
  				case 'left':
  					targetElemPos.left = hostElemPos.left;
  					break;
  				case 'right':
  					targetElemPos.left = hostElemPos.left + hostElemPos.width - targetWidth;
  					break;
  				case 'center':
  					if (PLACEMENT_REGEX.vertical.test(placement[0])) {
  						targetElemPos.left = hostElemPos.left + hostElemPos.width / 2 - targetWidth / 2;
  					} else {
  						targetElemPos.top = hostElemPos.top + hostElemPos.height / 2 - targetHeight / 2;
  					}
  					break;
  			}

  			targetElemPos.top = Math.round(targetElemPos.top);
  			targetElemPos.left = Math.round(targetElemPos.left);
  			targetElemPos.placement = placement[1] === 'center' ? placement[0] : placement[0] + '-' + placement[1];

  			return targetElemPos;
  		},

  		/**
		 * Provides a way to adjust the top positioning after first
		 * render to correctly align element to top after content
		 * rendering causes resized element height
		 *
		 * @param {array} placementClasses - The array of strings of classes
		 * element should have.
		 * @param {object} containerPosition - The object with container
		 * position information
		 * @param {number} initialHeight - The initial height for the elem.
		 * @param {number} currentHeight - The current height for the elem.
		 */
  		adjustTop: function (placementClasses, containerPosition, initialHeight, currentHeight) {
  			if (placementClasses.indexOf('top') !== -1 && initialHeight !== currentHeight) {
  				return {
  					top: containerPosition.top - currentHeight + 'px'
  				};
  			}
  		},

  		/**
		 * Provides a way for positioning tooltip & dropdown
		 * arrows when using placement options beyond the standard
		 * left, right, top, or bottom.
		 *
		 * @param {element} elem - The tooltip/dropdown element.
		 * @param {string} placement - The placement for the elem.
		 */
  		positionArrow: function (elem, placement) {
  			elem = this.getRawNode(elem);

  			var innerElem = elem.querySelector('.tooltip-inner, .popover-inner');
  			if (!innerElem) {
  				return;
  			}

  			var isTooltip = angular.element(innerElem).hasClass('tooltip-inner');

  			var arrowElem = isTooltip ? elem.querySelector('.tooltip-arrow') : elem.querySelector('.arrow');
  			if (!arrowElem) {
  				return;
  			}

  			var arrowCss = {
  				top: '',
  				bottom: '',
  				left: '',
  				right: ''
  			};

  			placement = this.parsePlacement(placement);
  			if (placement[1] === 'center') {
  				// no adjustment necessary - just reset styles
  				angular.element(arrowElem).css(arrowCss);
  				return;
  			}

  			var borderProp = 'border-' + placement[0] + '-width';
  			var borderWidth = $window.getComputedStyle(arrowElem)[borderProp];

  			var borderRadiusProp = 'border-';
  			if (PLACEMENT_REGEX.vertical.test(placement[0])) {
  				borderRadiusProp += placement[0] + '-' + placement[1];
  			} else {
  				borderRadiusProp += placement[1] + '-' + placement[0];
  			}
  			borderRadiusProp += '-radius';
  			var borderRadius = $window.getComputedStyle(isTooltip ? innerElem : elem)[borderRadiusProp];

  			switch (placement[0]) {
  				case 'top':
  					arrowCss.bottom = isTooltip ? '0' : '-' + borderWidth;
  					break;
  				case 'bottom':
  					arrowCss.top = isTooltip ? '0' : '-' + borderWidth;
  					break;
  				case 'left':
  					arrowCss.right = isTooltip ? '0' : '-' + borderWidth;
  					break;
  				case 'right':
  					arrowCss.left = isTooltip ? '0' : '-' + borderWidth;
  					break;
  			}

  			arrowCss[placement[1]] = borderRadius;

  			angular.element(arrowElem).css(arrowCss);
  		}
  	};
  }]);

angular.module('ui.bootstrap.datepickerPopup', ['ui.bootstrap.datepicker', 'ui.bootstrap.position'])

.value('$datepickerPopupLiteralWarning', true)

.constant('uibDatepickerPopupConfig', {
	altInputFormats: [],
	appendToBody: false,
	clearText: 'Clear',
	closeOnDateSelection: true,
	closeText: 'Done',
	currentText: 'Today',
	datepickerPopup: 'yyyy-MM-dd',
	datepickerPopupTemplateUrl: 'uib/template/datepickerPopup/popup.html',
	datepickerTemplateUrl: 'uib/template/datepicker/datepicker.html',
	html5Types: {
		date: 'yyyy-MM-dd',
		'datetime-local': 'yyyy-MM-ddTHH:mm:ss.sss',
		'month': 'yyyy-MM'
	},
	onOpenFocus: true,
	showButtonBar: true,
	placement: 'auto bottom-left'
})

.controller('UibDatepickerPopupController', ['$scope', '$element', '$attrs', '$compile', '$log', '$parse', '$window', '$document', '$rootScope', '$uibPosition', 'dateFilter', 'uibDateParser', 'uibDatepickerPopupConfig', '$timeout', 'uibDatepickerConfig', '$datepickerPopupLiteralWarning',
function ($scope, $element, $attrs, $compile, $log, $parse, $window, $document, $rootScope, $position, dateFilter, dateParser, datepickerPopupConfig, $timeout, datepickerConfig, $datepickerPopupLiteralWarning) {
	var cache = {},
	  isHtml5DateInput = false;
	var dateFormat, closeOnDateSelection, appendToBody, onOpenFocus,
	  datepickerPopupTemplateUrl, datepickerTemplateUrl, popupEl, datepickerEl, scrollParentEl,
	  ngModel, ngModelOptions, $popup, altInputFormats, watchListeners = [];

	this.init = function (_ngModel_) {
		ngModel = _ngModel_;
		ngModelOptions = angular.isObject(_ngModel_.$options) ?
		  _ngModel_.$options :
      {
      	timezone: null
      };
		closeOnDateSelection = angular.isDefined($attrs.closeOnDateSelection) ?
		  $scope.$parent.$eval($attrs.closeOnDateSelection) :
		  datepickerPopupConfig.closeOnDateSelection;
		appendToBody = angular.isDefined($attrs.datepickerAppendToBody) ?
		  $scope.$parent.$eval($attrs.datepickerAppendToBody) :
		  datepickerPopupConfig.appendToBody;
		onOpenFocus = angular.isDefined($attrs.onOpenFocus) ?
		  $scope.$parent.$eval($attrs.onOpenFocus) : datepickerPopupConfig.onOpenFocus;
		datepickerPopupTemplateUrl = angular.isDefined($attrs.datepickerPopupTemplateUrl) ?
		  $attrs.datepickerPopupTemplateUrl :
		  datepickerPopupConfig.datepickerPopupTemplateUrl;
		datepickerTemplateUrl = angular.isDefined($attrs.datepickerTemplateUrl) ?
		  $attrs.datepickerTemplateUrl : datepickerPopupConfig.datepickerTemplateUrl;
		altInputFormats = angular.isDefined($attrs.altInputFormats) ?
		  $scope.$parent.$eval($attrs.altInputFormats) :
		  datepickerPopupConfig.altInputFormats;

		$scope.showButtonBar = angular.isDefined($attrs.showButtonBar) ?
		  $scope.$parent.$eval($attrs.showButtonBar) :
		  datepickerPopupConfig.showButtonBar;

		if (datepickerPopupConfig.html5Types[$attrs.type]) {
			dateFormat = datepickerPopupConfig.html5Types[$attrs.type];
			isHtml5DateInput = true;
		} else {
			dateFormat = $attrs.uibDatepickerPopup || datepickerPopupConfig.datepickerPopup;
			$attrs.$observe('uibDatepickerPopup', function (value, oldValue) {
				var newDateFormat = value || datepickerPopupConfig.datepickerPopup;
				// Invalidate the $modelValue to ensure that formatters re-run
				// FIXME: Refactor when PR is merged: https://github.com/angular/angular.js/pull/10764
				if (newDateFormat !== dateFormat) {
					dateFormat = newDateFormat;
					ngModel.$modelValue = null;

					if (!dateFormat) {
						throw new Error('uibDatepickerPopup must have a date format specified.');
					}
				}
			});
		}

		if (!dateFormat) {
			throw new Error('uibDatepickerPopup must have a date format specified.');
		}

		if (isHtml5DateInput && $attrs.uibDatepickerPopup) {
			throw new Error('HTML5 date input types do not support custom formats.');
		}

		// popup element used to display calendar
		popupEl = angular.element('<div uib-datepicker-popup-wrap><div uib-datepicker></div></div>');

		popupEl.attr({
			'ng-model': 'date',
			'ng-change': 'dateSelection(date)',
			'template-url': datepickerPopupTemplateUrl
		});

		// datepicker element
		datepickerEl = angular.element(popupEl.children()[0]);
		datepickerEl.attr('template-url', datepickerTemplateUrl);

		if (!$scope.datepickerOptions) {
			$scope.datepickerOptions = {};
		}

		if (isHtml5DateInput) {
			if ($attrs.type === 'month') {
				$scope.datepickerOptions.datepickerMode = 'month';
				$scope.datepickerOptions.minMode = 'month';
			}
		}

		datepickerEl.attr('datepicker-options', 'datepickerOptions');

		if (!isHtml5DateInput) {
			// Internal API to maintain the correct ng-invalid-[key] class
			ngModel.$$parserName = 'date';
			ngModel.$validators.date = validator;
			ngModel.$parsers.unshift(parseDate);
			ngModel.$formatters.push(function (value) {
				if (ngModel.$isEmpty(value)) {
					$scope.date = value;
					return value;
				}

				if (angular.isNumber(value)) {
					value = new Date(value);
				}

				$scope.date = dateParser.fromTimezone(value, ngModelOptions.timezone);

				return dateParser.filter($scope.date, dateFormat);
			});
		} else {
			ngModel.$formatters.push(function (value) {
				$scope.date = dateParser.fromTimezone(value, ngModelOptions.timezone);
				return value;
			});
		}

		// Detect changes in the view from the text box
		ngModel.$viewChangeListeners.push(function () {
			$scope.date = parseDateString(ngModel.$viewValue);
		});

		$element.on('keydown', inputKeydownBind);

		$popup = $compile(popupEl)($scope);
		// Prevent jQuery cache memory leak (template is now redundant after linking)
		popupEl.remove();

		if (appendToBody) {
			$document.find('body').append($popup);
		} else {
			$element.after($popup);
		}

		$scope.$on('$destroy', function () {
			if ($scope.isOpen === true) {
				if (!$rootScope.$$phase) {
					$scope.$apply(function () {
						$scope.isOpen = false;
					});
				}
			}

			$popup.remove();
			$element.off('keydown', inputKeydownBind);
			$document.off('click', documentClickBind);
			if (scrollParentEl) {
				scrollParentEl.off('scroll', positionPopup);
			}
			angular.element($window).off('resize', positionPopup);

			//Clear all watch listeners on destroy
			while (watchListeners.length) {
				watchListeners.shift()();
			}
		});
	};

	$scope.getText = function (key) {
		return $scope[key + 'Text'] || datepickerPopupConfig[key + 'Text'];
	};

	$scope.isDisabled = function (date) {
		if (date === 'today') {
			date = dateParser.fromTimezone(new Date(), ngModelOptions.timezone);
		}

		var dates = {};
		angular.forEach(['minDate', 'maxDate'], function (key) {
			if (!$scope.datepickerOptions[key]) {
				dates[key] = null;
			} else if (angular.isDate($scope.datepickerOptions[key])) {
				dates[key] = new Date($scope.datepickerOptions[key]);
			} else {
				if ($datepickerPopupLiteralWarning) {
					$log.warn('Literal date support has been deprecated, please switch to date object usage');
				}

				dates[key] = new Date(dateFilter($scope.datepickerOptions[key], 'medium'));
			}
		});

		return $scope.datepickerOptions &&
		  dates.minDate && $scope.compare(date, dates.minDate) < 0 ||
		  dates.maxDate && $scope.compare(date, dates.maxDate) > 0;
	};

	$scope.compare = function (date1, date2) {
		return new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
	};

	// Inner change
	$scope.dateSelection = function (dt) {
		$scope.date = dt;
		var date = $scope.date ? dateParser.filter($scope.date, dateFormat) : null; // Setting to NULL is necessary for form validators to function
		$element.val(date);
		ngModel.$setViewValue(date);

		if (closeOnDateSelection) {
			$scope.isOpen = false;
			$element[0].focus();
		}
	};

	$scope.keydown = function (evt) {
		if (evt.which === 27) {
			evt.stopPropagation();
			$scope.isOpen = false;
			$element[0].focus();
		}
	};

	$scope.select = function (date, evt) {
		evt.stopPropagation();

		if (date === 'today') {
			var today = new Date();
			if (angular.isDate($scope.date)) {
				date = new Date($scope.date);
				date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());
			} else {
				date = dateParser.fromTimezone(today, ngModelOptions.timezone);
				date.setHours(0, 0, 0, 0);
			}
		}
		$scope.dateSelection(date);
	};

	$scope.close = function (evt) {
		evt.stopPropagation();

		$scope.isOpen = false;
		$element[0].focus();
	};

	$scope.disabled = angular.isDefined($attrs.disabled) || false;
	if ($attrs.ngDisabled) {
		watchListeners.push($scope.$parent.$watch($parse($attrs.ngDisabled), function (disabled) {
			$scope.disabled = disabled;
		}));
	}

	$scope.$watch('isOpen', function (value) {
		if (value) {
			if (!$scope.disabled) {
				$timeout(function () {
					positionPopup();

					if (onOpenFocus) {
						$scope.$broadcast('uib:datepicker.focus');
					}

					$document.on('click', documentClickBind);

					var placement = $attrs.popupPlacement ? $attrs.popupPlacement : datepickerPopupConfig.placement;
					if (appendToBody || $position.parsePlacement(placement)[2]) {
						scrollParentEl = scrollParentEl || angular.element($position.scrollParent($element));
						if (scrollParentEl) {
							scrollParentEl.on('scroll', positionPopup);
						}
					} else {
						scrollParentEl = null;
					}

					angular.element($window).on('resize', positionPopup);
				}, 0, false);
			} else {
				$scope.isOpen = false;
			}
		} else {
			$document.off('click', documentClickBind);
			if (scrollParentEl) {
				scrollParentEl.off('scroll', positionPopup);
			}
			angular.element($window).off('resize', positionPopup);
		}
	});

	function cameltoDash(string) {
		return string.replace(/([A-Z])/g, function ($1) { return '-' + $1.toLowerCase(); });
	}

	function parseDateString(viewValue) {
		var date = dateParser.parse(viewValue, dateFormat, $scope.date);
		if (isNaN(date)) {
			for (var i = 0; i < altInputFormats.length; i++) {
				date = dateParser.parse(viewValue, altInputFormats[i], $scope.date);
				if (!isNaN(date)) {
					return date;
				}
			}
		}
		return date;
	}

	function parseDate(viewValue) {
		if (angular.isNumber(viewValue)) {
			// presumably timestamp to date object
			viewValue = new Date(viewValue);
		}

		if (!viewValue) {
			return null;
		}

		if (angular.isDate(viewValue) && !isNaN(viewValue)) {
			return viewValue;
		}

		if (angular.isString(viewValue)) {
			var date = parseDateString(viewValue);
			if (!isNaN(date)) {
				return dateParser.fromTimezone(date, ngModelOptions.timezone);
			}
		}

		return ngModel.$options && ngModel.$options.allowInvalid ? viewValue : undefined;
	}

	function validator(modelValue, viewValue) {
		var value = modelValue || viewValue;

		if (!$attrs.ngRequired && !value) {
			return true;
		}

		if (angular.isNumber(value)) {
			value = new Date(value);
		}

		if (!value) {
			return true;
		}

		if (angular.isDate(value) && !isNaN(value)) {
			return true;
		}

		if (angular.isString(value)) {
			return !isNaN(parseDateString(value));
		}

		return false;
	}

	function documentClickBind(event) {
		if (!$scope.isOpen && $scope.disabled) {
			return;
		}

		var popup = $popup[0];
		var dpContainsTarget = $element[0].contains(event.target);
		// The popup node may not be an element node
		// In some browsers (IE) only element nodes have the 'contains' function
		var popupContainsTarget = popup.contains !== undefined && popup.contains(event.target);
		if ($scope.isOpen && !(dpContainsTarget || popupContainsTarget)) {
			$scope.$apply(function () {
				$scope.isOpen = false;
			});
		}
	}

	function inputKeydownBind(evt) {
		if (evt.which === 27 && $scope.isOpen) {
			evt.preventDefault();
			evt.stopPropagation();
			$scope.$apply(function () {
				$scope.isOpen = false;
			});
			$element[0].focus();
		} else if (evt.which === 40 && !$scope.isOpen) {
			evt.preventDefault();
			evt.stopPropagation();
			$scope.$apply(function () {
				$scope.isOpen = true;
			});
		}
	}

	function positionPopup() {
		if ($scope.isOpen) {
			var dpElement = angular.element($popup[0].querySelector('.uib-datepicker-popup'));
			var placement = $attrs.popupPlacement ? $attrs.popupPlacement : datepickerPopupConfig.placement;
			var position = $position.positionElements($element, dpElement, placement, appendToBody);
			dpElement.css({ top: position.top + 'px', left: position.left + 'px' });
			if (dpElement.hasClass('uib-position-measure')) {
				dpElement.removeClass('uib-position-measure');
			}
		}
	}

	$scope.$on('uib:datepicker.mode', function () {
		$timeout(positionPopup, 0, false);
	});
}])

.directive('uibDatepickerPopup', function () {
	return {
		require: ['ngModel', 'uibDatepickerPopup'],
		controller: 'UibDatepickerPopupController',
		scope: {
			datepickerOptions: '=?',
			isOpen: '=?',
			currentText: '@',
			clearText: '@',
			closeText: '@'
		},
		link: function (scope, element, attrs, ctrls) {
			var ngModel = ctrls[0],
			  ctrl = ctrls[1];

			ctrl.init(ngModel);
		}
	};
})

.directive('uibDatepickerPopupWrap', function () {
	return {
		restrict: 'A',
		transclude: true,
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/datepickerPopup/popup.html';
		}
	};
});

angular.module('ui.bootstrap.debounce', [])
/**
 * A helper, internal service that debounces a function
 */
  .factory('$$debounce', ['$timeout', function ($timeout) {
  	return function (callback, debounceTime) {
  		var timeoutPromise;

  		return function () {
  			var self = this;
  			var args = Array.prototype.slice.call(arguments);
  			if (timeoutPromise) {
  				$timeout.cancel(timeoutPromise);
  			}

  			timeoutPromise = $timeout(function () {
  				callback.apply(self, args);
  			}, debounceTime);
  		};
  	};
  }]);

angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position'])

.constant('uibDropdownConfig', {
	appendToOpenClass: 'uib-dropdown-open',
	openClass: 'open'
})

.service('uibDropdownService', ['$document', '$rootScope', function ($document, $rootScope) {
	var openScope = null;

	this.open = function (dropdownScope, element) {
		if (!openScope) {
			$document.on('click', closeDropdown);
		}

		if (openScope && openScope !== dropdownScope) {
			openScope.isOpen = false;
		}

		openScope = dropdownScope;
	};

	this.close = function (dropdownScope, element) {
		if (openScope === dropdownScope) {
			openScope = null;
			$document.off('click', closeDropdown);
			$document.off('keydown', this.keybindFilter);
		}
	};

	var closeDropdown = function (evt) {
		// This method may still be called during the same mouse event that
		// unbound this event handler. So check openScope before proceeding.
		if (!openScope) { return; }

		if (evt && openScope.getAutoClose() === 'disabled') { return; }

		if (evt && evt.which === 3) { return; }

		var toggleElement = openScope.getToggleElement();
		if (evt && toggleElement && toggleElement[0].contains(evt.target)) {
			return;
		}

		var dropdownElement = openScope.getDropdownElement();
		if (evt && openScope.getAutoClose() === 'outsideClick' &&
		  dropdownElement && dropdownElement[0].contains(evt.target)) {
			return;
		}

		openScope.focusToggleElement();
		openScope.isOpen = false;

		if (!$rootScope.$$phase) {
			openScope.$apply();
		}
	};

	this.keybindFilter = function (evt) {
		var dropdownElement = openScope.getDropdownElement();
		var toggleElement = openScope.getToggleElement();
		var dropdownElementTargeted = dropdownElement && dropdownElement[0].contains(evt.target);
		var toggleElementTargeted = toggleElement && toggleElement[0].contains(evt.target);
		if (evt.which === 27) {
			evt.stopPropagation();
			openScope.focusToggleElement();
			closeDropdown();
		} else if (openScope.isKeynavEnabled() && [38, 40].indexOf(evt.which) !== -1 && openScope.isOpen && (dropdownElementTargeted || toggleElementTargeted)) {
			evt.preventDefault();
			evt.stopPropagation();
			openScope.focusDropdownEntry(evt.which);
		}
	};
}])

.controller('UibDropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', function ($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest) {
	var self = this,
	  scope = $scope.$new(), // create a child scope so we are not polluting original one
	  templateScope,
	  appendToOpenClass = dropdownConfig.appendToOpenClass,
	  openClass = dropdownConfig.openClass,
	  getIsOpen,
	  setIsOpen = angular.noop,
	  toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop,
	  appendToBody = false,
	  appendTo = null,
	  keynavEnabled = false,
	  selectedOption = null,
	  body = $document.find('body');

	$element.addClass('dropdown');

	this.init = function () {
		if ($attrs.isOpen) {
			getIsOpen = $parse($attrs.isOpen);
			setIsOpen = getIsOpen.assign;

			$scope.$watch(getIsOpen, function (value) {
				scope.isOpen = !!value;
			});
		}

		if (angular.isDefined($attrs.dropdownAppendTo)) {
			var appendToEl = $parse($attrs.dropdownAppendTo)(scope);
			if (appendToEl) {
				appendTo = angular.element(appendToEl);
			}
		}

		appendToBody = angular.isDefined($attrs.dropdownAppendToBody);
		keynavEnabled = angular.isDefined($attrs.keyboardNav);

		if (appendToBody && !appendTo) {
			appendTo = body;
		}

		if (appendTo && self.dropdownMenu) {
			appendTo.append(self.dropdownMenu);
			$element.on('$destroy', function handleDestroyEvent() {
				self.dropdownMenu.remove();
			});
		}
	};

	this.toggle = function (open) {
		scope.isOpen = arguments.length ? !!open : !scope.isOpen;
		if (angular.isFunction(setIsOpen)) {
			setIsOpen(scope, scope.isOpen);
		}

		return scope.isOpen;
	};

	// Allow other directives to watch status
	this.isOpen = function () {
		return scope.isOpen;
	};

	scope.getToggleElement = function () {
		return self.toggleElement;
	};

	scope.getAutoClose = function () {
		return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled'
	};

	scope.getElement = function () {
		return $element;
	};

	scope.isKeynavEnabled = function () {
		return keynavEnabled;
	};

	scope.focusDropdownEntry = function (keyCode) {
		var elems = self.dropdownMenu ? //If append to body is used.
		  angular.element(self.dropdownMenu).find('a') :
		  $element.find('ul').eq(0).find('a');

		switch (keyCode) {
			case 40: {
				if (!angular.isNumber(self.selectedOption)) {
					self.selectedOption = 0;
				} else {
					self.selectedOption = self.selectedOption === elems.length - 1 ?
					  self.selectedOption :
					  self.selectedOption + 1;
				}
				break;
			}
			case 38: {
				if (!angular.isNumber(self.selectedOption)) {
					self.selectedOption = elems.length - 1;
				} else {
					self.selectedOption = self.selectedOption === 0 ?
					  0 : self.selectedOption - 1;
				}
				break;
			}
		}
		elems[self.selectedOption].focus();
	};

	scope.getDropdownElement = function () {
		return self.dropdownMenu;
	};

	scope.focusToggleElement = function () {
		if (self.toggleElement) {
			self.toggleElement[0].focus();
		}
	};

	scope.$watch('isOpen', function (isOpen, wasOpen) {
		if (appendTo && self.dropdownMenu) {
			var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true),
			  css,
			  rightalign,
			  scrollbarPadding,
			  scrollbarWidth = 0;

			css = {
				top: pos.top + 'px',
				display: isOpen ? 'block' : 'none'
			};

			rightalign = self.dropdownMenu.hasClass('dropdown-menu-right');
			if (!rightalign) {
				css.left = pos.left + 'px';
				css.right = 'auto';
			} else {
				css.left = 'auto';
				scrollbarPadding = $position.scrollbarPadding(appendTo);

				if (scrollbarPadding.heightOverflow && scrollbarPadding.scrollbarWidth) {
					scrollbarWidth = scrollbarPadding.scrollbarWidth;
				}

				css.right = window.innerWidth - scrollbarWidth -
				  (pos.left + $element.prop('offsetWidth')) + 'px';
			}

			// Need to adjust our positioning to be relative to the appendTo container
			// if it's not the body element
			if (!appendToBody) {
				var appendOffset = $position.offset(appendTo);

				css.top = pos.top - appendOffset.top + 'px';

				if (!rightalign) {
					css.left = pos.left - appendOffset.left + 'px';
				} else {
					css.right = window.innerWidth -
					  (pos.left - appendOffset.left + $element.prop('offsetWidth')) + 'px';
				}
			}

			self.dropdownMenu.css(css);
		}

		var openContainer = appendTo ? appendTo : $element;
		var hasOpenClass = openContainer.hasClass(appendTo ? appendToOpenClass : openClass);

		if (hasOpenClass === !isOpen) {
			$animate[isOpen ? 'addClass' : 'removeClass'](openContainer, appendTo ? appendToOpenClass : openClass).then(function () {
				if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
					toggleInvoker($scope, { open: !!isOpen });
				}
			});
		}

		if (isOpen) {
			if (self.dropdownMenuTemplateUrl) {
				$templateRequest(self.dropdownMenuTemplateUrl).then(function (tplContent) {
					templateScope = scope.$new();
					$compile(tplContent.trim())(templateScope, function (dropdownElement) {
						var newEl = dropdownElement;
						self.dropdownMenu.replaceWith(newEl);
						self.dropdownMenu = newEl;
						$document.on('keydown', uibDropdownService.keybindFilter);
					});
				});
			} else {
				$document.on('keydown', uibDropdownService.keybindFilter);
			}

			scope.focusToggleElement();
			uibDropdownService.open(scope, $element);
		} else {
			uibDropdownService.close(scope, $element);
			if (self.dropdownMenuTemplateUrl) {
				if (templateScope) {
					templateScope.$destroy();
				}
				var newEl = angular.element('<ul class="dropdown-menu"></ul>');
				self.dropdownMenu.replaceWith(newEl);
				self.dropdownMenu = newEl;
			}

			self.selectedOption = null;
		}

		if (angular.isFunction(setIsOpen)) {
			setIsOpen($scope, isOpen);
		}
	});
}])

.directive('uibDropdown', function () {
	return {
		controller: 'UibDropdownController',
		link: function (scope, element, attrs, dropdownCtrl) {
			dropdownCtrl.init();
		}
	};
})

.directive('uibDropdownMenu', function () {
	return {
		restrict: 'A',
		require: '?^uibDropdown',
		link: function (scope, element, attrs, dropdownCtrl) {
			if (!dropdownCtrl || angular.isDefined(attrs.dropdownNested)) {
				return;
			}

			element.addClass('dropdown-menu');

			var tplUrl = attrs.templateUrl;
			if (tplUrl) {
				dropdownCtrl.dropdownMenuTemplateUrl = tplUrl;
			}

			if (!dropdownCtrl.dropdownMenu) {
				dropdownCtrl.dropdownMenu = element;
			}
		}
	};
})

.directive('uibDropdownToggle', function () {
	return {
		require: '?^uibDropdown',
		link: function (scope, element, attrs, dropdownCtrl) {
			if (!dropdownCtrl) {
				return;
			}

			element.addClass('dropdown-toggle');

			dropdownCtrl.toggleElement = element;

			var toggleDropdown = function (event) {
				event.preventDefault();

				if (!element.hasClass('disabled') && !attrs.disabled) {
					scope.$apply(function () {
						dropdownCtrl.toggle();
					});
				}
			};

			element.bind('click', toggleDropdown);

			// WAI-ARIA
			element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
			scope.$watch(dropdownCtrl.isOpen, function (isOpen) {
				element.attr('aria-expanded', !!isOpen);
			});

			scope.$on('$destroy', function () {
				element.unbind('click', toggleDropdown);
			});
		}
	};
});

angular.module('ui.bootstrap.stackedMap', [])
/**
 * A helper, internal data structure that acts as a map but also allows getting / removing
 * elements in the LIFO order
 */
  .factory('$$stackedMap', function () {
  	return {
  		createNew: function () {
  			var stack = [];

  			return {
  				add: function (key, value) {
  					stack.push({
  						key: key,
  						value: value
  					});
  				},
  				get: function (key) {
  					for (var i = 0; i < stack.length; i++) {
  						if (key === stack[i].key) {
  							return stack[i];
  						}
  					}
  				},
  				keys: function () {
  					var keys = [];
  					for (var i = 0; i < stack.length; i++) {
  						keys.push(stack[i].key);
  					}
  					return keys;
  				},
  				top: function () {
  					return stack[stack.length - 1];
  				},
  				remove: function (key) {
  					var idx = -1;
  					for (var i = 0; i < stack.length; i++) {
  						if (key === stack[i].key) {
  							idx = i;
  							break;
  						}
  					}
  					return stack.splice(idx, 1)[0];
  				},
  				removeTop: function () {
  					return stack.pop();
  				},
  				length: function () {
  					return stack.length;
  				}
  			};
  		}
  	};
  });
angular.module('ui.bootstrap.modal', ['ui.bootstrap.stackedMap', 'ui.bootstrap.position'])
/**
 * A helper, internal data structure that stores all references attached to key
 */
  .factory('$$multiMap', function () {
  	return {
  		createNew: function () {
  			var map = {};

  			return {
  				entries: function () {
  					return Object.keys(map).map(function (key) {
  						return {
  							key: key,
  							value: map[key]
  						};
  					});
  				},
  				get: function (key) {
  					return map[key];
  				},
  				hasKey: function (key) {
  					return !!map[key];
  				},
  				keys: function () {
  					return Object.keys(map);
  				},
  				put: function (key, value) {
  					if (!map[key]) {
  						map[key] = [];
  					}

  					map[key].push(value);
  				},
  				remove: function (key, value) {
  					var values = map[key];

  					if (!values) {
  						return;
  					}

  					var idx = values.indexOf(value);

  					if (idx !== -1) {
  						values.splice(idx, 1);
  					}

  					if (!values.length) {
  						delete map[key];
  					}
  				}
  			};
  		}
  	};
  })

/**
 * Pluggable resolve mechanism for the modal resolve resolution
 * Supports UI Router's $resolve service
 */
  .provider('$uibResolve', function () {
  	var resolve = this;
  	this.resolver = null;

  	this.setResolver = function (resolver) {
  		this.resolver = resolver;
  	};

  	this.$get = ['$injector', '$q', function ($injector, $q) {
  		var resolver = resolve.resolver ? $injector.get(resolve.resolver) : null;
  		return {
  			resolve: function (invocables, locals, parent, self) {
  				if (resolver) {
  					return resolver.resolve(invocables, locals, parent, self);
  				}

  				var promises = [];

  				angular.forEach(invocables, function (value) {
  					if (angular.isFunction(value) || angular.isArray(value)) {
  						promises.push($q.resolve($injector.invoke(value)));
  					} else if (angular.isString(value)) {
  						promises.push($q.resolve($injector.get(value)));
  					} else {
  						promises.push($q.resolve(value));
  					}
  				});

  				return $q.all(promises).then(function (resolves) {
  					var resolveObj = {};
  					var resolveIter = 0;
  					angular.forEach(invocables, function (value, key) {
  						resolveObj[key] = resolves[resolveIter++];
  					});

  					return resolveObj;
  				});
  			}
  		};
  	}];
  })

/**
 * A helper directive for the $modal service. It creates a backdrop element.
 */
  .directive('uibModalBackdrop', ['$animate', '$injector', '$uibModalStack',
  function ($animate, $injector, $modalStack) {
  	return {
  		restrict: 'A',
  		compile: function (tElement, tAttrs) {
  			tElement.addClass(tAttrs.backdropClass);
  			return linkFn;
  		}
  	};

  	function linkFn(scope, element, attrs) {
  		if (attrs.modalInClass) {
  			$animate.addClass(element, attrs.modalInClass);

  			scope.$on($modalStack.NOW_CLOSING_EVENT, function (e, setIsAsync) {
  				var done = setIsAsync();
  				if (scope.modalOptions.animation) {
  					$animate.removeClass(element, attrs.modalInClass).then(done);
  				} else {
  					done();
  				}
  			});
  		}
  	}
  }])

  .directive('uibModalWindow', ['$uibModalStack', '$q', '$animateCss', '$document',
  function ($modalStack, $q, $animateCss, $document) {
  	return {
  		scope: {
  			index: '@'
  		},
  		restrict: 'A',
  		transclude: true,
  		templateUrl: function (tElement, tAttrs) {
  			return tAttrs.templateUrl || 'uib/template/modal/window.html';
  		},
  		link: function (scope, element, attrs) {
  			element.addClass(attrs.windowTopClass || '');
  			scope.size = attrs.size;

  			scope.close = function (evt) {
  				var modal = $modalStack.getTop();
  				if (modal && modal.value.backdrop &&
				  modal.value.backdrop !== 'static' &&
				  evt.target === evt.currentTarget) {
  					evt.preventDefault();
  					evt.stopPropagation();
  					$modalStack.dismiss(modal.key, 'backdrop click');
  				}
  			};

  			// moved from template to fix issue #2280
  			element.on('click', scope.close);

  			// This property is only added to the scope for the purpose of detecting when this directive is rendered.
  			// We can detect that by using this property in the template associated with this directive and then use
  			// {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}.
  			scope.$isRendered = true;

  			// Deferred object that will be resolved when this modal is render.
  			var modalRenderDeferObj = $q.defer();
  			// Resolve render promise post-digest
  			scope.$$postDigest(function () {
  				modalRenderDeferObj.resolve();
  			});

  			modalRenderDeferObj.promise.then(function () {
  				var animationPromise = null;

  				if (attrs.modalInClass) {
  					animationPromise = $animateCss(element, {
  						addClass: attrs.modalInClass
  					}).start();

  					scope.$on($modalStack.NOW_CLOSING_EVENT, function (e, setIsAsync) {
  						var done = setIsAsync();
  						$animateCss(element, {
  							removeClass: attrs.modalInClass
  						}).start().then(done);
  					});
  				}


  				$q.when(animationPromise).then(function () {
  					// Notify {@link $modalStack} that modal is rendered.
  					var modal = $modalStack.getTop();
  					if (modal) {
  						$modalStack.modalRendered(modal.key);
  					}

  					/**
					 * If something within the freshly-opened modal already has focus (perhaps via a
					 * directive that causes focus). then no need to try and focus anything.
					 */
  					if (!($document[0].activeElement && element[0].contains($document[0].activeElement))) {
  						var inputWithAutofocus = element[0].querySelector('[autofocus]');
  						/**
						 * Auto-focusing of a freshly-opened modal element causes any child elements
						 * with the autofocus attribute to lose focus. This is an issue on touch
						 * based devices which will show and then hide the onscreen keyboard.
						 * Attempts to refocus the autofocus element via JavaScript will not reopen
						 * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
						 * the modal element if the modal does not contain an autofocus element.
						 */
  						if (inputWithAutofocus) {
  							inputWithAutofocus.focus();
  						} else {
  							element[0].focus();
  						}
  					}
  				});
  			});
  		}
  	};
  }])

  .directive('uibModalAnimationClass', function () {
  	return {
  		compile: function (tElement, tAttrs) {
  			if (tAttrs.modalAnimation) {
  				tElement.addClass(tAttrs.uibModalAnimationClass);
  			}
  		}
  	};
  })

  .directive('uibModalTransclude', ['$animate', function ($animate) {
  	return {
  		link: function (scope, element, attrs, controller, transclude) {
  			transclude(scope.$parent, function (clone) {
  				element.empty();
  				$animate.enter(clone, element);
  			});
  		}
  	};
  }])

  .factory('$uibModalStack', ['$animate', '$animateCss', '$document',
    '$compile', '$rootScope', '$q', '$$multiMap', '$$stackedMap', '$uibPosition',
    function ($animate, $animateCss, $document, $compile, $rootScope, $q, $$multiMap, $$stackedMap, $uibPosition) {
    	var OPENED_MODAL_CLASS = 'modal-open';

    	var backdropDomEl, backdropScope;
    	var openedWindows = $$stackedMap.createNew();
    	var openedClasses = $$multiMap.createNew();
    	var $modalStack = {
    		NOW_CLOSING_EVENT: 'modal.stack.now-closing'
    	};
    	var topModalIndex = 0;
    	var previousTopOpenedModal = null;

    	//Modal focus behavior
    	var tabbableSelector = 'a[href], area[href], input:not([disabled]):not([tabindex=\'-1\']), ' +
		  'button:not([disabled]):not([tabindex=\'-1\']),select:not([disabled]):not([tabindex=\'-1\']), textarea:not([disabled]):not([tabindex=\'-1\']), ' +
		  'iframe, object, embed, *[tabindex]:not([tabindex=\'-1\']), *[contenteditable=true]';
    	var scrollbarPadding;
    	var SNAKE_CASE_REGEXP = /[A-Z]/g;

    	// TODO: extract into common dependency with tooltip
    	function snake_case(name) {
    		var separator = '-';
    		return name.replace(SNAKE_CASE_REGEXP, function (letter, pos) {
    			return (pos ? separator : '') + letter.toLowerCase();
    		});
    	}

    	function isVisible(element) {
    		return !!(element.offsetWidth ||
			  element.offsetHeight ||
			  element.getClientRects().length);
    	}

    	function backdropIndex() {
    		var topBackdropIndex = -1;
    		var opened = openedWindows.keys();
    		for (var i = 0; i < opened.length; i++) {
    			if (openedWindows.get(opened[i]).value.backdrop) {
    				topBackdropIndex = i;
    			}
    		}

    		// If any backdrop exist, ensure that it's index is always
    		// right below the top modal
    		if (topBackdropIndex > -1 && topBackdropIndex < topModalIndex) {
    			topBackdropIndex = topModalIndex;
    		}
    		return topBackdropIndex;
    	}

    	$rootScope.$watch(backdropIndex, function (newBackdropIndex) {
    		if (backdropScope) {
    			backdropScope.index = newBackdropIndex;
    		}
    	});

    	function removeModalWindow(modalInstance, elementToReceiveFocus) {
    		var modalWindow = openedWindows.get(modalInstance).value;
    		var appendToElement = modalWindow.appendTo;

    		//clean up the stack
    		openedWindows.remove(modalInstance);
    		previousTopOpenedModal = openedWindows.top();
    		if (previousTopOpenedModal) {
    			topModalIndex = parseInt(previousTopOpenedModal.value.modalDomEl.attr('index'), 10);
    		}

    		removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function () {
    			var modalBodyClass = modalWindow.openedClass || OPENED_MODAL_CLASS;
    			openedClasses.remove(modalBodyClass, modalInstance);
    			var areAnyOpen = openedClasses.hasKey(modalBodyClass);
    			appendToElement.toggleClass(modalBodyClass, areAnyOpen);
    			if (!areAnyOpen && scrollbarPadding && scrollbarPadding.heightOverflow && scrollbarPadding.scrollbarWidth) {
    				if (scrollbarPadding.originalRight) {
    					appendToElement.css({ paddingRight: scrollbarPadding.originalRight + 'px' });
    				} else {
    					appendToElement.css({ paddingRight: '' });
    				}
    				scrollbarPadding = null;
    			}
    			toggleTopWindowClass(true);
    		}, modalWindow.closedDeferred);
    		checkRemoveBackdrop();

    		//move focus to specified element if available, or else to body
    		if (elementToReceiveFocus && elementToReceiveFocus.focus) {
    			elementToReceiveFocus.focus();
    		} else if (appendToElement.focus) {
    			appendToElement.focus();
    		}
    	}

    	// Add or remove "windowTopClass" from the top window in the stack
    	function toggleTopWindowClass(toggleSwitch) {
    		var modalWindow;

    		if (openedWindows.length() > 0) {
    			modalWindow = openedWindows.top().value;
    			modalWindow.modalDomEl.toggleClass(modalWindow.windowTopClass || '', toggleSwitch);
    		}
    	}

    	function checkRemoveBackdrop() {
    		//remove backdrop if no longer needed
    		if (backdropDomEl && backdropIndex() === -1) {
    			var backdropScopeRef = backdropScope;
    			removeAfterAnimate(backdropDomEl, backdropScope, function () {
    				backdropScopeRef = null;
    			});
    			backdropDomEl = undefined;
    			backdropScope = undefined;
    		}
    	}

    	function removeAfterAnimate(domEl, scope, done, closedDeferred) {
    		var asyncDeferred;
    		var asyncPromise = null;
    		var setIsAsync = function () {
    			if (!asyncDeferred) {
    				asyncDeferred = $q.defer();
    				asyncPromise = asyncDeferred.promise;
    			}

    			return function asyncDone() {
    				asyncDeferred.resolve();
    			};
    		};
    		scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync);

    		// Note that it's intentional that asyncPromise might be null.
    		// That's when setIsAsync has not been called during the
    		// NOW_CLOSING_EVENT broadcast.
    		return $q.when(asyncPromise).then(afterAnimating);

    		function afterAnimating() {
    			if (afterAnimating.done) {
    				return;
    			}
    			afterAnimating.done = true;

    			$animate.leave(domEl).then(function () {
    				if (done) {
    					done();
    				}

    				domEl.remove();
    				if (closedDeferred) {
    					closedDeferred.resolve();
    				}
    			});

    			scope.$destroy();
    		}
    	}

    	$document.on('keydown', keydownListener);

    	$rootScope.$on('$destroy', function () {
    		$document.off('keydown', keydownListener);
    	});

    	function keydownListener(evt) {
    		if (evt.isDefaultPrevented()) {
    			return evt;
    		}

    		var modal = openedWindows.top();
    		if (modal) {
    			switch (evt.which) {
    				case 27: {
    					if (modal.value.keyboard) {
    						evt.preventDefault();
    						$rootScope.$apply(function () {
    							$modalStack.dismiss(modal.key, 'escape key press');
    						});
    					}
    					break;
    				}
    				case 9: {
    					var list = $modalStack.loadFocusElementList(modal);
    					var focusChanged = false;
    					if (evt.shiftKey) {
    						if ($modalStack.isFocusInFirstItem(evt, list) || $modalStack.isModalFocused(evt, modal)) {
    							focusChanged = $modalStack.focusLastFocusableElement(list);
    						}
    					} else {
    						if ($modalStack.isFocusInLastItem(evt, list)) {
    							focusChanged = $modalStack.focusFirstFocusableElement(list);
    						}
    					}

    					if (focusChanged) {
    						evt.preventDefault();
    						evt.stopPropagation();
    					}

    					break;
    				}
    			}
    		}
    	}

    	$modalStack.open = function (modalInstance, modal) {
    		var modalOpener = $document[0].activeElement,
			  modalBodyClass = modal.openedClass || OPENED_MODAL_CLASS;

    		toggleTopWindowClass(false);

    		// Store the current top first, to determine what index we ought to use
    		// for the current top modal
    		previousTopOpenedModal = openedWindows.top();

    		openedWindows.add(modalInstance, {
    			deferred: modal.deferred,
    			renderDeferred: modal.renderDeferred,
    			closedDeferred: modal.closedDeferred,
    			modalScope: modal.scope,
    			backdrop: modal.backdrop,
    			keyboard: modal.keyboard,
    			openedClass: modal.openedClass,
    			windowTopClass: modal.windowTopClass,
    			animation: modal.animation,
    			appendTo: modal.appendTo
    		});

    		openedClasses.put(modalBodyClass, modalInstance);

    		var appendToElement = modal.appendTo,
				currBackdropIndex = backdropIndex();

    		if (!appendToElement.length) {
    			throw new Error('appendTo element not found. Make sure that the element passed is in DOM.');
    		}

    		if (currBackdropIndex >= 0 && !backdropDomEl) {
    			backdropScope = $rootScope.$new(true);
    			backdropScope.modalOptions = modal;
    			backdropScope.index = currBackdropIndex;
    			backdropDomEl = angular.element('<div uib-modal-backdrop="modal-backdrop"></div>');
    			backdropDomEl.attr({
    				'class': 'modal-backdrop',
    				'ng-style': '{\'z-index\': 1040 + (index && 1 || 0) + index*10}',
    				'uib-modal-animation-class': 'fade',
    				'modal-in-class': 'in'
    			});
    			if (modal.backdropClass) {
    				backdropDomEl.addClass(modal.backdropClass);
    			}

    			if (modal.animation) {
    				backdropDomEl.attr('modal-animation', 'true');
    			}
    			$compile(backdropDomEl)(backdropScope);
    			$animate.enter(backdropDomEl, appendToElement);
    			if ($uibPosition.isScrollable(appendToElement)) {
    				scrollbarPadding = $uibPosition.scrollbarPadding(appendToElement);
    				if (scrollbarPadding.heightOverflow && scrollbarPadding.scrollbarWidth) {
    					appendToElement.css({ paddingRight: scrollbarPadding.right + 'px' });
    				}
    			}
    		}

    		var content;
    		if (modal.component) {
    			content = document.createElement(snake_case(modal.component.name));
    			content = angular.element(content);
    			content.attr({
    				resolve: '$resolve',
    				'modal-instance': '$uibModalInstance',
    				close: '$close($value)',
    				dismiss: '$dismiss($value)'
    			});
    		} else {
    			content = modal.content;
    		}

    		// Set the top modal index based on the index of the previous top modal
    		topModalIndex = previousTopOpenedModal ? parseInt(previousTopOpenedModal.value.modalDomEl.attr('index'), 10) + 1 : 0;
    		var angularDomEl = angular.element('<div uib-modal-window="modal-window"></div>');
    		angularDomEl.attr({
    			'class': 'modal',
    			'template-url': modal.windowTemplateUrl,
    			'window-top-class': modal.windowTopClass,
    			'role': 'dialog',
    			'aria-labelledby': modal.ariaLabelledBy,
    			'aria-describedby': modal.ariaDescribedBy,
    			'size': modal.size,
    			'index': topModalIndex,
    			'animate': 'animate',
    			'ng-style': '{\'z-index\': 1050 + $$topModalIndex*10, display: \'block\'}',
    			'tabindex': -1,
    			'uib-modal-animation-class': 'fade',
    			'modal-in-class': 'in'
    		}).append(content);
    		if (modal.windowClass) {
    			angularDomEl.addClass(modal.windowClass);
    		}

    		if (modal.animation) {
    			angularDomEl.attr('modal-animation', 'true');
    		}

    		appendToElement.addClass(modalBodyClass);
    		if (modal.scope) {
    			// we need to explicitly add the modal index to the modal scope
    			// because it is needed by ngStyle to compute the zIndex property.
    			modal.scope.$$topModalIndex = topModalIndex;
    		}
    		$animate.enter($compile(angularDomEl)(modal.scope), appendToElement);

    		openedWindows.top().value.modalDomEl = angularDomEl;
    		openedWindows.top().value.modalOpener = modalOpener;
    	};

    	function broadcastClosing(modalWindow, resultOrReason, closing) {
    		return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented;
    	}

    	$modalStack.close = function (modalInstance, result) {
    		var modalWindow = openedWindows.get(modalInstance);
    		if (modalWindow && broadcastClosing(modalWindow, result, true)) {
    			modalWindow.value.modalScope.$$uibDestructionScheduled = true;
    			modalWindow.value.deferred.resolve(result);
    			removeModalWindow(modalInstance, modalWindow.value.modalOpener);
    			return true;
    		}
    		return !modalWindow;
    	};

    	$modalStack.dismiss = function (modalInstance, reason) {
    		var modalWindow = openedWindows.get(modalInstance);
    		if (modalWindow && broadcastClosing(modalWindow, reason, false)) {
    			modalWindow.value.modalScope.$$uibDestructionScheduled = true;
    			modalWindow.value.deferred.reject(reason);
    			removeModalWindow(modalInstance, modalWindow.value.modalOpener);
    			return true;
    		}
    		return !modalWindow;
    	};

    	$modalStack.dismissAll = function (reason) {
    		var topModal = this.getTop();
    		while (topModal && this.dismiss(topModal.key, reason)) {
    			topModal = this.getTop();
    		}
    	};

    	$modalStack.getTop = function () {
    		return openedWindows.top();
    	};

    	$modalStack.modalRendered = function (modalInstance) {
    		var modalWindow = openedWindows.get(modalInstance);
    		if (modalWindow) {
    			modalWindow.value.renderDeferred.resolve();
    		}
    	};

    	$modalStack.focusFirstFocusableElement = function (list) {
    		if (list.length > 0) {
    			list[0].focus();
    			return true;
    		}
    		return false;
    	};

    	$modalStack.focusLastFocusableElement = function (list) {
    		if (list.length > 0) {
    			list[list.length - 1].focus();
    			return true;
    		}
    		return false;
    	};

    	$modalStack.isModalFocused = function (evt, modalWindow) {
    		if (evt && modalWindow) {
    			var modalDomEl = modalWindow.value.modalDomEl;
    			if (modalDomEl && modalDomEl.length) {
    				return (evt.target || evt.srcElement) === modalDomEl[0];
    			}
    		}
    		return false;
    	};

    	$modalStack.isFocusInFirstItem = function (evt, list) {
    		if (list.length > 0) {
    			return (evt.target || evt.srcElement) === list[0];
    		}
    		return false;
    	};

    	$modalStack.isFocusInLastItem = function (evt, list) {
    		if (list.length > 0) {
    			return (evt.target || evt.srcElement) === list[list.length - 1];
    		}
    		return false;
    	};

    	$modalStack.loadFocusElementList = function (modalWindow) {
    		if (modalWindow) {
    			var modalDomE1 = modalWindow.value.modalDomEl;
    			if (modalDomE1 && modalDomE1.length) {
    				var elements = modalDomE1[0].querySelectorAll(tabbableSelector);
    				return elements ?
					  Array.prototype.filter.call(elements, function (element) {
					  	return isVisible(element);
					  }) : elements;
    			}
    		}
    	};

    	return $modalStack;
    }])

  .provider('$uibModal', function () {
  	var $modalProvider = {
  		options: {
  			animation: true,
  			backdrop: true, //can also be false or 'static'
  			keyboard: true
  		},
  		$get: ['$rootScope', '$q', '$document', '$templateRequest', '$controller', '$uibResolve', '$uibModalStack',
		  function ($rootScope, $q, $document, $templateRequest, $controller, $uibResolve, $modalStack) {
		  	var $modal = {};

		  	function getTemplatePromise(options) {
		  		return options.template ? $q.when(options.template) :
				  $templateRequest(angular.isFunction(options.templateUrl) ?
					options.templateUrl() : options.templateUrl);
		  	}

		  	var promiseChain = null;
		  	$modal.getPromiseChain = function () {
		  		return promiseChain;
		  	};

		  	$modal.open = function (modalOptions) {
		  		var modalResultDeferred = $q.defer();
		  		var modalOpenedDeferred = $q.defer();
		  		var modalClosedDeferred = $q.defer();
		  		var modalRenderDeferred = $q.defer();

		  		//prepare an instance of a modal to be injected into controllers and returned to a caller
		  		var modalInstance = {
		  			result: modalResultDeferred.promise,
		  			opened: modalOpenedDeferred.promise,
		  			closed: modalClosedDeferred.promise,
		  			rendered: modalRenderDeferred.promise,
		  			close: function (result) {
		  				return $modalStack.close(modalInstance, result);
		  			},
		  			dismiss: function (reason) {
		  				return $modalStack.dismiss(modalInstance, reason);
		  			}
		  		};

		  		//merge and clean up options
		  		modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
		  		modalOptions.resolve = modalOptions.resolve || {};
		  		modalOptions.appendTo = modalOptions.appendTo || $document.find('body').eq(0);

		  		//verify options
		  		if (!modalOptions.component && !modalOptions.template && !modalOptions.templateUrl) {
		  			throw new Error('One of component or template or templateUrl options is required.');
		  		}

		  		var templateAndResolvePromise;
		  		if (modalOptions.component) {
		  			templateAndResolvePromise = $q.when($uibResolve.resolve(modalOptions.resolve, {}, null, null));
		  		} else {
		  			templateAndResolvePromise =
					  $q.all([getTemplatePromise(modalOptions), $uibResolve.resolve(modalOptions.resolve, {}, null, null)]);
		  		}

		  		function resolveWithTemplate() {
		  			return templateAndResolvePromise;
		  		}

		  		// Wait for the resolution of the existing promise chain.
		  		// Then switch to our own combined promise dependency (regardless of how the previous modal fared).
		  		// Then add to $modalStack and resolve opened.
		  		// Finally clean up the chain variable if no subsequent modal has overwritten it.
		  		var samePromise;
		  		samePromise = promiseChain = $q.all([promiseChain])
				  .then(resolveWithTemplate, resolveWithTemplate)
				  .then(function resolveSuccess(tplAndVars) {
				  	var providedScope = modalOptions.scope || $rootScope;

				  	var modalScope = providedScope.$new();
				  	modalScope.$close = modalInstance.close;
				  	modalScope.$dismiss = modalInstance.dismiss;

				  	modalScope.$on('$destroy', function () {
				  		if (!modalScope.$$uibDestructionScheduled) {
				  			modalScope.$dismiss('$uibUnscheduledDestruction');
				  		}
				  	});

				  	var modal = {
				  		scope: modalScope,
				  		deferred: modalResultDeferred,
				  		renderDeferred: modalRenderDeferred,
				  		closedDeferred: modalClosedDeferred,
				  		animation: modalOptions.animation,
				  		backdrop: modalOptions.backdrop,
				  		keyboard: modalOptions.keyboard,
				  		backdropClass: modalOptions.backdropClass,
				  		windowTopClass: modalOptions.windowTopClass,
				  		windowClass: modalOptions.windowClass,
				  		windowTemplateUrl: modalOptions.windowTemplateUrl,
				  		ariaLabelledBy: modalOptions.ariaLabelledBy,
				  		ariaDescribedBy: modalOptions.ariaDescribedBy,
				  		size: modalOptions.size,
				  		openedClass: modalOptions.openedClass,
				  		appendTo: modalOptions.appendTo
				  	};

				  	var component = {};
				  	var ctrlInstance, ctrlInstantiate, ctrlLocals = {};

				  	if (modalOptions.component) {
				  		constructLocals(component, false, true, false);
				  		component.name = modalOptions.component;
				  		modal.component = component;
				  	} else if (modalOptions.controller) {
				  		constructLocals(ctrlLocals, true, false, true);

				  		// the third param will make the controller instantiate later,private api
				  		// @see https://github.com/angular/angular.js/blob/master/src/ng/controller.js#L126
				  		ctrlInstantiate = $controller(modalOptions.controller, ctrlLocals, true, modalOptions.controllerAs);
				  		if (modalOptions.controllerAs && modalOptions.bindToController) {
				  			ctrlInstance = ctrlInstantiate.instance;
				  			ctrlInstance.$close = modalScope.$close;
				  			ctrlInstance.$dismiss = modalScope.$dismiss;
				  			angular.extend(ctrlInstance, {
				  				$resolve: ctrlLocals.$scope.$resolve
				  			}, providedScope);
				  		}

				  		ctrlInstance = ctrlInstantiate();

				  		if (angular.isFunction(ctrlInstance.$onInit)) {
				  			ctrlInstance.$onInit();
				  		}
				  	}

				  	if (!modalOptions.component) {
				  		modal.content = tplAndVars[0];
				  	}

				  	$modalStack.open(modalInstance, modal);
				  	modalOpenedDeferred.resolve(true);

				  	function constructLocals(obj, template, instanceOnScope, injectable) {
				  		obj.$scope = modalScope;
				  		obj.$scope.$resolve = {};
				  		if (instanceOnScope) {
				  			obj.$scope.$uibModalInstance = modalInstance;
				  		} else {
				  			obj.$uibModalInstance = modalInstance;
				  		}

				  		var resolves = template ? tplAndVars[1] : tplAndVars;
				  		angular.forEach(resolves, function (value, key) {
				  			if (injectable) {
				  				obj[key] = value;
				  			}

				  			obj.$scope.$resolve[key] = value;
				  		});
				  	}
				  }, function resolveError(reason) {
				  	modalOpenedDeferred.reject(reason);
				  	modalResultDeferred.reject(reason);
				  })['finally'](function () {
				  	if (promiseChain === samePromise) {
				  		promiseChain = null;
				  	}
				  });

		  		return modalInstance;
		  	};

		  	return $modal;
		  }
  		]
  	};

  	return $modalProvider;
  });

angular.module('ui.bootstrap.paging', [])
/**
 * Helper internal service for generating common controller code between the
 * pager and pagination components
 */
.factory('uibPaging', ['$parse', function ($parse) {
	return {
		create: function (ctrl, $scope, $attrs) {
			ctrl.setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;
			ctrl.ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl
			ctrl._watchers = [];

			ctrl.init = function (ngModelCtrl, config) {
				ctrl.ngModelCtrl = ngModelCtrl;
				ctrl.config = config;

				ngModelCtrl.$render = function () {
					ctrl.render();
				};

				if ($attrs.itemsPerPage) {
					ctrl._watchers.push($scope.$parent.$watch($attrs.itemsPerPage, function (value) {
						ctrl.itemsPerPage = parseInt(value, 10);
						$scope.totalPages = ctrl.calculateTotalPages();
						ctrl.updatePage();
					}));
				} else {
					ctrl.itemsPerPage = config.itemsPerPage;
				}

				$scope.$watch('totalItems', function (newTotal, oldTotal) {
					if (angular.isDefined(newTotal) || newTotal !== oldTotal) {
						$scope.totalPages = ctrl.calculateTotalPages();
						ctrl.updatePage();
					}
				});
			};

			ctrl.calculateTotalPages = function () {
				var totalPages = ctrl.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / ctrl.itemsPerPage);
				return Math.max(totalPages || 0, 1);
			};

			ctrl.render = function () {
				$scope.page = parseInt(ctrl.ngModelCtrl.$viewValue, 10) || 1;
			};

			$scope.selectPage = function (page, evt) {
				if (evt) {
					evt.preventDefault();
				}

				var clickAllowed = !$scope.ngDisabled || !evt;
				if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) {
					if (evt && evt.target) {
						evt.target.blur();
					}
					ctrl.ngModelCtrl.$setViewValue(page);
					ctrl.ngModelCtrl.$render();
				}
			};

			$scope.getText = function (key) {
				return $scope[key + 'Text'] || ctrl.config[key + 'Text'];
			};

			$scope.noPrevious = function () {
				return $scope.page === 1;
			};

			$scope.noNext = function () {
				return $scope.page === $scope.totalPages;
			};

			ctrl.updatePage = function () {
				ctrl.setNumPages($scope.$parent, $scope.totalPages); // Readonly variable

				if ($scope.page > $scope.totalPages) {
					$scope.selectPage($scope.totalPages);
				} else {
					ctrl.ngModelCtrl.$render();
				}
			};

			$scope.$on('$destroy', function () {
				while (ctrl._watchers.length) {
					ctrl._watchers.shift()();
				}
			});
		}
	};
}]);

angular.module('ui.bootstrap.pager', ['ui.bootstrap.paging', 'ui.bootstrap.tabindex'])

.controller('UibPagerController', ['$scope', '$attrs', 'uibPaging', 'uibPagerConfig', function ($scope, $attrs, uibPaging, uibPagerConfig) {
	$scope.align = angular.isDefined($attrs.align) ? $scope.$parent.$eval($attrs.align) : uibPagerConfig.align;

	uibPaging.create(this, $scope, $attrs);
}])

.constant('uibPagerConfig', {
	itemsPerPage: 10,
	previousText: '« Previous',
	nextText: 'Next »',
	align: true
})

.directive('uibPager', ['uibPagerConfig', function (uibPagerConfig) {
	return {
		scope: {
			totalItems: '=',
			previousText: '@',
			nextText: '@',
			ngDisabled: '='
		},
		require: ['uibPager', '?ngModel'],
		restrict: 'A',
		controller: 'UibPagerController',
		controllerAs: 'pager',
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/pager/pager.html';
		},
		link: function (scope, element, attrs, ctrls) {
			element.addClass('pager');
			var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];

			if (!ngModelCtrl) {
				return; // do nothing if no ng-model
			}

			paginationCtrl.init(ngModelCtrl, uibPagerConfig);
		}
	};
}]);

angular.module('ui.bootstrap.pagination', ['ui.bootstrap.paging', 'ui.bootstrap.tabindex'])
.controller('UibPaginationController', ['$scope', '$attrs', '$parse', 'uibPaging', 'uibPaginationConfig', function ($scope, $attrs, $parse, uibPaging, uibPaginationConfig) {
	var ctrl = this;
	// Setup configuration parameters
	var maxSize = angular.isDefined($attrs.maxSize) ? $scope.$parent.$eval($attrs.maxSize) : uibPaginationConfig.maxSize,
	  rotate = angular.isDefined($attrs.rotate) ? $scope.$parent.$eval($attrs.rotate) : uibPaginationConfig.rotate,
	  forceEllipses = angular.isDefined($attrs.forceEllipses) ? $scope.$parent.$eval($attrs.forceEllipses) : uibPaginationConfig.forceEllipses,
	  boundaryLinkNumbers = angular.isDefined($attrs.boundaryLinkNumbers) ? $scope.$parent.$eval($attrs.boundaryLinkNumbers) : uibPaginationConfig.boundaryLinkNumbers,
	  pageLabel = angular.isDefined($attrs.pageLabel) ? function (idx) { return $scope.$parent.$eval($attrs.pageLabel, { $page: idx }); } : angular.identity;
	$scope.boundaryLinks = angular.isDefined($attrs.boundaryLinks) ? $scope.$parent.$eval($attrs.boundaryLinks) : uibPaginationConfig.boundaryLinks;
	$scope.directionLinks = angular.isDefined($attrs.directionLinks) ? $scope.$parent.$eval($attrs.directionLinks) : uibPaginationConfig.directionLinks;

	uibPaging.create(this, $scope, $attrs);

	if ($attrs.maxSize) {
		ctrl._watchers.push($scope.$parent.$watch($parse($attrs.maxSize), function (value) {
			maxSize = parseInt(value, 10);
			ctrl.render();
		}));
	}

	// Create page object used in template
	function makePage(number, text, isActive) {
		return {
			number: number,
			text: text,
			active: isActive
		};
	}

	function getPages(currentPage, totalPages) {
		var pages = [];

		// Default page limits
		var startPage = 1, endPage = totalPages;
		var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages;

		// recompute if maxSize
		if (isMaxSized) {
			if (rotate) {
				// Current page is displayed in the middle of the visible ones
				startPage = Math.max(currentPage - Math.floor(maxSize / 2), 1);
				endPage = startPage + maxSize - 1;

				// Adjust if limit is exceeded
				if (endPage > totalPages) {
					endPage = totalPages;
					startPage = endPage - maxSize + 1;
				}
			} else {
				// Visible pages are paginated with maxSize
				startPage = (Math.ceil(currentPage / maxSize) - 1) * maxSize + 1;

				// Adjust last page if limit is exceeded
				endPage = Math.min(startPage + maxSize - 1, totalPages);
			}
		}

		// Add page number links
		for (var number = startPage; number <= endPage; number++) {
			var page = makePage(number, pageLabel(number), number === currentPage);
			pages.push(page);
		}

		// Add links to move between page sets
		if (isMaxSized && maxSize > 0 && (!rotate || forceEllipses || boundaryLinkNumbers)) {
			if (startPage > 1) {
				if (!boundaryLinkNumbers || startPage > 3) { //need ellipsis for all options unless range is too close to beginning
					var previousPageSet = makePage(startPage - 1, '...', false);
					pages.unshift(previousPageSet);
				}
				if (boundaryLinkNumbers) {
					if (startPage === 3) { //need to replace ellipsis when the buttons would be sequential
						var secondPageLink = makePage(2, '2', false);
						pages.unshift(secondPageLink);
					}
					//add the first page
					var firstPageLink = makePage(1, '1', false);
					pages.unshift(firstPageLink);
				}
			}

			if (endPage < totalPages) {
				if (!boundaryLinkNumbers || endPage < totalPages - 2) { //need ellipsis for all options unless range is too close to end
					var nextPageSet = makePage(endPage + 1, '...', false);
					pages.push(nextPageSet);
				}
				if (boundaryLinkNumbers) {
					if (endPage === totalPages - 2) { //need to replace ellipsis when the buttons would be sequential
						var secondToLastPageLink = makePage(totalPages - 1, totalPages - 1, false);
						pages.push(secondToLastPageLink);
					}
					//add the last page
					var lastPageLink = makePage(totalPages, totalPages, false);
					pages.push(lastPageLink);
				}
			}
		}
		return pages;
	}

	var originalRender = this.render;
	this.render = function () {
		originalRender();
		if ($scope.page > 0 && $scope.page <= $scope.totalPages) {
			$scope.pages = getPages($scope.page, $scope.totalPages);
		}
	};
}])

.constant('uibPaginationConfig', {
	itemsPerPage: 10,
	boundaryLinks: false,
	boundaryLinkNumbers: false,
	directionLinks: true,
	firstText: 'First',
	previousText: 'Previous',
	nextText: 'Next',
	lastText: 'Last',
	rotate: true,
	forceEllipses: false
})

.directive('uibPagination', ['$parse', 'uibPaginationConfig', function ($parse, uibPaginationConfig) {
	return {
		scope: {
			totalItems: '=',
			firstText: '@',
			previousText: '@',
			nextText: '@',
			lastText: '@',
			ngDisabled: '='
		},
		require: ['uibPagination', '?ngModel'],
		restrict: 'A',
		controller: 'UibPaginationController',
		controllerAs: 'pagination',
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/pagination/pagination.html';
		},
		link: function (scope, element, attrs, ctrls) {
			element.addClass('pagination');
			var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];

			if (!ngModelCtrl) {
				return; // do nothing if no ng-model
			}

			paginationCtrl.init(ngModelCtrl, uibPaginationConfig);
		}
	};
}]);

/**
 * The following features are still outstanding: animation as a
 * function, placement as a function, inside, support for more triggers than
 * just mouse enter/leave, html tooltips, and selector delegation.
 */
angular.module('ui.bootstrap.tooltip', ['ui.bootstrap.position', 'ui.bootstrap.stackedMap'])

/**
 * The $tooltip service creates tooltip- and popover-like directives as well as
 * houses global options for them.
 */
.provider('$uibTooltip', function () {
	// The default options tooltip and popover.
	var defaultOptions = {
		placement: 'top',
		placementClassPrefix: '',
		animation: true,
		popupDelay: 0,
		popupCloseDelay: 0,
		useContentExp: false
	};

	// Default hide triggers for each show trigger
	var triggerMap = {
		'mouseenter': 'mouseleave',
		'click': 'click',
		'outsideClick': 'outsideClick',
		'focus': 'blur',
		'none': ''
	};

	// The options specified to the provider globally.
	var globalOptions = {};

	/**
	 * `options({})` allows global configuration of all tooltips in the
	 * application.
	 *
	 *   var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {
	 *     // place tooltips left instead of top by default
	 *     $tooltipProvider.options( { placement: 'left' } );
	 *   });
	 */
	this.options = function (value) {
		angular.extend(globalOptions, value);
	};

	/**
	 * This allows you to extend the set of trigger mappings available. E.g.:
	 *
	 *   $tooltipProvider.setTriggers( { 'openTrigger': 'closeTrigger' } );
	 */
	this.setTriggers = function setTriggers(triggers) {
		angular.extend(triggerMap, triggers);
	};

	/**
	 * This is a helper function for translating camel-case to snake_case.
	 */
	function snake_case(name) {
		var regexp = /[A-Z]/g;
		var separator = '-';
		return name.replace(regexp, function (letter, pos) {
			return (pos ? separator : '') + letter.toLowerCase();
		});
	}

	/**
	 * Returns the actual instance of the $tooltip service.
	 * TODO support multiple triggers
	 */
	this.$get = ['$window', '$compile', '$timeout', '$document', '$uibPosition', '$interpolate', '$rootScope', '$parse', '$$stackedMap', function ($window, $compile, $timeout, $document, $position, $interpolate, $rootScope, $parse, $$stackedMap) {
		var openedTooltips = $$stackedMap.createNew();
		$document.on('keyup', keypressListener);

		$rootScope.$on('$destroy', function () {
			$document.off('keyup', keypressListener);
		});

		function keypressListener(e) {
			if (e.which === 27) {
				var last = openedTooltips.top();
				if (last) {
					last.value.close();
					last = null;
				}
			}
		}

		return function $tooltip(ttType, prefix, defaultTriggerShow, options) {
			options = angular.extend({}, defaultOptions, globalOptions, options);

			/**
			 * Returns an object of show and hide triggers.
			 *
			 * If a trigger is supplied,
			 * it is used to show the tooltip; otherwise, it will use the `trigger`
			 * option passed to the `$tooltipProvider.options` method; else it will
			 * default to the trigger supplied to this directive factory.
			 *
			 * The hide trigger is based on the show trigger. If the `trigger` option
			 * was passed to the `$tooltipProvider.options` method, it will use the
			 * mapped trigger from `triggerMap` or the passed trigger if the map is
			 * undefined; otherwise, it uses the `triggerMap` value of the show
			 * trigger; else it will just use the show trigger.
			 */
			function getTriggers(trigger) {
				var show = (trigger || options.trigger || defaultTriggerShow).split(' ');
				var hide = show.map(function (trigger) {
					return triggerMap[trigger] || trigger;
				});
				return {
					show: show,
					hide: hide
				};
			}

			var directiveName = snake_case(ttType);

			var startSym = $interpolate.startSymbol();
			var endSym = $interpolate.endSymbol();
			var template =
			  '<div ' + directiveName + '-popup ' +
				'uib-title="' + startSym + 'title' + endSym + '" ' +
				(options.useContentExp ?
				  'content-exp="contentExp()" ' :
				  'content="' + startSym + 'content' + endSym + '" ') +
				'origin-scope="origScope" ' +
				'class="uib-position-measure ' + prefix + '" ' +
				'tooltip-animation-class="fade"' +
				'uib-tooltip-classes ' +
				'ng-class="{ in: isOpen }" ' +
				'>' +
			  '</div>';

			return {
				compile: function (tElem, tAttrs) {
					var tooltipLinker = $compile(template);

					return function link(scope, element, attrs, tooltipCtrl) {
						var tooltip;
						var tooltipLinkedScope;
						var transitionTimeout;
						var showTimeout;
						var hideTimeout;
						var positionTimeout;
						var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false;
						var triggers = getTriggers(undefined);
						var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']);
						var ttScope = scope.$new(true);
						var repositionScheduled = false;
						var isOpenParse = angular.isDefined(attrs[prefix + 'IsOpen']) ? $parse(attrs[prefix + 'IsOpen']) : false;
						var contentParse = options.useContentExp ? $parse(attrs[ttType]) : false;
						var observers = [];
						var lastPlacement;

						var positionTooltip = function () {
							// check if tooltip exists and is not empty
							if (!tooltip || !tooltip.html()) { return; }

							if (!positionTimeout) {
								positionTimeout = $timeout(function () {
									var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody);
									var initialHeight = angular.isDefined(tooltip.offsetHeight) ? tooltip.offsetHeight : tooltip.prop('offsetHeight');
									var elementPos = appendToBody ? $position.offset(element) : $position.position(element);
									tooltip.css({ top: ttPosition.top + 'px', left: ttPosition.left + 'px' });
									var placementClasses = ttPosition.placement.split('-');

									if (!tooltip.hasClass(placementClasses[0])) {
										tooltip.removeClass(lastPlacement.split('-')[0]);
										tooltip.addClass(placementClasses[0]);
									}

									if (!tooltip.hasClass(options.placementClassPrefix + ttPosition.placement)) {
										tooltip.removeClass(options.placementClassPrefix + lastPlacement);
										tooltip.addClass(options.placementClassPrefix + ttPosition.placement);
									}

									$timeout(function () {
										var currentHeight = angular.isDefined(tooltip.offsetHeight) ? tooltip.offsetHeight : tooltip.prop('offsetHeight');
										var adjustment = $position.adjustTop(placementClasses, elementPos, initialHeight, currentHeight);
										if (adjustment) {
											tooltip.css(adjustment);
										}
									}, 0, false);

									// first time through tt element will have the
									// uib-position-measure class or if the placement
									// has changed we need to position the arrow.
									if (tooltip.hasClass('uib-position-measure')) {
										$position.positionArrow(tooltip, ttPosition.placement);
										tooltip.removeClass('uib-position-measure');
									} else if (lastPlacement !== ttPosition.placement) {
										$position.positionArrow(tooltip, ttPosition.placement);
									}
									lastPlacement = ttPosition.placement;

									positionTimeout = null;
								}, 0, false);
							}
						};

						// Set up the correct scope to allow transclusion later
						ttScope.origScope = scope;

						// By default, the tooltip is not open.
						// TODO add ability to start tooltip opened
						ttScope.isOpen = false;

						function toggleTooltipBind() {
							if (!ttScope.isOpen) {
								showTooltipBind();
							} else {
								hideTooltipBind();
							}
						}

						// Show the tooltip with delay if specified, otherwise show it immediately
						function showTooltipBind() {
							if (hasEnableExp && !scope.$eval(attrs[prefix + 'Enable'])) {
								return;
							}

							cancelHide();
							prepareTooltip();

							if (ttScope.popupDelay) {
								// Do nothing if the tooltip was already scheduled to pop-up.
								// This happens if show is triggered multiple times before any hide is triggered.
								if (!showTimeout) {
									showTimeout = $timeout(show, ttScope.popupDelay, false);
								}
							} else {
								show();
							}
						}

						function hideTooltipBind() {
							cancelShow();

							if (ttScope.popupCloseDelay) {
								if (!hideTimeout) {
									hideTimeout = $timeout(hide, ttScope.popupCloseDelay, false);
								}
							} else {
								hide();
							}
						}

						// Show the tooltip popup element.
						function show() {
							cancelShow();
							cancelHide();

							// Don't show empty tooltips.
							if (!ttScope.content) {
								return angular.noop;
							}

							createTooltip();

							// And show the tooltip.
							ttScope.$evalAsync(function () {
								ttScope.isOpen = true;
								assignIsOpen(true);
								positionTooltip();
							});
						}

						function cancelShow() {
							if (showTimeout) {
								$timeout.cancel(showTimeout);
								showTimeout = null;
							}

							if (positionTimeout) {
								$timeout.cancel(positionTimeout);
								positionTimeout = null;
							}
						}

						// Hide the tooltip popup element.
						function hide() {
							if (!ttScope) {
								return;
							}

							// First things first: we don't show it anymore.
							ttScope.$evalAsync(function () {
								if (ttScope) {
									ttScope.isOpen = false;
									assignIsOpen(false);
									// And now we remove it from the DOM. However, if we have animation, we
									// need to wait for it to expire beforehand.
									// FIXME: this is a placeholder for a port of the transitions library.
									// The fade transition in TWBS is 150ms.
									if (ttScope.animation) {
										if (!transitionTimeout) {
											transitionTimeout = $timeout(removeTooltip, 150, false);
										}
									} else {
										removeTooltip();
									}
								}
							});
						}

						function cancelHide() {
							if (hideTimeout) {
								$timeout.cancel(hideTimeout);
								hideTimeout = null;
							}

							if (transitionTimeout) {
								$timeout.cancel(transitionTimeout);
								transitionTimeout = null;
							}
						}

						function createTooltip() {
							// There can only be one tooltip element per directive shown at once.
							if (tooltip) {
								return;
							}

							tooltipLinkedScope = ttScope.$new();
							tooltip = tooltipLinker(tooltipLinkedScope, function (tooltip) {
								if (appendToBody) {
									$document.find('body').append(tooltip);
								} else {
									element.after(tooltip);
								}
							});

							openedTooltips.add(ttScope, {
								close: hide
							});

							prepObservers();
						}

						function removeTooltip() {
							cancelShow();
							cancelHide();
							unregisterObservers();

							if (tooltip) {
								tooltip.remove();
								tooltip = null;
							}

							openedTooltips.remove(ttScope);

							if (tooltipLinkedScope) {
								tooltipLinkedScope.$destroy();
								tooltipLinkedScope = null;
							}
						}

						/**
						 * Set the initial scope values. Once
						 * the tooltip is created, the observers
						 * will be added to keep things in sync.
						 */
						function prepareTooltip() {
							ttScope.title = attrs[prefix + 'Title'];
							if (contentParse) {
								ttScope.content = contentParse(scope);
							} else {
								ttScope.content = attrs[ttType];
							}

							ttScope.popupClass = attrs[prefix + 'Class'];
							ttScope.placement = angular.isDefined(attrs[prefix + 'Placement']) ? attrs[prefix + 'Placement'] : options.placement;
							var placement = $position.parsePlacement(ttScope.placement);
							lastPlacement = placement[1] ? placement[0] + '-' + placement[1] : placement[0];

							var delay = parseInt(attrs[prefix + 'PopupDelay'], 10);
							var closeDelay = parseInt(attrs[prefix + 'PopupCloseDelay'], 10);
							ttScope.popupDelay = !isNaN(delay) ? delay : options.popupDelay;
							ttScope.popupCloseDelay = !isNaN(closeDelay) ? closeDelay : options.popupCloseDelay;
						}

						function assignIsOpen(isOpen) {
							if (isOpenParse && angular.isFunction(isOpenParse.assign)) {
								isOpenParse.assign(scope, isOpen);
							}
						}

						ttScope.contentExp = function () {
							return ttScope.content;
						};

						/**
						 * Observe the relevant attributes.
						 */
						attrs.$observe('disabled', function (val) {
							if (val) {
								cancelShow();
							}

							if (val && ttScope.isOpen) {
								hide();
							}
						});

						if (isOpenParse) {
							scope.$watch(isOpenParse, function (val) {
								if (ttScope && !val === ttScope.isOpen) {
									toggleTooltipBind();
								}
							});
						}

						function prepObservers() {
							observers.length = 0;

							if (contentParse) {
								observers.push(
								  scope.$watch(contentParse, function (val) {
								  	ttScope.content = val;
								  	if (!val && ttScope.isOpen) {
								  		hide();
								  	}
								  })
								);

								observers.push(
								  tooltipLinkedScope.$watch(function () {
								  	if (!repositionScheduled) {
								  		repositionScheduled = true;
								  		tooltipLinkedScope.$$postDigest(function () {
								  			repositionScheduled = false;
								  			if (ttScope && ttScope.isOpen) {
								  				positionTooltip();
								  			}
								  		});
								  	}
								  })
								);
							} else {
								observers.push(
								  attrs.$observe(ttType, function (val) {
								  	ttScope.content = val;
								  	if (!val && ttScope.isOpen) {
								  		hide();
								  	} else {
								  		positionTooltip();
								  	}
								  })
								);
							}

							observers.push(
							  attrs.$observe(prefix + 'Title', function (val) {
							  	ttScope.title = val;
							  	if (ttScope.isOpen) {
							  		positionTooltip();
							  	}
							  })
							);

							observers.push(
							  attrs.$observe(prefix + 'Placement', function (val) {
							  	ttScope.placement = val ? val : options.placement;
							  	if (ttScope.isOpen) {
							  		positionTooltip();
							  	}
							  })
							);
						}

						function unregisterObservers() {
							if (observers.length) {
								angular.forEach(observers, function (observer) {
									observer();
								});
								observers.length = 0;
							}
						}

						// hide tooltips/popovers for outsideClick trigger
						function bodyHideTooltipBind(e) {
							if (!ttScope || !ttScope.isOpen || !tooltip) {
								return;
							}
							// make sure the tooltip/popover link or tool tooltip/popover itself were not clicked
							if (!element[0].contains(e.target) && !tooltip[0].contains(e.target)) {
								hideTooltipBind();
							}
						}

						var unregisterTriggers = function () {
							triggers.show.forEach(function (trigger) {
								if (trigger === 'outsideClick') {
									element.off('click', toggleTooltipBind);
								} else {
									element.off(trigger, showTooltipBind);
									element.off(trigger, toggleTooltipBind);
								}
							});
							triggers.hide.forEach(function (trigger) {
								if (trigger === 'outsideClick') {
									$document.off('click', bodyHideTooltipBind);
								} else {
									element.off(trigger, hideTooltipBind);
								}
							});
						};

						function prepTriggers() {
							var showTriggers = [], hideTriggers = [];
							var val = scope.$eval(attrs[prefix + 'Trigger']);
							unregisterTriggers();

							if (angular.isObject(val)) {
								Object.keys(val).forEach(function (key) {
									showTriggers.push(key);
									hideTriggers.push(val[key]);
								});
								triggers = {
									show: showTriggers,
									hide: hideTriggers
								};
							} else {
								triggers = getTriggers(val);
							}

							if (triggers.show !== 'none') {
								triggers.show.forEach(function (trigger, idx) {
									if (trigger === 'outsideClick') {
										element.on('click', toggleTooltipBind);
										$document.on('click', bodyHideTooltipBind);
									} else if (trigger === triggers.hide[idx]) {
										element.on(trigger, toggleTooltipBind);
									} else if (trigger) {
										element.on(trigger, showTooltipBind);
										element.on(triggers.hide[idx], hideTooltipBind);
									}

									element.on('keypress', function (e) {
										if (e.which === 27) {
											hideTooltipBind();
										}
									});
								});
							}
						}

						prepTriggers();

						var animation = scope.$eval(attrs[prefix + 'Animation']);
						ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation;

						var appendToBodyVal;
						var appendKey = prefix + 'AppendToBody';
						if (appendKey in attrs && attrs[appendKey] === undefined) {
							appendToBodyVal = true;
						} else {
							appendToBodyVal = scope.$eval(attrs[appendKey]);
						}

						appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody;

						// Make sure tooltip is destroyed and removed.
						scope.$on('$destroy', function onDestroyTooltip() {
							unregisterTriggers();
							removeTooltip();
							ttScope = null;
						});
					};
				}
			};
		};
	}];
})

// This is mostly ngInclude code but with a custom scope
.directive('uibTooltipTemplateTransclude', [
         '$animate', '$sce', '$compile', '$templateRequest',
function ($animate, $sce, $compile, $templateRequest) {
	return {
		link: function (scope, elem, attrs) {
			var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope);

			var changeCounter = 0,
			  currentScope,
			  previousElement,
			  currentElement;

			var cleanupLastIncludeContent = function () {
				if (previousElement) {
					previousElement.remove();
					previousElement = null;
				}

				if (currentScope) {
					currentScope.$destroy();
					currentScope = null;
				}

				if (currentElement) {
					$animate.leave(currentElement).then(function () {
						previousElement = null;
					});
					previousElement = currentElement;
					currentElement = null;
				}
			};

			scope.$watch($sce.parseAsResourceUrl(attrs.uibTooltipTemplateTransclude), function (src) {
				var thisChangeId = ++changeCounter;

				if (src) {
					//set the 2nd param to true to ignore the template request error so that the inner
					//contents and scope can be cleaned up.
					$templateRequest(src, true).then(function (response) {
						if (thisChangeId !== changeCounter) { return; }
						var newScope = origScope.$new();
						var template = response;

						var clone = $compile(template)(newScope, function (clone) {
							cleanupLastIncludeContent();
							$animate.enter(clone, elem);
						});

						currentScope = newScope;
						currentElement = clone;

						currentScope.$emit('$includeContentLoaded', src);
					}, function () {
						if (thisChangeId === changeCounter) {
							cleanupLastIncludeContent();
							scope.$emit('$includeContentError', src);
						}
					});
					scope.$emit('$includeContentRequested', src);
				} else {
					cleanupLastIncludeContent();
				}
			});

			scope.$on('$destroy', cleanupLastIncludeContent);
		}
	};
}])

/**
 * Note that it's intentional that these classes are *not* applied through $animate.
 * They must not be animated as they're expected to be present on the tooltip on
 * initialization.
 */
.directive('uibTooltipClasses', ['$uibPosition', function ($uibPosition) {
	return {
		restrict: 'A',
		link: function (scope, element, attrs) {
			// need to set the primary position so the
			// arrow has space during position measure.
			// tooltip.positionTooltip()
			if (scope.placement) {
				// // There are no top-left etc... classes
				// // in TWBS, so we need the primary position.
				var position = $uibPosition.parsePlacement(scope.placement);
				element.addClass(position[0]);
			}

			if (scope.popupClass) {
				element.addClass(scope.popupClass);
			}

			if (scope.animation) {
				element.addClass(attrs.tooltipAnimationClass);
			}
		}
	};
}])

.directive('uibTooltipPopup', function () {
	return {
		restrict: 'A',
		scope: { content: '@' },
		templateUrl: 'uib/template/tooltip/tooltip-popup.html'
	};
})

.directive('uibTooltip', ['$uibTooltip', function ($uibTooltip) {
	return $uibTooltip('uibTooltip', 'tooltip', 'mouseenter');
}])

.directive('uibTooltipTemplatePopup', function () {
	return {
		restrict: 'A',
		scope: { contentExp: '&', originScope: '&' },
		templateUrl: 'uib/template/tooltip/tooltip-template-popup.html'
	};
})

.directive('uibTooltipTemplate', ['$uibTooltip', function ($uibTooltip) {
	return $uibTooltip('uibTooltipTemplate', 'tooltip', 'mouseenter', {
		useContentExp: true
	});
}])

.directive('uibTooltipHtmlPopup', function () {
	return {
		restrict: 'A',
		scope: { contentExp: '&' },
		templateUrl: 'uib/template/tooltip/tooltip-html-popup.html'
	};
})

.directive('uibTooltipHtml', ['$uibTooltip', function ($uibTooltip) {
	return $uibTooltip('uibTooltipHtml', 'tooltip', 'mouseenter', {
		useContentExp: true
	});
}]);

/**
 * The following features are still outstanding: popup delay, animation as a
 * function, placement as a function, inside, support for more triggers than
 * just mouse enter/leave, and selector delegatation.
 */
angular.module('ui.bootstrap.popover', ['ui.bootstrap.tooltip'])

.directive('uibPopoverTemplatePopup', function () {
	return {
		restrict: 'A',
		scope: { uibTitle: '@', contentExp: '&', originScope: '&' },
		templateUrl: 'uib/template/popover/popover-template.html'
	};
})

.directive('uibPopoverTemplate', ['$uibTooltip', function ($uibTooltip) {
	return $uibTooltip('uibPopoverTemplate', 'popover', 'click', {
		useContentExp: true
	});
}])

.directive('uibPopoverHtmlPopup', function () {
	return {
		restrict: 'A',
		scope: { contentExp: '&', uibTitle: '@' },
		templateUrl: 'uib/template/popover/popover-html.html'
	};
})

.directive('uibPopoverHtml', ['$uibTooltip', function ($uibTooltip) {
	return $uibTooltip('uibPopoverHtml', 'popover', 'click', {
		useContentExp: true
	});
}])

.directive('uibPopoverPopup', function () {
	return {
		restrict: 'A',
		scope: { uibTitle: '@', content: '@' },
		templateUrl: 'uib/template/popover/popover.html'
	};
})

.directive('uibPopover', ['$uibTooltip', function ($uibTooltip) {
	return $uibTooltip('uibPopover', 'popover', 'click');
}]);

angular.module('ui.bootstrap.progressbar', [])

.constant('uibProgressConfig', {
	animate: true,
	max: 100
})

.controller('UibProgressController', ['$scope', '$attrs', 'uibProgressConfig', function ($scope, $attrs, progressConfig) {
	var self = this,
		animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;

	this.bars = [];
	$scope.max = getMaxOrDefault();

	this.addBar = function (bar, element, attrs) {
		if (!animate) {
			element.css({ 'transition': 'none' });
		}

		this.bars.push(bar);

		bar.max = getMaxOrDefault();
		bar.title = attrs && angular.isDefined(attrs.title) ? attrs.title : 'progressbar';

		bar.$watch('value', function (value) {
			bar.recalculatePercentage();
		});

		bar.recalculatePercentage = function () {
			var totalPercentage = self.bars.reduce(function (total, bar) {
				bar.percent = +(100 * bar.value / bar.max).toFixed(2);
				return total + bar.percent;
			}, 0);

			if (totalPercentage > 100) {
				bar.percent -= totalPercentage - 100;
			}
		};

		bar.$on('$destroy', function () {
			element = null;
			self.removeBar(bar);
		});
	};

	this.removeBar = function (bar) {
		this.bars.splice(this.bars.indexOf(bar), 1);
		this.bars.forEach(function (bar) {
			bar.recalculatePercentage();
		});
	};

	//$attrs.$observe('maxParam', function(maxParam) {
	$scope.$watch('maxParam', function (maxParam) {
		self.bars.forEach(function (bar) {
			bar.max = getMaxOrDefault();
			bar.recalculatePercentage();
		});
	});

	function getMaxOrDefault() {
		return angular.isDefined($scope.maxParam) ? $scope.maxParam : progressConfig.max;
	}
}])

.directive('uibProgress', function () {
	return {
		replace: true,
		transclude: true,
		controller: 'UibProgressController',
		require: 'uibProgress',
		scope: {
			maxParam: '=?max'
		},
		templateUrl: 'uib/template/progressbar/progress.html'
	};
})

.directive('uibBar', function () {
	return {
		replace: true,
		transclude: true,
		require: '^uibProgress',
		scope: {
			value: '=',
			type: '@'
		},
		templateUrl: 'uib/template/progressbar/bar.html',
		link: function (scope, element, attrs, progressCtrl) {
			progressCtrl.addBar(scope, element, attrs);
		}
	};
})

.directive('uibProgressbar', function () {
	return {
		replace: true,
		transclude: true,
		controller: 'UibProgressController',
		scope: {
			value: '=',
			maxParam: '=?max',
			type: '@'
		},
		templateUrl: 'uib/template/progressbar/progressbar.html',
		link: function (scope, element, attrs, progressCtrl) {
			progressCtrl.addBar(scope, angular.element(element.children()[0]), { title: attrs.title });
		}
	};
});

angular.module('ui.bootstrap.rating', [])

.constant('uibRatingConfig', {
	max: 5,
	stateOn: null,
	stateOff: null,
	enableReset: true,
	titles: ['one', 'two', 'three', 'four', 'five']
})

.controller('UibRatingController', ['$scope', '$attrs', 'uibRatingConfig', function ($scope, $attrs, ratingConfig) {
	var ngModelCtrl = { $setViewValue: angular.noop },
	  self = this;

	this.init = function (ngModelCtrl_) {
		ngModelCtrl = ngModelCtrl_;
		ngModelCtrl.$render = this.render;

		ngModelCtrl.$formatters.push(function (value) {
			if (angular.isNumber(value) && value << 0 !== value) {
				value = Math.round(value);
			}

			return value;
		});

		this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;
		this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;
		this.enableReset = angular.isDefined($attrs.enableReset) ?
		  $scope.$parent.$eval($attrs.enableReset) : ratingConfig.enableReset;
		var tmpTitles = angular.isDefined($attrs.titles) ? $scope.$parent.$eval($attrs.titles) : ratingConfig.titles;
		this.titles = angular.isArray(tmpTitles) && tmpTitles.length > 0 ?
			tmpTitles : ratingConfig.titles;

		var ratingStates = angular.isDefined($attrs.ratingStates) ?
		  $scope.$parent.$eval($attrs.ratingStates) :
		  new Array(angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max);
		$scope.range = this.buildTemplateObjects(ratingStates);
	};

	this.buildTemplateObjects = function (states) {
		for (var i = 0, n = states.length; i < n; i++) {
			states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff, title: this.getTitle(i) }, states[i]);
		}
		return states;
	};

	this.getTitle = function (index) {
		if (index >= this.titles.length) {
			return index + 1;
		}

		return this.titles[index];
	};

	$scope.rate = function (value) {
		if (!$scope.readonly && value >= 0 && value <= $scope.range.length) {
			var newViewValue = self.enableReset && ngModelCtrl.$viewValue === value ? 0 : value;
			ngModelCtrl.$setViewValue(newViewValue);
			ngModelCtrl.$render();
		}
	};

	$scope.enter = function (value) {
		if (!$scope.readonly) {
			$scope.value = value;
		}
		$scope.onHover({ value: value });
	};

	$scope.reset = function () {
		$scope.value = ngModelCtrl.$viewValue;
		$scope.onLeave();
	};

	$scope.onKeydown = function (evt) {
		if (/(37|38|39|40)/.test(evt.which)) {
			evt.preventDefault();
			evt.stopPropagation();
			$scope.rate($scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1));
		}
	};

	this.render = function () {
		$scope.value = ngModelCtrl.$viewValue;
		$scope.title = self.getTitle($scope.value - 1);
	};
}])

.directive('uibRating', function () {
	return {
		require: ['uibRating', 'ngModel'],
		restrict: 'A',
		scope: {
			readonly: '=?readOnly',
			onHover: '&',
			onLeave: '&'
		},
		controller: 'UibRatingController',
		templateUrl: 'uib/template/rating/rating.html',
		link: function (scope, element, attrs, ctrls) {
			var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1];
			ratingCtrl.init(ngModelCtrl);
		}
	};
});

angular.module('ui.bootstrap.tabs', [])

.controller('UibTabsetController', ['$scope', function ($scope) {
	var ctrl = this,
	  oldIndex;
	ctrl.tabs = [];

	ctrl.select = function (index, evt) {
		if (!destroyed) {
			var previousIndex = findTabIndex(oldIndex);
			var previousSelected = ctrl.tabs[previousIndex];
			if (previousSelected) {
				previousSelected.tab.onDeselect({
					$event: evt,
					$selectedIndex: index
				});
				if (evt && evt.isDefaultPrevented()) {
					return;
				}
				previousSelected.tab.active = false;
			}

			var selected = ctrl.tabs[index];
			if (selected) {
				selected.tab.onSelect({
					$event: evt
				});
				selected.tab.active = true;
				ctrl.active = selected.index;
				oldIndex = selected.index;
			} else if (!selected && angular.isDefined(oldIndex)) {
				ctrl.active = null;
				oldIndex = null;
			}
		}
	};

	ctrl.addTab = function addTab(tab) {
		ctrl.tabs.push({
			tab: tab,
			index: tab.index
		});
		ctrl.tabs.sort(function (t1, t2) {
			if (t1.index > t2.index) {
				return 1;
			}

			if (t1.index < t2.index) {
				return -1;
			}

			return 0;
		});

		if (tab.index === ctrl.active || !angular.isDefined(ctrl.active) && ctrl.tabs.length === 1) {
			var newActiveIndex = findTabIndex(tab.index);
			ctrl.select(newActiveIndex);
		}
	};

	ctrl.removeTab = function removeTab(tab) {
		var index;
		for (var i = 0; i < ctrl.tabs.length; i++) {
			if (ctrl.tabs[i].tab === tab) {
				index = i;
				break;
			}
		}

		if (ctrl.tabs[index].index === ctrl.active) {
			var newActiveTabIndex = index === ctrl.tabs.length - 1 ?
			  index - 1 : index + 1 % ctrl.tabs.length;
			ctrl.select(newActiveTabIndex);
		}

		ctrl.tabs.splice(index, 1);
	};

	$scope.$watch('tabset.active', function (val) {
		if (angular.isDefined(val) && val !== oldIndex) {
			ctrl.select(findTabIndex(val));
		}
	});

	var destroyed;
	$scope.$on('$destroy', function () {
		destroyed = true;
	});

	function findTabIndex(index) {
		for (var i = 0; i < ctrl.tabs.length; i++) {
			if (ctrl.tabs[i].index === index) {
				return i;
			}
		}
	}
}])

.directive('uibTabset', function () {
	return {
		transclude: true,
		replace: true,
		scope: {},
		bindToController: {
			active: '=?',
			type: '@'
		},
		controller: 'UibTabsetController',
		controllerAs: 'tabset',
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/tabs/tabset.html';
		},
		link: function (scope, element, attrs) {
			scope.vertical = angular.isDefined(attrs.vertical) ?
			  scope.$parent.$eval(attrs.vertical) : false;
			scope.justified = angular.isDefined(attrs.justified) ?
			  scope.$parent.$eval(attrs.justified) : false;
		}
	};
})

.directive('uibTab', ['$parse', function ($parse) {
	return {
		require: '^uibTabset',
		replace: true,
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || 'uib/template/tabs/tab.html';
		},
		transclude: true,
		scope: {
			heading: '@',
			index: '=?',
			classes: '@?',
			onSelect: '&select', //This callback is called in contentHeadingTransclude
			//once it inserts the tab's content into the dom
			onDeselect: '&deselect'
		},
		controller: function () {
			//Empty controller so other directives can require being 'under' a tab
		},
		controllerAs: 'tab',
		link: function (scope, elm, attrs, tabsetCtrl, transclude) {
			scope.disabled = false;
			if (attrs.disable) {
				scope.$parent.$watch($parse(attrs.disable), function (value) {
					scope.disabled = !!value;
				});
			}

			if (angular.isUndefined(attrs.index)) {
				if (tabsetCtrl.tabs && tabsetCtrl.tabs.length) {
					scope.index = Math.max.apply(null, tabsetCtrl.tabs.map(function (t) { return t.index; })) + 1;
				} else {
					scope.index = 0;
				}
			}

			if (angular.isUndefined(attrs.classes)) {
				scope.classes = '';
			}

			scope.select = function (evt) {
				if (!scope.disabled) {
					var index;
					for (var i = 0; i < tabsetCtrl.tabs.length; i++) {
						if (tabsetCtrl.tabs[i].tab === scope) {
							index = i;
							break;
						}
					}

					tabsetCtrl.select(index, evt);
				}
			};

			tabsetCtrl.addTab(scope);
			scope.$on('$destroy', function () {
				tabsetCtrl.removeTab(scope);
			});

			//We need to transclude later, once the content container is ready.
			//when this link happens, we're inside a tab heading.
			scope.$transcludeFn = transclude;
		}
	};
}])

.directive('uibTabHeadingTransclude', function () {
	return {
		restrict: 'A',
		require: '^uibTab',
		link: function (scope, elm) {
			scope.$watch('headingElement', function updateHeadingElement(heading) {
				if (heading) {
					elm.html('');
					elm.append(heading);
				}
			});
		}
	};
})

.directive('uibTabContentTransclude', function () {
	return {
		restrict: 'A',
		require: '^uibTabset',
		link: function (scope, elm, attrs) {
			var tab = scope.$eval(attrs.uibTabContentTransclude).tab;

			//Now our tab is ready to be transcluded: both the tab heading area
			//and the tab content area are loaded.  Transclude 'em both.
			tab.$transcludeFn(tab.$parent, function (contents) {
				angular.forEach(contents, function (node) {
					if (isTabHeading(node)) {
						//Let tabHeadingTransclude know.
						tab.headingElement = node;
					} else {
						elm.append(node);
					}
				});
			});
		}
	};

	function isTabHeading(node) {
		return node.tagName && (
		  node.hasAttribute('uib-tab-heading') ||
		  node.hasAttribute('data-uib-tab-heading') ||
		  node.hasAttribute('x-uib-tab-heading') ||
		  node.tagName.toLowerCase() === 'uib-tab-heading' ||
		  node.tagName.toLowerCase() === 'data-uib-tab-heading' ||
		  node.tagName.toLowerCase() === 'x-uib-tab-heading' ||
		  node.tagName.toLowerCase() === 'uib:tab-heading'
		);
	}
});

angular.module('ui.bootstrap.timepicker', [])

.constant('uibTimepickerConfig', {
	hourStep: 1,
	minuteStep: 1,
	secondStep: 1,
	showMeridian: true,
	showSeconds: false,
	meridians: null,
	readonlyInput: false,
	mousewheel: true,
	arrowkeys: true,
	showSpinners: true,
	templateUrl: 'uib/template/timepicker/timepicker.html'
})

.controller('UibTimepickerController', ['$scope', '$element', '$attrs', '$parse', '$log', '$locale', 'uibTimepickerConfig', function ($scope, $element, $attrs, $parse, $log, $locale, timepickerConfig) {
	var selected = new Date(),
	  watchers = [],
	  ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
	  meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS,
	  padHours = angular.isDefined($attrs.padHours) ? $scope.$parent.$eval($attrs.padHours) : true;

	$scope.tabindex = angular.isDefined($attrs.tabindex) ? $attrs.tabindex : 0;
	$element.removeAttr('tabindex');

	this.init = function (ngModelCtrl_, inputs) {
		ngModelCtrl = ngModelCtrl_;
		ngModelCtrl.$render = this.render;

		ngModelCtrl.$formatters.unshift(function (modelValue) {
			return modelValue ? new Date(modelValue) : null;
		});

		var hoursInputEl = inputs.eq(0),
			minutesInputEl = inputs.eq(1),
			secondsInputEl = inputs.eq(2);

		var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel;

		if (mousewheel) {
			this.setupMousewheelEvents(hoursInputEl, minutesInputEl, secondsInputEl);
		}

		var arrowkeys = angular.isDefined($attrs.arrowkeys) ? $scope.$parent.$eval($attrs.arrowkeys) : timepickerConfig.arrowkeys;
		if (arrowkeys) {
			this.setupArrowkeyEvents(hoursInputEl, minutesInputEl, secondsInputEl);
		}

		$scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput;
		this.setupInputEvents(hoursInputEl, minutesInputEl, secondsInputEl);
	};

	var hourStep = timepickerConfig.hourStep;
	if ($attrs.hourStep) {
		watchers.push($scope.$parent.$watch($parse($attrs.hourStep), function (value) {
			hourStep = +value;
		}));
	}

	var minuteStep = timepickerConfig.minuteStep;
	if ($attrs.minuteStep) {
		watchers.push($scope.$parent.$watch($parse($attrs.minuteStep), function (value) {
			minuteStep = +value;
		}));
	}

	var min;
	watchers.push($scope.$parent.$watch($parse($attrs.min), function (value) {
		var dt = new Date(value);
		min = isNaN(dt) ? undefined : dt;
	}));

	var max;
	watchers.push($scope.$parent.$watch($parse($attrs.max), function (value) {
		var dt = new Date(value);
		max = isNaN(dt) ? undefined : dt;
	}));

	var disabled = false;
	if ($attrs.ngDisabled) {
		watchers.push($scope.$parent.$watch($parse($attrs.ngDisabled), function (value) {
			disabled = value;
		}));
	}

	$scope.noIncrementHours = function () {
		var incrementedSelected = addMinutes(selected, hourStep * 60);
		return disabled || incrementedSelected > max ||
		  incrementedSelected < selected && incrementedSelected < min;
	};

	$scope.noDecrementHours = function () {
		var decrementedSelected = addMinutes(selected, -hourStep * 60);
		return disabled || decrementedSelected < min ||
		  decrementedSelected > selected && decrementedSelected > max;
	};

	$scope.noIncrementMinutes = function () {
		var incrementedSelected = addMinutes(selected, minuteStep);
		return disabled || incrementedSelected > max ||
		  incrementedSelected < selected && incrementedSelected < min;
	};

	$scope.noDecrementMinutes = function () {
		var decrementedSelected = addMinutes(selected, -minuteStep);
		return disabled || decrementedSelected < min ||
		  decrementedSelected > selected && decrementedSelected > max;
	};

	$scope.noIncrementSeconds = function () {
		var incrementedSelected = addSeconds(selected, secondStep);
		return disabled || incrementedSelected > max ||
		  incrementedSelected < selected && incrementedSelected < min;
	};

	$scope.noDecrementSeconds = function () {
		var decrementedSelected = addSeconds(selected, -secondStep);
		return disabled || decrementedSelected < min ||
		  decrementedSelected > selected && decrementedSelected > max;
	};

	$scope.noToggleMeridian = function () {
		if (selected.getHours() < 12) {
			return disabled || addMinutes(selected, 12 * 60) > max;
		}

		return disabled || addMinutes(selected, -12 * 60) < min;
	};

	var secondStep = timepickerConfig.secondStep;
	if ($attrs.secondStep) {
		watchers.push($scope.$parent.$watch($parse($attrs.secondStep), function (value) {
			secondStep = +value;
		}));
	}

	$scope.showSeconds = timepickerConfig.showSeconds;
	if ($attrs.showSeconds) {
		watchers.push($scope.$parent.$watch($parse($attrs.showSeconds), function (value) {
			$scope.showSeconds = !!value;
		}));
	}

	// 12H / 24H mode
	$scope.showMeridian = timepickerConfig.showMeridian;
	if ($attrs.showMeridian) {
		watchers.push($scope.$parent.$watch($parse($attrs.showMeridian), function (value) {
			$scope.showMeridian = !!value;

			if (ngModelCtrl.$error.time) {
				// Evaluate from template
				var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();
				if (angular.isDefined(hours) && angular.isDefined(minutes)) {
					selected.setHours(hours);
					refresh();
				}
			} else {
				updateTemplate();
			}
		}));
	}

	// Get $scope.hours in 24H mode if valid
	function getHoursFromTemplate() {
		var hours = +$scope.hours;
		var valid = $scope.showMeridian ? hours > 0 && hours < 13 :
		  hours >= 0 && hours < 24;
		if (!valid || $scope.hours === '') {
			return undefined;
		}

		if ($scope.showMeridian) {
			if (hours === 12) {
				hours = 0;
			}
			if ($scope.meridian === meridians[1]) {
				hours = hours + 12;
			}
		}
		return hours;
	}

	function getMinutesFromTemplate() {
		var minutes = +$scope.minutes;
		var valid = minutes >= 0 && minutes < 60;
		if (!valid || $scope.minutes === '') {
			return undefined;
		}
		return minutes;
	}

	function getSecondsFromTemplate() {
		var seconds = +$scope.seconds;
		return seconds >= 0 && seconds < 60 ? seconds : undefined;
	}

	function pad(value, noPad) {
		if (value === null) {
			return '';
		}

		return angular.isDefined(value) && value.toString().length < 2 && !noPad ?
		  '0' + value : value.toString();
	}

	// Respond on mousewheel spin
	this.setupMousewheelEvents = function (hoursInputEl, minutesInputEl, secondsInputEl) {
		var isScrollingUp = function (e) {
			if (e.originalEvent) {
				e = e.originalEvent;
			}
			//pick correct delta variable depending on event
			var delta = e.wheelDelta ? e.wheelDelta : -e.deltaY;
			return e.detail || delta > 0;
		};

		hoursInputEl.bind('mousewheel wheel', function (e) {
			if (!disabled) {
				$scope.$apply(isScrollingUp(e) ? $scope.incrementHours() : $scope.decrementHours());
			}
			e.preventDefault();
		});

		minutesInputEl.bind('mousewheel wheel', function (e) {
			if (!disabled) {
				$scope.$apply(isScrollingUp(e) ? $scope.incrementMinutes() : $scope.decrementMinutes());
			}
			e.preventDefault();
		});

		secondsInputEl.bind('mousewheel wheel', function (e) {
			if (!disabled) {
				$scope.$apply(isScrollingUp(e) ? $scope.incrementSeconds() : $scope.decrementSeconds());
			}
			e.preventDefault();
		});
	};

	// Respond on up/down arrowkeys
	this.setupArrowkeyEvents = function (hoursInputEl, minutesInputEl, secondsInputEl) {
		hoursInputEl.bind('keydown', function (e) {
			if (!disabled) {
				if (e.which === 38) { // up
					e.preventDefault();
					$scope.incrementHours();
					$scope.$apply();
				} else if (e.which === 40) { // down
					e.preventDefault();
					$scope.decrementHours();
					$scope.$apply();
				}
			}
		});

		minutesInputEl.bind('keydown', function (e) {
			if (!disabled) {
				if (e.which === 38) { // up
					e.preventDefault();
					$scope.incrementMinutes();
					$scope.$apply();
				} else if (e.which === 40) { // down
					e.preventDefault();
					$scope.decrementMinutes();
					$scope.$apply();
				}
			}
		});

		secondsInputEl.bind('keydown', function (e) {
			if (!disabled) {
				if (e.which === 38) { // up
					e.preventDefault();
					$scope.incrementSeconds();
					$scope.$apply();
				} else if (e.which === 40) { // down
					e.preventDefault();
					$scope.decrementSeconds();
					$scope.$apply();
				}
			}
		});
	};

	this.setupInputEvents = function (hoursInputEl, minutesInputEl, secondsInputEl) {
		if ($scope.readonlyInput) {
			$scope.updateHours = angular.noop;
			$scope.updateMinutes = angular.noop;
			$scope.updateSeconds = angular.noop;
			return;
		}

		var invalidate = function (invalidHours, invalidMinutes, invalidSeconds) {
			ngModelCtrl.$setViewValue(null);
			ngModelCtrl.$setValidity('time', false);
			if (angular.isDefined(invalidHours)) {
				$scope.invalidHours = invalidHours;
			}

			if (angular.isDefined(invalidMinutes)) {
				$scope.invalidMinutes = invalidMinutes;
			}

			if (angular.isDefined(invalidSeconds)) {
				$scope.invalidSeconds = invalidSeconds;
			}
		};

		$scope.updateHours = function () {
			var hours = getHoursFromTemplate(),
			  minutes = getMinutesFromTemplate();

			ngModelCtrl.$setDirty();

			if (angular.isDefined(hours) && angular.isDefined(minutes)) {
				selected.setHours(hours);
				selected.setMinutes(minutes);
				if (selected < min || selected > max) {
					invalidate(true);
				} else {
					refresh('h');
				}
			} else {
				invalidate(true);
			}
		};

		hoursInputEl.bind('blur', function (e) {
			ngModelCtrl.$setTouched();
			if (modelIsEmpty()) {
				makeValid();
			} else if ($scope.hours === null || $scope.hours === '') {
				invalidate(true);
			} else if (!$scope.invalidHours && $scope.hours < 10) {
				$scope.$apply(function () {
					$scope.hours = pad($scope.hours, !padHours);
				});
			}
		});

		$scope.updateMinutes = function () {
			var minutes = getMinutesFromTemplate(),
			  hours = getHoursFromTemplate();

			ngModelCtrl.$setDirty();

			if (angular.isDefined(minutes) && angular.isDefined(hours)) {
				selected.setHours(hours);
				selected.setMinutes(minutes);
				if (selected < min || selected > max) {
					invalidate(undefined, true);
				} else {
					refresh('m');
				}
			} else {
				invalidate(undefined, true);
			}
		};

		minutesInputEl.bind('blur', function (e) {
			ngModelCtrl.$setTouched();
			if (modelIsEmpty()) {
				makeValid();
			} else if ($scope.minutes === null) {
				invalidate(undefined, true);
			} else if (!$scope.invalidMinutes && $scope.minutes < 10) {
				$scope.$apply(function () {
					$scope.minutes = pad($scope.minutes);
				});
			}
		});

		$scope.updateSeconds = function () {
			var seconds = getSecondsFromTemplate();

			ngModelCtrl.$setDirty();

			if (angular.isDefined(seconds)) {
				selected.setSeconds(seconds);
				refresh('s');
			} else {
				invalidate(undefined, undefined, true);
			}
		};

		secondsInputEl.bind('blur', function (e) {
			if (modelIsEmpty()) {
				makeValid();
			} else if (!$scope.invalidSeconds && $scope.seconds < 10) {
				$scope.$apply(function () {
					$scope.seconds = pad($scope.seconds);
				});
			}
		});

	};

	this.render = function () {
		var date = ngModelCtrl.$viewValue;

		if (isNaN(date)) {
			ngModelCtrl.$setValidity('time', false);
			$log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
		} else {
			if (date) {
				selected = date;
			}

			if (selected < min || selected > max) {
				ngModelCtrl.$setValidity('time', false);
				$scope.invalidHours = true;
				$scope.invalidMinutes = true;
			} else {
				makeValid();
			}
			updateTemplate();
		}
	};

	// Call internally when we know that model is valid.
	function refresh(keyboardChange) {
		makeValid();
		ngModelCtrl.$setViewValue(new Date(selected));
		updateTemplate(keyboardChange);
	}

	function makeValid() {
		ngModelCtrl.$setValidity('time', true);
		$scope.invalidHours = false;
		$scope.invalidMinutes = false;
		$scope.invalidSeconds = false;
	}

	function updateTemplate(keyboardChange) {
		if (!ngModelCtrl.$modelValue) {
			$scope.hours = null;
			$scope.minutes = null;
			$scope.seconds = null;
			$scope.meridian = meridians[0];
		} else {
			var hours = selected.getHours(),
			  minutes = selected.getMinutes(),
			  seconds = selected.getSeconds();

			if ($scope.showMeridian) {
				hours = hours === 0 || hours === 12 ? 12 : hours % 12; // Convert 24 to 12 hour system
			}

			$scope.hours = keyboardChange === 'h' ? hours : pad(hours, !padHours);
			if (keyboardChange !== 'm') {
				$scope.minutes = pad(minutes);
			}
			$scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];

			if (keyboardChange !== 's') {
				$scope.seconds = pad(seconds);
			}
			$scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
		}
	}

	function addSecondsToSelected(seconds) {
		selected = addSeconds(selected, seconds);
		refresh();
	}

	function addMinutes(selected, minutes) {
		return addSeconds(selected, minutes * 60);
	}

	function addSeconds(date, seconds) {
		var dt = new Date(date.getTime() + seconds * 1000);
		var newDate = new Date(date);
		newDate.setHours(dt.getHours(), dt.getMinutes(), dt.getSeconds());
		return newDate;
	}

	function modelIsEmpty() {
		return ($scope.hours === null || $scope.hours === '') &&
		  ($scope.minutes === null || $scope.minutes === '') &&
		  (!$scope.showSeconds || $scope.showSeconds && ($scope.seconds === null || $scope.seconds === ''));
	}

	$scope.showSpinners = angular.isDefined($attrs.showSpinners) ?
	  $scope.$parent.$eval($attrs.showSpinners) : timepickerConfig.showSpinners;

	$scope.incrementHours = function () {
		if (!$scope.noIncrementHours()) {
			addSecondsToSelected(hourStep * 60 * 60);
		}
	};

	$scope.decrementHours = function () {
		if (!$scope.noDecrementHours()) {
			addSecondsToSelected(-hourStep * 60 * 60);
		}
	};

	$scope.incrementMinutes = function () {
		if (!$scope.noIncrementMinutes()) {
			addSecondsToSelected(minuteStep * 60);
		}
	};

	$scope.decrementMinutes = function () {
		if (!$scope.noDecrementMinutes()) {
			addSecondsToSelected(-minuteStep * 60);
		}
	};

	$scope.incrementSeconds = function () {
		if (!$scope.noIncrementSeconds()) {
			addSecondsToSelected(secondStep);
		}
	};

	$scope.decrementSeconds = function () {
		if (!$scope.noDecrementSeconds()) {
			addSecondsToSelected(-secondStep);
		}
	};

	$scope.toggleMeridian = function () {
		var minutes = getMinutesFromTemplate(),
			hours = getHoursFromTemplate();

		if (!$scope.noToggleMeridian()) {
			if (angular.isDefined(minutes) && angular.isDefined(hours)) {
				addSecondsToSelected(12 * 60 * (selected.getHours() < 12 ? 60 : -60));
			} else {
				$scope.meridian = $scope.meridian === meridians[0] ? meridians[1] : meridians[0];
			}
		}
	};

	$scope.blur = function () {
		ngModelCtrl.$setTouched();
	};

	$scope.$on('$destroy', function () {
		while (watchers.length) {
			watchers.shift()();
		}
	});
}])

.directive('uibTimepicker', ['uibTimepickerConfig', function (uibTimepickerConfig) {
	return {
		require: ['uibTimepicker', '?^ngModel'],
		restrict: 'A',
		controller: 'UibTimepickerController',
		controllerAs: 'timepicker',
		scope: {},
		templateUrl: function (element, attrs) {
			return attrs.templateUrl || uibTimepickerConfig.templateUrl;
		},
		link: function (scope, element, attrs, ctrls) {
			var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];

			if (ngModelCtrl) {
				timepickerCtrl.init(ngModelCtrl, element.find('input'));
			}
		}
	};
}]);

angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.debounce', 'ui.bootstrap.position'])

/**
 * A helper service that can parse typeahead's syntax (string provided by users)
 * Extracted to a separate service for ease of unit testing
 */
  .factory('uibTypeaheadParser', ['$parse', function ($parse) {
  	//                      000001111111100000000000002222222200000000000000003333333333333330000000000044444444000
  	var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;
  	return {
  		parse: function (input) {
  			var match = input.match(TYPEAHEAD_REGEXP);
  			if (!match) {
  				throw new Error(
				  'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' +
					' but got "' + input + '".');
  			}

  			return {
  				itemName: match[3],
  				source: $parse(match[4]),
  				viewMapper: $parse(match[2] || match[1]),
  				modelMapper: $parse(match[1])
  			};
  		}
  	};
  }])

  .controller('UibTypeaheadController', ['$scope', '$element', '$attrs', '$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$$debounce', '$uibPosition', 'uibTypeaheadParser',
    function (originalScope, element, attrs, $compile, $parse, $q, $timeout, $document, $window, $rootScope, $$debounce, $position, typeaheadParser) {
    	var HOT_KEYS = [9, 13, 27, 38, 40];
    	var eventDebounceTime = 200;
    	var modelCtrl, ngModelOptions;
    	//SUPPORTED ATTRIBUTES (OPTIONS)

    	//minimal no of characters that needs to be entered before typeahead kicks-in
    	var minLength = originalScope.$eval(attrs.typeaheadMinLength);
    	if (!minLength && minLength !== 0) {
    		minLength = 1;
    	}

    	originalScope.$watch(attrs.typeaheadMinLength, function (newVal) {
    		minLength = !newVal && newVal !== 0 ? 1 : newVal;
    	});

    	//minimal wait time after last character typed before typeahead kicks-in
    	var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;

    	//should it restrict model values to the ones selected from the popup only?
    	var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;
    	originalScope.$watch(attrs.typeaheadEditable, function (newVal) {
    		isEditable = newVal !== false;
    	});

    	//binding to a variable that indicates if matches are being retrieved asynchronously
    	var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;

    	//a function to determine if an event should cause selection
    	var isSelectEvent = attrs.typeaheadShouldSelect ? $parse(attrs.typeaheadShouldSelect) : function (scope, vals) {
    		var evt = vals.$event;
    		return evt.which === 13 || evt.which === 9;
    	};

    	//a callback executed when a match is selected
    	var onSelectCallback = $parse(attrs.typeaheadOnSelect);

    	//should it select highlighted popup value when losing focus?
    	var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false;

    	//binding to a variable that indicates if there were no results after the query is completed
    	var isNoResultsSetter = $parse(attrs.typeaheadNoResults).assign || angular.noop;

    	var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;

    	var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;

    	var appendTo = attrs.typeaheadAppendTo ?
		  originalScope.$eval(attrs.typeaheadAppendTo) : null;

    	var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;

    	//If input matches an item of the list exactly, select it automatically
    	var selectOnExact = attrs.typeaheadSelectOnExact ? originalScope.$eval(attrs.typeaheadSelectOnExact) : false;

    	//binding to a variable that indicates if dropdown is open
    	var isOpenSetter = $parse(attrs.typeaheadIsOpen).assign || angular.noop;

    	var showHint = originalScope.$eval(attrs.typeaheadShowHint) || false;

    	//INTERNAL VARIABLES

    	//model setter executed upon match selection
    	var parsedModel = $parse(attrs.ngModel);
    	var invokeModelSetter = $parse(attrs.ngModel + '($$$p)');
    	var $setModelValue = function (scope, newValue) {
    		if (angular.isFunction(parsedModel(originalScope)) &&
			  ngModelOptions && ngModelOptions.$options && ngModelOptions.$options.getterSetter) {
    			return invokeModelSetter(scope, { $$$p: newValue });
    		}

    		return parsedModel.assign(scope, newValue);
    	};

    	//expressions used by typeahead
    	var parserResult = typeaheadParser.parse(attrs.uibTypeahead);

    	var hasFocus;

    	//Used to avoid bug in iOS webview where iOS keyboard does not fire
    	//mousedown & mouseup events
    	//Issue #3699
    	var selected;

    	//create a child scope for the typeahead directive so we are not polluting original scope
    	//with typeahead-specific data (matches, query etc.)
    	var scope = originalScope.$new();
    	var offDestroy = originalScope.$on('$destroy', function () {
    		scope.$destroy();
    	});
    	scope.$on('$destroy', offDestroy);

    	// WAI-ARIA
    	var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
    	element.attr({
    		'aria-autocomplete': 'list',
    		'aria-expanded': false,
    		'aria-owns': popupId
    	});

    	var inputsContainer, hintInputElem;
    	//add read-only input to show hint
    	if (showHint) {
    		inputsContainer = angular.element('<div></div>');
    		inputsContainer.css('position', 'relative');
    		element.after(inputsContainer);
    		hintInputElem = element.clone();
    		hintInputElem.attr('placeholder', '');
    		hintInputElem.attr('tabindex', '-1');
    		hintInputElem.val('');
    		hintInputElem.css({
    			'position': 'absolute',
    			'top': '0px',
    			'left': '0px',
    			'border-color': 'transparent',
    			'box-shadow': 'none',
    			'opacity': 1,
    			'background': 'none 0% 0% / auto repeat scroll padding-box border-box rgb(255, 255, 255)',
    			'color': '#999'
    		});
    		element.css({
    			'position': 'relative',
    			'vertical-align': 'top',
    			'background-color': 'transparent'
    		});

    		if (hintInputElem.attr('id')) {
    			hintInputElem.removeAttr('id'); // remove duplicate id if present.
    		}
    		inputsContainer.append(hintInputElem);
    		hintInputElem.after(element);
    	}

    	//pop-up element used to display matches
    	var popUpEl = angular.element('<div uib-typeahead-popup></div>');
    	popUpEl.attr({
    		id: popupId,
    		matches: 'matches',
    		active: 'activeIdx',
    		select: 'select(activeIdx, evt)',
    		'move-in-progress': 'moveInProgress',
    		query: 'query',
    		position: 'position',
    		'assign-is-open': 'assignIsOpen(isOpen)',
    		debounce: 'debounceUpdate'
    	});
    	//custom item template
    	if (angular.isDefined(attrs.typeaheadTemplateUrl)) {
    		popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);
    	}

    	if (angular.isDefined(attrs.typeaheadPopupTemplateUrl)) {
    		popUpEl.attr('popup-template-url', attrs.typeaheadPopupTemplateUrl);
    	}

    	var resetHint = function () {
    		if (showHint) {
    			hintInputElem.val('');
    		}
    	};

    	var resetMatches = function () {
    		scope.matches = [];
    		scope.activeIdx = -1;
    		element.attr('aria-expanded', false);
    		resetHint();
    	};

    	var getMatchId = function (index) {
    		return popupId + '-option-' + index;
    	};

    	// Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead.
    	// This attribute is added or removed automatically when the `activeIdx` changes.
    	scope.$watch('activeIdx', function (index) {
    		if (index < 0) {
    			element.removeAttr('aria-activedescendant');
    		} else {
    			element.attr('aria-activedescendant', getMatchId(index));
    		}
    	});

    	var inputIsExactMatch = function (inputValue, index) {
    		if (scope.matches.length > index && inputValue) {
    			return inputValue.toUpperCase() === scope.matches[index].label.toUpperCase();
    		}

    		return false;
    	};

    	var getMatchesAsync = function (inputValue, evt) {
    		var locals = { $viewValue: inputValue };
    		isLoadingSetter(originalScope, true);
    		isNoResultsSetter(originalScope, false);
    		$q.when(parserResult.source(originalScope, locals)).then(function (matches) {
    			//it might happen that several async queries were in progress if a user were typing fast
    			//but we are interested only in responses that correspond to the current view value
    			var onCurrentRequest = inputValue === modelCtrl.$viewValue;
    			if (onCurrentRequest && hasFocus) {
    				if (matches && matches.length > 0) {
    					scope.activeIdx = focusFirst ? 0 : -1;
    					isNoResultsSetter(originalScope, false);
    					scope.matches.length = 0;

    					//transform labels
    					for (var i = 0; i < matches.length; i++) {
    						locals[parserResult.itemName] = matches[i];
    						scope.matches.push({
    							id: getMatchId(i),
    							label: parserResult.viewMapper(scope, locals),
    							model: matches[i]
    						});
    					}

    					scope.query = inputValue;
    					//position pop-up with matches - we need to re-calculate its position each time we are opening a window
    					//with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
    					//due to other elements being rendered
    					recalculatePosition();

    					element.attr('aria-expanded', true);

    					//Select the single remaining option if user input matches
    					if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) {
    						if (angular.isNumber(scope.debounceUpdate) || angular.isObject(scope.debounceUpdate)) {
    							$$debounce(function () {
    								scope.select(0, evt);
    							}, angular.isNumber(scope.debounceUpdate) ? scope.debounceUpdate : scope.debounceUpdate['default']);
    						} else {
    							scope.select(0, evt);
    						}
    					}

    					if (showHint) {
    						var firstLabel = scope.matches[0].label;
    						if (angular.isString(inputValue) &&
							  inputValue.length > 0 &&
							  firstLabel.slice(0, inputValue.length).toUpperCase() === inputValue.toUpperCase()) {
    							hintInputElem.val(inputValue + firstLabel.slice(inputValue.length));
    						} else {
    							hintInputElem.val('');
    						}
    					}
    				} else {
    					resetMatches();
    					isNoResultsSetter(originalScope, true);
    				}
    			}
    			if (onCurrentRequest) {
    				isLoadingSetter(originalScope, false);
    			}
    		}, function () {
    			resetMatches();
    			isLoadingSetter(originalScope, false);
    			isNoResultsSetter(originalScope, true);
    		});
    	};

    	// bind events only if appendToBody params exist - performance feature
    	if (appendToBody) {
    		angular.element($window).on('resize', fireRecalculating);
    		$document.find('body').on('scroll', fireRecalculating);
    	}

    	// Declare the debounced function outside recalculating for
    	// proper debouncing
    	var debouncedRecalculate = $$debounce(function () {
    		// if popup is visible
    		if (scope.matches.length) {
    			recalculatePosition();
    		}

    		scope.moveInProgress = false;
    	}, eventDebounceTime);

    	// Default progress type
    	scope.moveInProgress = false;

    	function fireRecalculating() {
    		if (!scope.moveInProgress) {
    			scope.moveInProgress = true;
    			scope.$digest();
    		}

    		debouncedRecalculate();
    	}

    	// recalculate actual position and set new values to scope
    	// after digest loop is popup in right position
    	function recalculatePosition() {
    		scope.position = appendToBody ? $position.offset(element) : $position.position(element);
    		scope.position.top += element.prop('offsetHeight');
    	}

    	//we need to propagate user's query so we can higlight matches
    	scope.query = undefined;

    	//Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
    	var timeoutPromise;

    	var scheduleSearchWithTimeout = function (inputValue) {
    		timeoutPromise = $timeout(function () {
    			getMatchesAsync(inputValue);
    		}, waitTime);
    	};

    	var cancelPreviousTimeout = function () {
    		if (timeoutPromise) {
    			$timeout.cancel(timeoutPromise);
    		}
    	};

    	resetMatches();

    	scope.assignIsOpen = function (isOpen) {
    		isOpenSetter(originalScope, isOpen);
    	};

    	scope.select = function (activeIdx, evt) {
    		//called from within the $digest() cycle
    		var locals = {};
    		var model, item;

    		selected = true;
    		locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
    		model = parserResult.modelMapper(originalScope, locals);
    		$setModelValue(originalScope, model);
    		modelCtrl.$setValidity('editable', true);
    		modelCtrl.$setValidity('parse', true);

    		onSelectCallback(originalScope, {
    			$item: item,
    			$model: model,
    			$label: parserResult.viewMapper(originalScope, locals),
    			$event: evt
    		});

    		resetMatches();

    		//return focus to the input element if a match was selected via a mouse click event
    		// use timeout to avoid $rootScope:inprog error
    		if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) {
    			$timeout(function () { element[0].focus(); }, 0, false);
    		}
    	};

    	//bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
    	element.on('keydown', function (evt) {
    		//typeahead is open and an "interesting" key was pressed
    		if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
    			return;
    		}

    		var shouldSelect = isSelectEvent(originalScope, { $event: evt });

    		/**
			 * if there's nothing selected (i.e. focusFirst) and enter or tab is hit
			 * or
			 * shift + tab is pressed to bring focus to the previous element
			 * then clear the results
			 */
    		if (scope.activeIdx === -1 && shouldSelect || evt.which === 9 && !!evt.shiftKey) {
    			resetMatches();
    			scope.$digest();
    			return;
    		}

    		evt.preventDefault();
    		var target;
    		switch (evt.which) {
    			case 27: // escape
    				evt.stopPropagation();

    				resetMatches();
    				originalScope.$digest();
    				break;
    			case 38: // up arrow
    				scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1;
    				scope.$digest();
    				target = popUpEl[0].querySelectorAll('.uib-typeahead-match')[scope.activeIdx];
    				target.parentNode.scrollTop = target.offsetTop;
    				break;
    			case 40: // down arrow
    				scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
    				scope.$digest();
    				target = popUpEl[0].querySelectorAll('.uib-typeahead-match')[scope.activeIdx];
    				target.parentNode.scrollTop = target.offsetTop;
    				break;
    			default:
    				if (shouldSelect) {
    					scope.$apply(function () {
    						if (angular.isNumber(scope.debounceUpdate) || angular.isObject(scope.debounceUpdate)) {
    							$$debounce(function () {
    								scope.select(scope.activeIdx, evt);
    							}, angular.isNumber(scope.debounceUpdate) ? scope.debounceUpdate : scope.debounceUpdate['default']);
    						} else {
    							scope.select(scope.activeIdx, evt);
    						}
    					});
    				}
    		}
    	});

    	element.bind('focus', function (evt) {
    		hasFocus = true;
    		if (minLength === 0 && !modelCtrl.$viewValue) {
    			$timeout(function () {
    				getMatchesAsync(modelCtrl.$viewValue, evt);
    			}, 0);
    		}
    	});

    	element.bind('blur', function (evt) {
    		if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) {
    			selected = true;
    			scope.$apply(function () {
    				if (angular.isObject(scope.debounceUpdate) && angular.isNumber(scope.debounceUpdate.blur)) {
    					$$debounce(function () {
    						scope.select(scope.activeIdx, evt);
    					}, scope.debounceUpdate.blur);
    				} else {
    					scope.select(scope.activeIdx, evt);
    				}
    			});
    		}
    		if (!isEditable && modelCtrl.$error.editable) {
    			modelCtrl.$setViewValue();
    			scope.$apply(function () {
    				// Reset validity as we are clearing
    				modelCtrl.$setValidity('editable', true);
    				modelCtrl.$setValidity('parse', true);
    			});
    			element.val('');
    		}
    		hasFocus = false;
    		selected = false;
    	});

    	// Keep reference to click handler to unbind it.
    	var dismissClickHandler = function (evt) {
    		// Issue #3973
    		// Firefox treats right click as a click on document
    		if (element[0] !== evt.target && evt.which !== 3 && scope.matches.length !== 0) {
    			resetMatches();
    			if (!$rootScope.$$phase) {
    				originalScope.$digest();
    			}
    		}
    	};

    	$document.on('click', dismissClickHandler);

    	originalScope.$on('$destroy', function () {
    		$document.off('click', dismissClickHandler);
    		if (appendToBody || appendTo) {
    			$popup.remove();
    		}

    		if (appendToBody) {
    			angular.element($window).off('resize', fireRecalculating);
    			$document.find('body').off('scroll', fireRecalculating);
    		}
    		// Prevent jQuery cache memory leak
    		popUpEl.remove();

    		if (showHint) {
    			inputsContainer.remove();
    		}
    	});

    	var $popup = $compile(popUpEl)(scope);

    	if (appendToBody) {
    		$document.find('body').append($popup);
    	} else if (appendTo) {
    		angular.element(appendTo).eq(0).append($popup);
    	} else {
    		element.after($popup);
    	}

    	this.init = function (_modelCtrl, _ngModelOptions) {
    		modelCtrl = _modelCtrl;
    		ngModelOptions = _ngModelOptions;

    		scope.debounceUpdate = modelCtrl.$options && $parse(modelCtrl.$options.debounce)(originalScope);

    		//plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
    		//$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
    		modelCtrl.$parsers.unshift(function (inputValue) {
    			hasFocus = true;

    			if (minLength === 0 || inputValue && inputValue.length >= minLength) {
    				if (waitTime > 0) {
    					cancelPreviousTimeout();
    					scheduleSearchWithTimeout(inputValue);
    				} else {
    					getMatchesAsync(inputValue);
    				}
    			} else {
    				isLoadingSetter(originalScope, false);
    				cancelPreviousTimeout();
    				resetMatches();
    			}

    			if (isEditable) {
    				return inputValue;
    			}

    			if (!inputValue) {
    				// Reset in case user had typed something previously.
    				modelCtrl.$setValidity('editable', true);
    				return null;
    			}

    			modelCtrl.$setValidity('editable', false);
    			return undefined;
    		});

    		modelCtrl.$formatters.push(function (modelValue) {
    			var candidateViewValue, emptyViewValue;
    			var locals = {};

    			// The validity may be set to false via $parsers (see above) if
    			// the model is restricted to selected values. If the model
    			// is set manually it is considered to be valid.
    			if (!isEditable) {
    				modelCtrl.$setValidity('editable', true);
    			}

    			if (inputFormatter) {
    				locals.$model = modelValue;
    				return inputFormatter(originalScope, locals);
    			}

    			//it might happen that we don't have enough info to properly render input value
    			//we need to check for this situation and simply return model value if we can't apply custom formatting
    			locals[parserResult.itemName] = modelValue;
    			candidateViewValue = parserResult.viewMapper(originalScope, locals);
    			locals[parserResult.itemName] = undefined;
    			emptyViewValue = parserResult.viewMapper(originalScope, locals);

    			return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue;
    		});
    	};
    }])

  .directive('uibTypeahead', function () {
  	return {
  		controller: 'UibTypeaheadController',
  		require: ['ngModel', '^?ngModelOptions', 'uibTypeahead'],
  		link: function (originalScope, element, attrs, ctrls) {
  			ctrls[2].init(ctrls[0], ctrls[1]);
  		}
  	};
  })

  .directive('uibTypeaheadPopup', ['$$debounce', function ($$debounce) {
  	return {
  		scope: {
  			matches: '=',
  			query: '=',
  			active: '=',
  			position: '&',
  			moveInProgress: '=',
  			select: '&',
  			assignIsOpen: '&',
  			debounce: '&'
  		},
  		replace: true,
  		templateUrl: function (element, attrs) {
  			return attrs.popupTemplateUrl || 'uib/template/typeahead/typeahead-popup.html';
  		},
  		link: function (scope, element, attrs) {
  			scope.templateUrl = attrs.templateUrl;

  			scope.isOpen = function () {
  				var isDropdownOpen = scope.matches.length > 0;
  				scope.assignIsOpen({ isOpen: isDropdownOpen });
  				return isDropdownOpen;
  			};

  			scope.isActive = function (matchIdx) {
  				return scope.active === matchIdx;
  			};

  			scope.selectActive = function (matchIdx) {
  				scope.active = matchIdx;
  			};

  			scope.selectMatch = function (activeIdx, evt) {
  				var debounce = scope.debounce();
  				if (angular.isNumber(debounce) || angular.isObject(debounce)) {
  					$$debounce(function () {
  						scope.select({ activeIdx: activeIdx, evt: evt });
  					}, angular.isNumber(debounce) ? debounce : debounce['default']);
  				} else {
  					scope.select({ activeIdx: activeIdx, evt: evt });
  				}
  			};
  		}
  	};
  }])

  .directive('uibTypeaheadMatch', ['$templateRequest', '$compile', '$parse', function ($templateRequest, $compile, $parse) {
  	return {
  		scope: {
  			index: '=',
  			match: '=',
  			query: '='
  		},
  		link: function (scope, element, attrs) {
  			var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'uib/template/typeahead/typeahead-match.html';
  			$templateRequest(tplUrl).then(function (tplContent) {
  				var tplEl = angular.element(tplContent.trim());
  				element.replaceWith(tplEl);
  				$compile(tplEl)(scope);
  			});
  		}
  	};
  }])

  .filter('uibTypeaheadHighlight', ['$sce', '$injector', '$log', function ($sce, $injector, $log) {
  	var isSanitizePresent;
  	isSanitizePresent = $injector.has('$sanitize');

  	function escapeRegexp(queryToEscape) {
  		// Regex: capture the whole query string and replace it with the string that will be used to match
  		// the results, for example if the capture is "a" the result will be \a
  		return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
  	}

  	function containsHtml(matchItem) {
  		return /<.*>/g.test(matchItem);
  	}

  	return function (matchItem, query) {
  		if (!isSanitizePresent && containsHtml(matchItem)) {
  			$log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger
  		}
  		matchItem = query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag
  		if (!isSanitizePresent) {
  			matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive
  		}
  		return matchItem;
  	};
  }]);

angular.module("uib/template/accordion/accordion-group.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/accordion/accordion-group.html",
	  "<div role=\"tab\" id=\"{{::headingId}}\" aria-selected=\"{{isOpen}}\" class=\"panel-heading\" ng-keypress=\"toggleOpen($event)\">\n" +
	  "  <h4 class=\"panel-title\">\n" +
	  "    <a role=\"button\" data-toggle=\"collapse\" href aria-expanded=\"{{isOpen}}\" aria-controls=\"{{::panelId}}\" tabindex=\"0\" class=\"accordion-toggle\" ng-click=\"toggleOpen()\" uib-accordion-transclude=\"heading\" ng-disabled=\"isDisabled\" uib-tabindex-toggle><span uib-accordion-header ng-class=\"{'text-muted': isDisabled}\">{{heading}}</span></a>\n" +
	  "  </h4>\n" +
	  "</div>\n" +
	  "<div id=\"{{::panelId}}\" aria-labelledby=\"{{::headingId}}\" aria-hidden=\"{{!isOpen}}\" role=\"tabpanel\" class=\"panel-collapse collapse\" uib-collapse=\"!isOpen\">\n" +
	  "  <div class=\"panel-body\" ng-transclude></div>\n" +
	  "</div>\n" +
	  "");
}]);

angular.module("uib/template/accordion/accordion.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/accordion/accordion.html",
	  "<div role=\"tablist\" class=\"panel-group\" ng-transclude></div>");
}]);

angular.module("uib/template/alert/alert.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/alert/alert.html",
	  "<button ng-show=\"closeable\" type=\"button\" class=\"close\" ng-click=\"close({$event: $event})\">\n" +
	  "  <span aria-hidden=\"true\">&times;</span>\n" +
	  "  <span class=\"sr-only\">Close</span>\n" +
	  "</button>\n" +
	  "<div ng-transclude></div>\n" +
	  "");
}]);

angular.module("uib/template/carousel/carousel.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/carousel/carousel.html",
	  "<div class=\"carousel-inner\" ng-transclude></div>\n" +
	  "<a role=\"button\" href class=\"left carousel-control\" ng-click=\"prev()\" ng-class=\"{ disabled: isPrevDisabled() }\" ng-show=\"slides.length > 1\">\n" +
	  "  <span aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-left\"></span>\n" +
	  "  <span class=\"sr-only\">previous</span>\n" +
	  "</a>\n" +
	  "<a role=\"button\" href class=\"right carousel-control\" ng-click=\"next()\" ng-class=\"{ disabled: isNextDisabled() }\" ng-show=\"slides.length > 1\">\n" +
	  "  <span aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-right\"></span>\n" +
	  "  <span class=\"sr-only\">next</span>\n" +
	  "</a>\n" +
	  "<ol class=\"carousel-indicators\" ng-show=\"slides.length > 1\">\n" +
	  "  <li ng-repeat=\"slide in slides | orderBy:indexOfSlide track by $index\" ng-class=\"{ active: isActive(slide) }\" ng-click=\"select(slide)\">\n" +
	  "    <span class=\"sr-only\">slide {{ $index + 1 }} of {{ slides.length }}<span ng-if=\"isActive(slide)\">, currently active</span></span>\n" +
	  "  </li>\n" +
	  "</ol>\n" +
	  "");
}]);

angular.module("uib/template/carousel/slide.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/carousel/slide.html",
	  "<div class=\"text-center\" ng-transclude></div>\n" +
	  "");
}]);

angular.module("uib/template/datepicker/datepicker.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/datepicker/datepicker.html",
	  "<div ng-switch=\"datepickerMode\">\n" +
	  "  <div uib-daypicker ng-switch-when=\"day\" tabindex=\"0\" class=\"uib-daypicker\"></div>\n" +
	  "  <div uib-monthpicker ng-switch-when=\"month\" tabindex=\"0\" class=\"uib-monthpicker\"></div>\n" +
	  "  <div uib-yearpicker ng-switch-when=\"year\" tabindex=\"0\" class=\"uib-yearpicker\"></div>\n" +
	  "</div>\n" +
	  "");
}]);

angular.module("uib/template/datepicker/day.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/datepicker/day.html",
	  "<table role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
	  "  <thead>\n" +
	  "    <tr>\n" +
	  "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left uib-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-left\"></i><span class=\"sr-only\">previous</span></button></th>\n" +
	  "      <th colspan=\"{{::5 + showWeeks}}\"><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm uib-title\" ng-click=\"toggleMode()\" ng-disabled=\"datepickerMode === maxMode\" tabindex=\"-1\"><strong>{{title}}</strong></button></th>\n" +
	  "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right uib-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-right\"></i><span class=\"sr-only\">next</span></button></th>\n" +
	  "    </tr>\n" +
	  "    <tr>\n" +
	  "      <th ng-if=\"showWeeks\" class=\"text-center\"></th>\n" +
	  "      <th ng-repeat=\"label in ::labels track by $index\" class=\"text-center\"><small aria-label=\"{{::label.full}}\">{{::label.abbr}}</small></th>\n" +
	  "    </tr>\n" +
	  "  </thead>\n" +
	  "  <tbody>\n" +
	  "    <tr class=\"uib-weeks\" ng-repeat=\"row in rows track by $index\" role=\"row\">\n" +
	  "      <td ng-if=\"showWeeks\" class=\"text-center h6\"><em>{{ weekNumbers[$index] }}</em></td>\n" +
	  "      <td ng-repeat=\"dt in row\" class=\"uib-day text-center\" role=\"gridcell\"\n" +
	  "        id=\"{{::dt.uid}}\"\n" +
	  "        ng-class=\"::dt.customClass\">\n" +
	  "        <button type=\"button\" class=\"btn btn-default btn-sm\"\n" +
	  "          uib-is-class=\"\n" +
	  "            'btn-info' for selectedDt,\n" +
	  "            'active' for activeDt\n" +
	  "            on dt\"\n" +
	  "          ng-click=\"select(dt.date)\"\n" +
	  "          ng-disabled=\"::dt.disabled\"\n" +
	  "          tabindex=\"-1\"><span ng-class=\"::{'text-muted': dt.secondary, 'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
	  "      </td>\n" +
	  "    </tr>\n" +
	  "  </tbody>\n" +
	  "</table>\n" +
	  "");
}]);

angular.module("uib/template/datepicker/month.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/datepicker/month.html",
	  "<table role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
	  "  <thead>\n" +
	  "    <tr>\n" +
	  "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left uib-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-left\"></i><span class=\"sr-only\">previous</span></button></th>\n" +
	  "      <th colspan=\"{{::yearHeaderColspan}}\"><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm uib-title\" ng-click=\"toggleMode()\" ng-disabled=\"datepickerMode === maxMode\" tabindex=\"-1\"><strong>{{title}}</strong></button></th>\n" +
	  "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right uib-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-right\"></i><span class=\"sr-only\">next</span></i></button></th>\n" +
	  "    </tr>\n" +
	  "  </thead>\n" +
	  "  <tbody>\n" +
	  "    <tr class=\"uib-months\" ng-repeat=\"row in rows track by $index\" role=\"row\">\n" +
	  "      <td ng-repeat=\"dt in row\" class=\"uib-month text-center\" role=\"gridcell\"\n" +
	  "        id=\"{{::dt.uid}}\"\n" +
	  "        ng-class=\"::dt.customClass\">\n" +
	  "        <button type=\"button\" class=\"btn btn-default\"\n" +
	  "          uib-is-class=\"\n" +
	  "            'btn-info' for selectedDt,\n" +
	  "            'active' for activeDt\n" +
	  "            on dt\"\n" +
	  "          ng-click=\"select(dt.date)\"\n" +
	  "          ng-disabled=\"::dt.disabled\"\n" +
	  "          tabindex=\"-1\"><span ng-class=\"::{'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
	  "      </td>\n" +
	  "    </tr>\n" +
	  "  </tbody>\n" +
	  "</table>\n" +
	  "");
}]);

angular.module("uib/template/datepicker/year.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/datepicker/year.html",
	  "<table role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
	  "  <thead>\n" +
	  "    <tr>\n" +
	  "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left uib-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-left\"></i><span class=\"sr-only\">previous</span></button></th>\n" +
	  "      <th colspan=\"{{::columns - 2}}\"><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm uib-title\" ng-click=\"toggleMode()\" ng-disabled=\"datepickerMode === maxMode\" tabindex=\"-1\"><strong>{{title}}</strong></button></th>\n" +
	  "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right uib-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-right\"></i><span class=\"sr-only\">next</span></button></th>\n" +
	  "    </tr>\n" +
	  "  </thead>\n" +
	  "  <tbody>\n" +
	  "    <tr class=\"uib-years\" ng-repeat=\"row in rows track by $index\" role=\"row\">\n" +
	  "      <td ng-repeat=\"dt in row\" class=\"uib-year text-center\" role=\"gridcell\"\n" +
	  "        id=\"{{::dt.uid}}\"\n" +
	  "        ng-class=\"::dt.customClass\">\n" +
	  "        <button type=\"button\" class=\"btn btn-default\"\n" +
	  "          uib-is-class=\"\n" +
	  "            'btn-info' for selectedDt,\n" +
	  "            'active' for activeDt\n" +
	  "            on dt\"\n" +
	  "          ng-click=\"select(dt.date)\"\n" +
	  "          ng-disabled=\"::dt.disabled\"\n" +
	  "          tabindex=\"-1\"><span ng-class=\"::{'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
	  "      </td>\n" +
	  "    </tr>\n" +
	  "  </tbody>\n" +
	  "</table>\n" +
	  "");
}]);

angular.module("uib/template/datepickerPopup/popup.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/datepickerPopup/popup.html",
	  "<ul role=\"presentation\" class=\"uib-datepicker-popup dropdown-menu uib-position-measure\" dropdown-nested ng-if=\"isOpen\" ng-keydown=\"keydown($event)\" ng-click=\"$event.stopPropagation()\">\n" +
	  "  <li ng-transclude></li>\n" +
	  "  <li ng-if=\"showButtonBar\" class=\"uib-button-bar\">\n" +
	  "    <span class=\"btn-group pull-left\">\n" +
	  "      <button type=\"button\" class=\"btn btn-sm btn-info uib-datepicker-current\" ng-click=\"select('today', $event)\" ng-disabled=\"isDisabled('today')\">{{ getText('current') }}</button>\n" +
	  "      <button type=\"button\" class=\"btn btn-sm btn-danger uib-clear\" ng-click=\"select(null, $event)\">{{ getText('clear') }}</button>\n" +
	  "    </span>\n" +
	  "    <button type=\"button\" class=\"btn btn-sm btn-success pull-right uib-close\" ng-click=\"close($event)\">{{ getText('close') }}</button>\n" +
	  "  </li>\n" +
	  "</ul>\n" +
	  "");
}]);

angular.module("uib/template/modal/window.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/modal/window.html",
	  "<div class=\"modal-dialog {{size ? 'modal-' + size : ''}}\"><div class=\"modal-content\" uib-modal-transclude></div></div>\n" +
	  "");
}]);

angular.module("uib/template/pager/pager.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/pager/pager.html",
	  "<li ng-class=\"{disabled: noPrevious()||ngDisabled, previous: align}\"><a href ng-click=\"selectPage(page - 1, $event)\" ng-disabled=\"noPrevious()||ngDisabled\" uib-tabindex-toggle>{{::getText('previous')}}</a></li>\n" +
	  "<li ng-class=\"{disabled: noNext()||ngDisabled, next: align}\"><a href ng-click=\"selectPage(page + 1, $event)\" ng-disabled=\"noNext()||ngDisabled\" uib-tabindex-toggle>{{::getText('next')}}</a></li>\n" +
	  "");
}]);

angular.module("uib/template/pagination/pagination.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/pagination/pagination.html",
	  "<li ng-if=\"::boundaryLinks\" ng-class=\"{disabled: noPrevious()||ngDisabled}\" class=\"pagination-first\"><a href ng-click=\"selectPage(1, $event)\" ng-disabled=\"noPrevious()||ngDisabled\" uib-tabindex-toggle>{{::getText('first')}}</a></li>\n" +
	  "<li ng-if=\"::directionLinks\" ng-class=\"{disabled: noPrevious()||ngDisabled}\" class=\"pagination-prev\"><a href ng-click=\"selectPage(page - 1, $event)\" ng-disabled=\"noPrevious()||ngDisabled\" uib-tabindex-toggle>{{::getText('previous')}}</a></li>\n" +
	  "<li ng-repeat=\"page in pages track by $index\" ng-class=\"{active: page.active,disabled: ngDisabled&&!page.active}\" class=\"pagination-page\"><a href ng-click=\"selectPage(page.number, $event)\" ng-disabled=\"ngDisabled&&!page.active\" uib-tabindex-toggle>{{page.text}}</a></li>\n" +
	  "<li ng-if=\"::directionLinks\" ng-class=\"{disabled: noNext()||ngDisabled}\" class=\"pagination-next\"><a href ng-click=\"selectPage(page + 1, $event)\" ng-disabled=\"noNext()||ngDisabled\" uib-tabindex-toggle>{{::getText('next')}}</a></li>\n" +
	  "<li ng-if=\"::boundaryLinks\" ng-class=\"{disabled: noNext()||ngDisabled}\" class=\"pagination-last\"><a href ng-click=\"selectPage(totalPages, $event)\" ng-disabled=\"noNext()||ngDisabled\" uib-tabindex-toggle>{{::getText('last')}}</a></li>\n" +
	  "");
}]);

angular.module("uib/template/tooltip/tooltip-html-popup.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/tooltip/tooltip-html-popup.html",
	  "<div class=\"tooltip-arrow\"></div>\n" +
	  "<div class=\"tooltip-inner\" ng-bind-html=\"contentExp()\"></div>\n" +
	  "");
}]);

angular.module("uib/template/tooltip/tooltip-popup.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/tooltip/tooltip-popup.html",
	  "<div class=\"tooltip-arrow\"></div>\n" +
	  "<div class=\"tooltip-inner\" ng-bind=\"content\"></div>\n" +
	  "");
}]);

angular.module("uib/template/tooltip/tooltip-template-popup.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/tooltip/tooltip-template-popup.html",
	  "<div class=\"tooltip-arrow\"></div>\n" +
	  "<div class=\"tooltip-inner\"\n" +
	  "  uib-tooltip-template-transclude=\"contentExp()\"\n" +
	  "  tooltip-template-transclude-scope=\"originScope()\"></div>\n" +
	  "");
}]);

angular.module("uib/template/popover/popover-html.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/popover/popover-html.html",
	  "<div class=\"arrow\"></div>\n" +
	  "\n" +
	  "<div class=\"popover-inner\">\n" +
	  "    <h3 class=\"popover-title\" ng-bind=\"uibTitle\" ng-if=\"uibTitle\"></h3>\n" +
	  "    <div class=\"popover-content\" ng-bind-html=\"contentExp()\"></div>\n" +
	  "</div>\n" +
	  "");
}]);

angular.module("uib/template/popover/popover-template.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/popover/popover-template.html",
	  "<div class=\"arrow\"></div>\n" +
	  "\n" +
	  "<div class=\"popover-inner\">\n" +
	  "    <h3 class=\"popover-title\" ng-bind=\"uibTitle\" ng-if=\"uibTitle\"></h3>\n" +
	  "    <div class=\"popover-content\"\n" +
	  "      uib-tooltip-template-transclude=\"contentExp()\"\n" +
	  "      tooltip-template-transclude-scope=\"originScope()\"></div>\n" +
	  "</div>\n" +
	  "");
}]);

angular.module("uib/template/popover/popover.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/popover/popover.html",
	  "<div class=\"arrow\"></div>\n" +
	  "\n" +
	  "<div class=\"popover-inner\">\n" +
	  "    <h3 class=\"popover-title\" ng-bind=\"uibTitle\" ng-if=\"uibTitle\"></h3>\n" +
	  "    <div class=\"popover-content\" ng-bind=\"content\"></div>\n" +
	  "</div>\n" +
	  "");
}]);

angular.module("uib/template/progressbar/bar.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/progressbar/bar.html",
	  "<div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" role=\"progressbar\" aria-valuenow=\"{{value}}\" aria-valuemin=\"0\" aria-valuemax=\"{{max}}\" ng-style=\"{width: (percent < 100 ? percent : 100) + '%'}\" aria-valuetext=\"{{percent | number:0}}%\" aria-labelledby=\"{{::title}}\" ng-transclude></div>\n" +
	  "");
}]);

angular.module("uib/template/progressbar/progress.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/progressbar/progress.html",
	  "<div class=\"progress\" ng-transclude aria-labelledby=\"{{::title}}\"></div>");
}]);

angular.module("uib/template/progressbar/progressbar.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/progressbar/progressbar.html",
	  "<div class=\"progress\">\n" +
	  "  <div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" role=\"progressbar\" aria-valuenow=\"{{value}}\" aria-valuemin=\"0\" aria-valuemax=\"{{max}}\" ng-style=\"{width: (percent < 100 ? percent : 100) + '%'}\" aria-valuetext=\"{{percent | number:0}}%\" aria-labelledby=\"{{::title}}\" ng-transclude></div>\n" +
	  "</div>\n" +
	  "");
}]);

angular.module("uib/template/rating/rating.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/rating/rating.html",
	  "<span ng-mouseleave=\"reset()\" ng-keydown=\"onKeydown($event)\" tabindex=\"0\" role=\"slider\" aria-valuemin=\"0\" aria-valuemax=\"{{range.length}}\" aria-valuenow=\"{{value}}\" aria-valuetext=\"{{title}}\">\n" +
	  "    <span ng-repeat-start=\"r in range track by $index\" class=\"sr-only\">({{ $index < value ? '*' : ' ' }})</span>\n" +
	  "    <i ng-repeat-end ng-mouseenter=\"enter($index + 1)\" ng-click=\"rate($index + 1)\" class=\"glyphicon\" ng-class=\"$index < value && (r.stateOn || 'glyphicon-star') || (r.stateOff || 'glyphicon-star-empty')\" ng-attr-title=\"{{r.title}}\"></i>\n" +
	  "</span>\n" +
	  "");
}]);

angular.module("uib/template/tabs/tab.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/tabs/tab.html",
	  "<li ng-class=\"[{active: active, disabled: disabled}, classes]\" class=\"uib-tab nav-item\">\n" +
	  "  <a href ng-click=\"select($event)\" class=\"nav-link\" uib-tab-heading-transclude>{{heading}}</a>\n" +
	  "</li>\n" +
	  "");
}]);

angular.module("uib/template/tabs/tabset.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/tabs/tabset.html",
	  "<div>\n" +
	  "  <ul class=\"nav nav-{{tabset.type || 'tabs'}}\" ng-class=\"{'nav-stacked': vertical, 'nav-justified': justified}\" ng-transclude></ul>\n" +
	  "  <div class=\"tab-content\">\n" +
	  "    <div class=\"tab-pane\"\n" +
	  "         ng-repeat=\"tab in tabset.tabs\"\n" +
	  "         ng-class=\"{active: tabset.active === tab.index}\"\n" +
	  "         uib-tab-content-transclude=\"tab\">\n" +
	  "    </div>\n" +
	  "  </div>\n" +
	  "</div>\n" +
	  "");
}]);

angular.module("uib/template/timepicker/timepicker.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/timepicker/timepicker.html",
	  "<table class=\"uib-timepicker\">\n" +
	  "  <tbody>\n" +
	  "    <tr class=\"text-center\" ng-show=\"::showSpinners\">\n" +
	  "      <td class=\"uib-increment hours\"><a ng-click=\"incrementHours()\" ng-class=\"{disabled: noIncrementHours()}\" class=\"btn btn-link\" ng-disabled=\"noIncrementHours()\" tabindex=\"-1\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
	  "      <td>&nbsp;</td>\n" +
	  "      <td class=\"uib-increment minutes\"><a ng-click=\"incrementMinutes()\" ng-class=\"{disabled: noIncrementMinutes()}\" class=\"btn btn-link\" ng-disabled=\"noIncrementMinutes()\" tabindex=\"-1\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
	  "      <td ng-show=\"showSeconds\">&nbsp;</td>\n" +
	  "      <td ng-show=\"showSeconds\" class=\"uib-increment seconds\"><a ng-click=\"incrementSeconds()\" ng-class=\"{disabled: noIncrementSeconds()}\" class=\"btn btn-link\" ng-disabled=\"noIncrementSeconds()\" tabindex=\"-1\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
	  "      <td ng-show=\"showMeridian\"></td>\n" +
	  "    </tr>\n" +
	  "    <tr>\n" +
	  "      <td class=\"form-group uib-time hours\" ng-class=\"{'has-error': invalidHours}\">\n" +
	  "        <input type=\"text\" placeholder=\"HH\" ng-model=\"hours\" ng-change=\"updateHours()\" class=\"form-control text-center\" ng-readonly=\"::readonlyInput\" maxlength=\"2\" tabindex=\"{{::tabindex}}\" ng-disabled=\"noIncrementHours()\" ng-blur=\"blur()\">\n" +
	  "      </td>\n" +
	  "      <td class=\"uib-separator\">:</td>\n" +
	  "      <td class=\"form-group uib-time minutes\" ng-class=\"{'has-error': invalidMinutes}\">\n" +
	  "        <input type=\"text\" placeholder=\"MM\" ng-model=\"minutes\" ng-change=\"updateMinutes()\" class=\"form-control text-center\" ng-readonly=\"::readonlyInput\" maxlength=\"2\" tabindex=\"{{::tabindex}}\" ng-disabled=\"noIncrementMinutes()\" ng-blur=\"blur()\">\n" +
	  "      </td>\n" +
	  "      <td ng-show=\"showSeconds\" class=\"uib-separator\">:</td>\n" +
	  "      <td class=\"form-group uib-time seconds\" ng-class=\"{'has-error': invalidSeconds}\" ng-show=\"showSeconds\">\n" +
	  "        <input type=\"text\" placeholder=\"SS\" ng-model=\"seconds\" ng-change=\"updateSeconds()\" class=\"form-control text-center\" ng-readonly=\"readonlyInput\" maxlength=\"2\" tabindex=\"{{::tabindex}}\" ng-disabled=\"noIncrementSeconds()\" ng-blur=\"blur()\">\n" +
	  "      </td>\n" +
	  "      <td ng-show=\"showMeridian\" class=\"uib-time am-pm\"><button type=\"button\" ng-class=\"{disabled: noToggleMeridian()}\" class=\"btn btn-default text-center\" ng-click=\"toggleMeridian()\" ng-disabled=\"noToggleMeridian()\" tabindex=\"{{::tabindex}}\">{{meridian}}</button></td>\n" +
	  "    </tr>\n" +
	  "    <tr class=\"text-center\" ng-show=\"::showSpinners\">\n" +
	  "      <td class=\"uib-decrement hours\"><a ng-click=\"decrementHours()\" ng-class=\"{disabled: noDecrementHours()}\" class=\"btn btn-link\" ng-disabled=\"noDecrementHours()\" tabindex=\"-1\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
	  "      <td>&nbsp;</td>\n" +
	  "      <td class=\"uib-decrement minutes\"><a ng-click=\"decrementMinutes()\" ng-class=\"{disabled: noDecrementMinutes()}\" class=\"btn btn-link\" ng-disabled=\"noDecrementMinutes()\" tabindex=\"-1\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
	  "      <td ng-show=\"showSeconds\">&nbsp;</td>\n" +
	  "      <td ng-show=\"showSeconds\" class=\"uib-decrement seconds\"><a ng-click=\"decrementSeconds()\" ng-class=\"{disabled: noDecrementSeconds()}\" class=\"btn btn-link\" ng-disabled=\"noDecrementSeconds()\" tabindex=\"-1\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
	  "      <td ng-show=\"showMeridian\"></td>\n" +
	  "    </tr>\n" +
	  "  </tbody>\n" +
	  "</table>\n" +
	  "");
}]);

angular.module("uib/template/typeahead/typeahead-match.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/typeahead/typeahead-match.html",
	  "<a href\n" +
	  "   tabindex=\"-1\"\n" +
	  "   ng-bind-html=\"match.label | uibTypeaheadHighlight:query\"\n" +
	  "   ng-attr-title=\"{{match.label}}\"></a>\n" +
	  "");
}]);

angular.module("uib/template/typeahead/typeahead-popup.html", []).run(["$templateCache", function ($templateCache) {
	$templateCache.put("uib/template/typeahead/typeahead-popup.html",
	  "<ul class=\"dropdown-menu\" ng-show=\"isOpen() && !moveInProgress\" ng-style=\"{top: position().top+'px', left: position().left+'px'}\" role=\"listbox\" aria-hidden=\"{{!isOpen()}}\">\n" +
	  "    <li class=\"uib-typeahead-match\" ng-repeat=\"match in matches track by $index\" ng-class=\"{active: isActive($index) }\" ng-mouseenter=\"selectActive($index)\" ng-click=\"selectMatch($index, $event)\" role=\"option\" id=\"{{::match.id}}\">\n" +
	  "        <div uib-typeahead-match index=\"$index\" match=\"match\" query=\"query\" template-url=\"templateUrl\"></div>\n" +
	  "    </li>\n" +
	  "</ul>\n" +
	  "");
}]);
angular.module('ui.bootstrap.carousel').run(function () { !angular.$$csp().noInlineStyle && !angular.$$uibCarouselCss && angular.element(document).find('head').prepend('<style type="text/css">.ng-animate.item:not(.left):not(.right){-webkit-transition:0s ease-in-out left;transition:0s ease-in-out left}</style>'); angular.$$uibCarouselCss = true; });
angular.module('ui.bootstrap.datepicker').run(function () { !angular.$$csp().noInlineStyle && !angular.$$uibDatepickerCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-datepicker .uib-title{width:100%;}.uib-day button,.uib-month button,.uib-year button{min-width:100%;}.uib-left,.uib-right{width:100%}</style>'); angular.$$uibDatepickerCss = true; });
angular.module('ui.bootstrap.position').run(function () { !angular.$$csp().noInlineStyle && !angular.$$uibPositionCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-position-measure{display:block !important;visibility:hidden !important;position:absolute !important;top:-9999px !important;left:-9999px !important;}.uib-position-scrollbar-measure{position:absolute !important;top:-9999px !important;width:50px !important;height:50px !important;overflow:scroll !important;}.uib-position-body-scrollbar-measure{overflow:scroll !important;}</style>'); angular.$$uibPositionCss = true; });
angular.module('ui.bootstrap.datepickerPopup').run(function () { !angular.$$csp().noInlineStyle && !angular.$$uibDatepickerpopupCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-datepicker-popup.dropdown-menu{display:block;float:none;margin:0;}.uib-button-bar{padding:10px 9px 2px;}</style>'); angular.$$uibDatepickerpopupCss = true; });
angular.module('ui.bootstrap.tooltip').run(function () { !angular.$$csp().noInlineStyle && !angular.$$uibTooltipCss && angular.element(document).find('head').prepend('<style type="text/css">[uib-tooltip-popup].tooltip.top-left > .tooltip-arrow,[uib-tooltip-popup].tooltip.top-right > .tooltip-arrow,[uib-tooltip-popup].tooltip.bottom-left > .tooltip-arrow,[uib-tooltip-popup].tooltip.bottom-right > .tooltip-arrow,[uib-tooltip-popup].tooltip.left-top > .tooltip-arrow,[uib-tooltip-popup].tooltip.left-bottom > .tooltip-arrow,[uib-tooltip-popup].tooltip.right-top > .tooltip-arrow,[uib-tooltip-popup].tooltip.right-bottom > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.top-left > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.top-right > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.bottom-left > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.bottom-right > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.left-top > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.left-bottom > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.right-top > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.right-bottom > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.top-left > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.top-right > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.bottom-left > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.bottom-right > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.left-top > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.left-bottom > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.right-top > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.right-bottom > .tooltip-arrow,[uib-popover-popup].popover.top-left > .arrow,[uib-popover-popup].popover.top-right > .arrow,[uib-popover-popup].popover.bottom-left > .arrow,[uib-popover-popup].popover.bottom-right > .arrow,[uib-popover-popup].popover.left-top > .arrow,[uib-popover-popup].popover.left-bottom > .arrow,[uib-popover-popup].popover.right-top > .arrow,[uib-popover-popup].popover.right-bottom > .arrow,[uib-popover-html-popup].popover.top-left > .arrow,[uib-popover-html-popup].popover.top-right > .arrow,[uib-popover-html-popup].popover.bottom-left > .arrow,[uib-popover-html-popup].popover.bottom-right > .arrow,[uib-popover-html-popup].popover.left-top > .arrow,[uib-popover-html-popup].popover.left-bottom > .arrow,[uib-popover-html-popup].popover.right-top > .arrow,[uib-popover-html-popup].popover.right-bottom > .arrow,[uib-popover-template-popup].popover.top-left > .arrow,[uib-popover-template-popup].popover.top-right > .arrow,[uib-popover-template-popup].popover.bottom-left > .arrow,[uib-popover-template-popup].popover.bottom-right > .arrow,[uib-popover-template-popup].popover.left-top > .arrow,[uib-popover-template-popup].popover.left-bottom > .arrow,[uib-popover-template-popup].popover.right-top > .arrow,[uib-popover-template-popup].popover.right-bottom > .arrow{top:auto;bottom:auto;left:auto;right:auto;margin:0;}[uib-popover-popup].popover,[uib-popover-html-popup].popover,[uib-popover-template-popup].popover{display:block !important;}</style>'); angular.$$uibTooltipCss = true; });
angular.module('ui.bootstrap.timepicker').run(function () { !angular.$$csp().noInlineStyle && !angular.$$uibTimepickerCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-time input{width:50px;}</style>'); angular.$$uibTimepickerCss = true; });
angular.module('ui.bootstrap.typeahead').run(function () { !angular.$$csp().noInlineStyle && !angular.$$uibTypeaheadCss && angular.element(document).find('head').prepend('<style type="text/css">[uib-typeahead-popup].dropdown-menu{display:block;}</style>'); angular.$$uibTypeaheadCss = true; });;
/**
 * @license AngularJS v1.4.0
 * (c) 2010-2015 Google, Inc. http://angularjs.org
 * License: MIT
 */
(function (window, angular, undefined) {
	'use strict';

	/* jshint ignore:start */
	// this code is in the core, but not in angular-messages.js
	var isArray = angular.isArray;
	var forEach = angular.forEach;
	var isString = angular.isString;
	var jqLite = angular.element;
	/* jshint ignore:end */

	/**
	 * @ngdoc module
	 * @name ngMessages
	 * @description
	 *
	 * The `ngMessages` module provides enhanced support for displaying messages within templates
	 * (typically within forms or when rendering message objects that return key/value data).
	 * Instead of relying on JavaScript code and/or complex ng-if statements within your form template to
	 * show and hide error messages specific to the state of an input field, the `ngMessages` and
	 * `ngMessage` directives are designed to handle the complexity, inheritance and priority
	 * sequencing based on the order of how the messages are defined in the template.
	 *
	 * Currently, the ngMessages module only contains the code for the `ngMessages`, `ngMessagesInclude`
	 * `ngMessage` and `ngMessageExp` directives.
	 *
	 * # Usage
	 * The `ngMessages` directive listens on a key/value collection which is set on the ngMessages attribute.
	 * Since the {@link ngModel ngModel} directive exposes an `$error` object, this error object can be
	 * used with `ngMessages` to display control error messages in an easier way than with just regular angular
	 * template directives.
	 *
	 * ```html
	 * <form name="myForm">
	 *   <label>
	 *     Enter text:
	 *     <input type="text" ng-model="field" name="myField" required minlength="5" />
	 *   </label>
	 *   <div ng-messages="myForm.myField.$error" role="alert">
	 *     <div ng-message="required">You did not enter a field</div>
	 *     <div ng-message="minlength, maxlength">
	 *       Your email must be between 5 and 100 characters long
	 *     </div>
	 *   </div>
	 * </form>
	 * ```
	 *
	 * Now whatever key/value entries are present within the provided object (in this case `$error`) then
	 * the ngMessages directive will render the inner first ngMessage directive (depending if the key values
	 * match the attribute value present on each ngMessage directive). In other words, if your errors
	 * object contains the following data:
	 *
	 * ```javascript
	 * <!-- keep in mind that ngModel automatically sets these error flags -->
	 * myField.$error = { minlength : true, required : false };
	 * ```
	 *
	 * Then the `required` message will be displayed first. When required is false then the `minlength` message
	 * will be displayed right after (since these messages are ordered this way in the template HTML code).
	 * The prioritization of each message is determined by what order they're present in the DOM.
	 * Therefore, instead of having custom JavaScript code determine the priority of what errors are
	 * present before others, the presentation of the errors are handled within the template.
	 *
	 * By default, ngMessages will only display one error at a time. However, if you wish to display all
	 * messages then the `ng-messages-multiple` attribute flag can be used on the element containing the
	 * ngMessages directive to make this happen.
	 *
	 * ```html
	 * <!-- attribute-style usage -->
	 * <div ng-messages="myForm.myField.$error" ng-messages-multiple>...</div>
	 *
	 * <!-- element-style usage -->
	 * <ng-messages for="myForm.myField.$error" multiple>...</ng-messages>
	 * ```
	 *
	 * ## Reusing and Overriding Messages
	 * In addition to prioritization, ngMessages also allows for including messages from a remote or an inline
	 * template. This allows for generic collection of messages to be reused across multiple parts of an
	 * application.
	 *
	 * ```html
	 * <script type="text/ng-template" id="error-messages">
	 *   <div ng-message="required">This field is required</div>
	 *   <div ng-message="minlength">This field is too short</div>
	 * </script>
	 *
	 * <div ng-messages="myForm.myField.$error" role="alert">
	 *   <div ng-messages-include="error-messages"></div>
	 * </div>
	 * ```
	 *
	 * However, including generic messages may not be useful enough to match all input fields, therefore,
	 * `ngMessages` provides the ability to override messages defined in the remote template by redefining
	 * them within the directive container.
	 *
	 * ```html
	 * <!-- a generic template of error messages known as "my-custom-messages" -->
	 * <script type="text/ng-template" id="my-custom-messages">
	 *   <div ng-message="required">This field is required</div>
	 *   <div ng-message="minlength">This field is too short</div>
	 * </script>
	 *
	 * <form name="myForm">
	 *   <label>
	 *     Email address
	 *     <input type="email"
	 *            id="email"
	 *            name="myEmail"
	 *            ng-model="email"
	 *            minlength="5"
	 *            required />
	 *   </label>
	 *   <!-- any ng-message elements that appear BEFORE the ng-messages-include will
	 *        override the messages present in the ng-messages-include template -->
	 *   <div ng-messages="myForm.myEmail.$error" role="alert">
	 *     <!-- this required message has overridden the template message -->
	 *     <div ng-message="required">You did not enter your email address</div>
	 *
	 *     <!-- this is a brand new message and will appear last in the prioritization -->
	 *     <div ng-message="email">Your email address is invalid</div>
	 *
	 *     <!-- and here are the generic error messages -->
	 *     <div ng-messages-include="my-custom-messages"></div>
	 *   </div>
	 * </form>
	 * ```
	 *
	 * In the example HTML code above the message that is set on required will override the corresponding
	 * required message defined within the remote template. Therefore, with particular input fields (such
	 * email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied
	 * while more generic messages can be used to handle other, more general input errors.
	 *
	 * ## Dynamic Messaging
	 * ngMessages also supports using expressions to dynamically change key values. Using arrays and
	 * repeaters to list messages is also supported. This means that the code below will be able to
	 * fully adapt itself and display the appropriate message when any of the expression data changes:
	 *
	 * ```html
	 * <form name="myForm">
	 *   <label>
	 *     Email address
	 *     <input type="email"
	 *            name="myEmail"
	 *            ng-model="email"
	 *            minlength="5"
	 *            required />
	 *   </label>
	 *   <div ng-messages="myForm.myEmail.$error" role="alert">
	 *     <div ng-message="required">You did not enter your email address</div>
	 *     <div ng-repeat="errorMessage in errorMessages">
	 *       <!-- use ng-message-exp for a message whose key is given by an expression -->
	 *       <div ng-message-exp="errorMessage.type">{{ errorMessage.text }}</div>
	 *     </div>
	 *   </div>
	 * </form>
	 * ```
	 *
	 * The `errorMessage.type` expression can be a string value or it can be an array so
	 * that multiple errors can be associated with a single error message:
	 *
	 * ```html
	 *   <label>
	 *     Email address
	 *     <input type="email"
	 *            ng-model="data.email"
	 *            name="myEmail"
	 *            ng-minlength="5"
	 *            ng-maxlength="100"
	 *            required />
	 *   </label>
	 *   <div ng-messages="myForm.myEmail.$error" role="alert">
	 *     <div ng-message-exp="'required'">You did not enter your email address</div>
	 *     <div ng-message-exp="['minlength', 'maxlength']">
	 *       Your email must be between 5 and 100 characters long
	 *     </div>
	 *   </div>
	 * ```
	 *
	 * Feel free to use other structural directives such as ng-if and ng-switch to further control
	 * what messages are active and when. Be careful, if you place ng-message on the same element
	 * as these structural directives, Angular may not be able to determine if a message is active
	 * or not. Therefore it is best to place the ng-message on a child element of the structural
	 * directive.
	 *
	 * ```html
	 * <div ng-messages="myForm.myEmail.$error" role="alert">
	 *   <div ng-if="showRequiredError">
	 *     <div ng-message="required">Please enter something</div>
	 *   </div>
	 * </div>
	 * ```
	 *
	 * ## Animations
	 * If the `ngAnimate` module is active within the application then the `ngMessages`, `ngMessage` and
	 * `ngMessageExp` directives will trigger animations whenever any messages are added and removed from
	 * the DOM by the `ngMessages` directive.
	 *
	 * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS
	 * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no
	 * messages present. Therefore, CSS transitions and keyframes as well as JavaScript animations can
	 * hook into the animations whenever these classes are added/removed.
	 *
	 * Let's say that our HTML code for our messages container looks like so:
	 *
	 * ```html
	 * <div ng-messages="myMessages" class="my-messages" role="alert">
	 *   <div ng-message="alert" class="some-message">...</div>
	 *   <div ng-message="fail" class="some-message">...</div>
	 * </div>
	 * ```
	 *
	 * Then the CSS animation code for the message container looks like so:
	 *
	 * ```css
	 * .my-messages {
	 *   transition:1s linear all;
	 * }
	 * .my-messages.ng-active {
	 *   // messages are visible
	 * }
	 * .my-messages.ng-inactive {
	 *   // messages are hidden
	 * }
	 * ```
	 *
	 * Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter
	 * and leave animation is triggered for each particular element bound to the `ngMessage` directive.
	 *
	 * Therefore, the CSS code for the inner messages looks like so:
	 *
	 * ```css
	 * .some-message {
	 *   transition:1s linear all;
	 * }
	 *
	 * .some-message.ng-enter {}
	 * .some-message.ng-enter.ng-enter-active {}
	 *
	 * .some-message.ng-leave {}
	 * .some-message.ng-leave.ng-leave-active {}
	 * ```
	 *
	 * {@link ngAnimate Click here} to learn how to use JavaScript animations or to learn more about ngAnimate.
	 */
	angular.module('ngMessages', [])

	   /**
		* @ngdoc directive
		* @module ngMessages
		* @name ngMessages
		* @restrict AE
		*
		* @description
		* `ngMessages` is a directive that is designed to show and hide messages based on the state
		* of a key/value object that it listens on. The directive itself compliments error message
		* reporting with the `ngModel` $error object (which stores a key/value state of validation errors).
		*
		* `ngMessages` manages the state of internal messages within its container element. The internal
		* messages use the `ngMessage` directive and will be inserted/removed from the page depending
		* on if they're present within the key/value object. By default, only one message will be displayed
		* at a time and this depends on the prioritization of the messages within the template. (This can
		* be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.)
		*
		* A remote template can also be used to promote message reusability and messages can also be
		* overridden.
		*
		* {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.
		*
		* @usage
		* ```html
		* <!-- using attribute directives -->
		* <ANY ng-messages="expression" role="alert">
		*   <ANY ng-message="stringValue">...</ANY>
		*   <ANY ng-message="stringValue1, stringValue2, ...">...</ANY>
		*   <ANY ng-message-exp="expressionValue">...</ANY>
		* </ANY>
		*
		* <!-- or by using element directives -->
		* <ng-messages for="expression" role="alert">
		*   <ng-message when="stringValue">...</ng-message>
		*   <ng-message when="stringValue1, stringValue2, ...">...</ng-message>
		*   <ng-message when-exp="expressionValue">...</ng-message>
		* </ng-messages>
		* ```
		*
		* @param {string} ngMessages an angular expression evaluating to a key/value object
		*                 (this is typically the $error object on an ngModel instance).
		* @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true
		*
		* @example
		* <example name="ngMessages-directive" module="ngMessagesExample"
		*          deps="angular-messages.js"
		*          animations="true" fixBase="true">
		*   <file name="index.html">
		*     <form name="myForm">
		*       <label>
		*         Enter your name:
		*         <input type="text"
		*                name="myName"
		*                ng-model="name"
		*                ng-minlength="5"
		*                ng-maxlength="20"
		*                required />
		*       </label>
		*       <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
		*
		*       <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
		*         <div ng-message="required">You did not enter a field</div>
		*         <div ng-message="minlength">Your field is too short</div>
		*         <div ng-message="maxlength">Your field is too long</div>
		*       </div>
		*     </form>
		*   </file>
		*   <file name="script.js">
		*     angular.module('ngMessagesExample', ['ngMessages']);
		*   </file>
		* </example>
		*/
	   .directive('ngMessages', ['$animate', function ($animate) {
	   	var ACTIVE_CLASS = 'ng-active';
	   	var INACTIVE_CLASS = 'ng-inactive';

	   	return {
	   		require: 'ngMessages',
	   		restrict: 'AE',
	   		controller: ['$element', '$scope', '$attrs', function ($element, $scope, $attrs) {
	   			var ctrl = this;
	   			var latestKey = 0;

	   			var messages = this.messages = {};
	   			var renderLater, cachedCollection;

	   			this.render = function (collection) {
	   				collection = collection || {};

	   				renderLater = false;
	   				cachedCollection = collection;

	   				// this is true if the attribute is empty or if the attribute value is truthy
	   				var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) ||
								   isAttrTruthy($scope, $attrs.multiple);

	   				var unmatchedMessages = [];
	   				var matchedKeys = {};
	   				var messageItem = ctrl.head;
	   				var messageFound = false;
	   				var totalMessages = 0;

	   				// we use != instead of !== to allow for both undefined and null values
	   				while (messageItem != null) {
	   					totalMessages++;
	   					var messageCtrl = messageItem.message;

	   					var messageUsed = false;
	   					if (!messageFound) {
	   						forEach(collection, function (value, key) {
	   							if (!messageUsed && truthy(value) && messageCtrl.test(key)) {
	   								// this is to prevent the same error name from showing up twice
	   								if (matchedKeys[key]) return;
	   								matchedKeys[key] = true;

	   								messageUsed = true;
	   								messageCtrl.attach();
	   							}
	   						});
	   					}

	   					if (messageUsed) {
	   						// unless we want to display multiple messages then we should
	   						// set a flag here to avoid displaying the next message in the list
	   						messageFound = !multiple;
	   					} else {
	   						unmatchedMessages.push(messageCtrl);
	   					}

	   					messageItem = messageItem.next;
	   				}

	   				forEach(unmatchedMessages, function (messageCtrl) {
	   					messageCtrl.detach();
	   				});

	   				unmatchedMessages.length !== totalMessages
					   ? $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS)
					   : $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS);
	   			};

	   			$scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render);

	   			this.reRender = function () {
	   				if (!renderLater) {
	   					renderLater = true;
	   					$scope.$evalAsync(function () {
	   						if (renderLater) {
	   							cachedCollection && ctrl.render(cachedCollection);
	   						}
	   					});
	   				}
	   			};

	   			this.register = function (comment, messageCtrl) {
	   				var nextKey = latestKey.toString();
	   				messages[nextKey] = {
	   					message: messageCtrl
	   				};
	   				insertMessageNode($element[0], comment, nextKey);
	   				comment.$$ngMessageNode = nextKey;
	   				latestKey++;

	   				ctrl.reRender();
	   			};

	   			this.deregister = function (comment) {
	   				var key = comment.$$ngMessageNode;
	   				delete comment.$$ngMessageNode;
	   				removeMessageNode($element[0], comment, key);
	   				delete messages[key];
	   				ctrl.reRender();
	   			};

	   			function findPreviousMessage(parent, comment) {
	   				var prevNode = comment;
	   				var parentLookup = [];
	   				while (prevNode && prevNode !== parent) {
	   					var prevKey = prevNode.$$ngMessageNode;
	   					if (prevKey && prevKey.length) {
	   						return messages[prevKey];
	   					}

	   					// dive deeper into the DOM and examine its children for any ngMessage
	   					// comments that may be in an element that appears deeper in the list
	   					if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) == -1) {
	   						parentLookup.push(prevNode);
	   						prevNode = prevNode.childNodes[prevNode.childNodes.length - 1];
	   					} else {
	   						prevNode = prevNode.previousSibling || prevNode.parentNode;
	   					}
	   				}
	   			}

	   			function insertMessageNode(parent, comment, key) {
	   				var messageNode = messages[key];
	   				if (!ctrl.head) {
	   					ctrl.head = messageNode;
	   				} else {
	   					var match = findPreviousMessage(parent, comment);
	   					if (match) {
	   						messageNode.next = match.next;
	   						match.next = messageNode;
	   					} else {
	   						messageNode.next = ctrl.head;
	   						ctrl.head = messageNode;
	   					}
	   				}
	   			}

	   			function removeMessageNode(parent, comment, key) {
	   				var messageNode = messages[key];

	   				var match = findPreviousMessage(parent, comment);
	   				if (match) {
	   					match.next = messageNode.next;
	   				} else {
	   					ctrl.head = messageNode.next;
	   				}
	   			}
	   		}]
	   	};

	   	function isAttrTruthy(scope, attr) {
	   		return (isString(attr) && attr.length === 0) || //empty attribute
				   truthy(scope.$eval(attr));
	   	}

	   	function truthy(val) {
	   		return isString(val) ? val.length : !!val;
	   	}
	   }])

	   /**
		* @ngdoc directive
		* @name ngMessagesInclude
		* @restrict AE
		* @scope
		*
		* @description
		* `ngMessagesInclude` is a directive with the purpose to import existing ngMessage template
		* code from a remote template and place the downloaded template code into the exact spot
		* that the ngMessagesInclude directive is placed within the ngMessages container. This allows
		* for a series of pre-defined messages to be reused and also allows for the developer to
		* determine what messages are overridden due to the placement of the ngMessagesInclude directive.
		*
		* @usage
		* ```html
		* <!-- using attribute directives -->
		* <ANY ng-messages="expression" role="alert">
		*   <ANY ng-messages-include="remoteTplString">...</ANY>
		* </ANY>
		*
		* <!-- or by using element directives -->
		* <ng-messages for="expression" role="alert">
		*   <ng-messages-include src="expressionValue1">...</ng-messages-include>
		* </ng-messages>
		* ```
		*
		* {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.
		*
		* @param {string} ngMessagesInclude|src a string value corresponding to the remote template.
		*/
	   .directive('ngMessagesInclude',
		 ['$templateRequest', '$document', '$compile', function ($templateRequest, $document, $compile) {

		 	return {
		 		restrict: 'AE',
		 		require: '^^ngMessages', // we only require this for validation sake
		 		link: function ($scope, element, attrs) {
		 			var src = attrs.ngMessagesInclude || attrs.src;
		 			$templateRequest(src).then(function (html) {
		 				$compile(html)($scope, function (contents) {
		 					element.after(contents);

		 					// the anchor is placed for debugging purposes
		 					var anchor = jqLite($document[0].createComment(' ngMessagesInclude: ' + src + ' '));
		 					element.after(anchor);

		 					// we don't want to pollute the DOM anymore by keeping an empty directive element
		 					element.remove();
		 				});
		 			});
		 		}
		 	};
		 }])

	   /**
		* @ngdoc directive
		* @name ngMessage
		* @restrict AE
		* @scope
		*
		* @description
		* `ngMessage` is a directive with the purpose to show and hide a particular message.
		* For `ngMessage` to operate, a parent `ngMessages` directive on a parent DOM element
		* must be situated since it determines which messages are visible based on the state
		* of the provided key/value map that `ngMessages` listens on.
		*
		* More information about using `ngMessage` can be found in the
		* {@link module:ngMessages `ngMessages` module documentation}.
		*
		* @usage
		* ```html
		* <!-- using attribute directives -->
		* <ANY ng-messages="expression" role="alert">
		*   <ANY ng-message="stringValue">...</ANY>
		*   <ANY ng-message="stringValue1, stringValue2, ...">...</ANY>
		* </ANY>
		*
		* <!-- or by using element directives -->
		* <ng-messages for="expression" role="alert">
		*   <ng-message when="stringValue">...</ng-message>
		*   <ng-message when="stringValue1, stringValue2, ...">...</ng-message>
		* </ng-messages>
		* ```
		*
		* @param {expression} ngMessage|when a string value corresponding to the message key.
		*/
	  .directive('ngMessage', ngMessageDirectiveFactory('AE'))


	   /**
		* @ngdoc directive
		* @name ngMessageExp
		* @restrict AE
		* @scope
		*
		* @description
		* `ngMessageExp` is a directive with the purpose to show and hide a particular message.
		* For `ngMessageExp` to operate, a parent `ngMessages` directive on a parent DOM element
		* must be situated since it determines which messages are visible based on the state
		* of the provided key/value map that `ngMessages` listens on.
		*
		* @usage
		* ```html
		* <!-- using attribute directives -->
		* <ANY ng-messages="expression">
		*   <ANY ng-message-exp="expressionValue">...</ANY>
		* </ANY>
		*
		* <!-- or by using element directives -->
		* <ng-messages for="expression">
		*   <ng-message when-exp="expressionValue">...</ng-message>
		* </ng-messages>
		* ```
		*
		* {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.
		*
		* @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key.
		*/
	  .directive('ngMessageExp', ngMessageDirectiveFactory('A'));

	function ngMessageDirectiveFactory(restrict) {
		return ['$animate', function ($animate) {
			return {
				restrict: 'AE',
				transclude: 'element',
				terminal: true,
				require: '^^ngMessages',
				link: function (scope, element, attrs, ngMessagesCtrl, $transclude) {
					var commentNode = element[0];

					var records;
					var staticExp = attrs.ngMessage || attrs.when;
					var dynamicExp = attrs.ngMessageExp || attrs.whenExp;
					var assignRecords = function (items) {
						records = items
							? (isArray(items)
								  ? items
								  : items.split(/[\s,]+/))
							: null;
						ngMessagesCtrl.reRender();
					};

					if (dynamicExp) {
						assignRecords(scope.$eval(dynamicExp));
						scope.$watchCollection(dynamicExp, assignRecords);
					} else {
						assignRecords(staticExp);
					}

					var currentElement, messageCtrl;
					ngMessagesCtrl.register(commentNode, messageCtrl = {
						test: function (name) {
							return contains(records, name);
						},
						attach: function () {
							if (!currentElement) {
								$transclude(scope, function (elm) {
									$animate.enter(elm, null, element);
									currentElement = elm;

									// in the event that the parent element is destroyed
									// by any other structural directive then it's time
									// to deregister the message from the controller
									currentElement.on('$destroy', function () {
										if (currentElement) {
											ngMessagesCtrl.deregister(commentNode);
											messageCtrl.detach();
										}
									});
								});
							}
						},
						detach: function () {
							if (currentElement) {
								var elm = currentElement;
								currentElement = null;
								$animate.leave(elm);
							}
						}
					});
				}
			};
		}];

		function contains(collection, key) {
			if (collection) {
				return isArray(collection)
					? collection.indexOf(key) >= 0
					: collection.hasOwnProperty(key);
			}
		}
	}


})(window, window.angular);;
/**!
 * AngularJS Ladda directive
 * @author Chungsub Kim <subicura@subicura.com>
 */

/* global Ladda */
/* exported Ladda */
(function (root, factory) {
	'use strict';
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define(['angular', 'ladda'], factory);
	} else if (typeof module !== 'undefined' && typeof module.exports === 'object') {
		// CommonJS support (for us webpack/browserify/ComponentJS folks)
		module.exports = factory(window.angular || require('angular'), require('ladda'));
	} else {
		// in the case of no module loading system
		return factory(root.angular, root.Ladda);
	}
}(this, function (angular, Ladda) {
	'use strict';

	var moduleName = 'angular-ladda';

	angular.module(moduleName, [])
	  .provider('ladda', function () {
	  	var opts = {
	  		'style': 'slide-left'
	  	};
	  	return {
	  		setOption: function (newOpts) {
	  			angular.extend(opts, newOpts);
	  		},
	  		$get: function () {
	  			return opts;
	  		}
	  	};
	  })
	  .directive('ladda', ['ladda', '$timeout', function (laddaOption, $timeout) {
	  	return {
	  		restrict: 'A',
	  		priority: -1,
	  		link: function (scope, element, attrs) {
	  			$timeout(function () {
	  				element.addClass('ladda-button');
	  				if (angular.isUndefined(element.attr('data-style'))) {
	  					element.attr('data-style', laddaOption.style || 'zoom-in');
	  				}
	  				if (angular.isUndefined(element.attr('data-spinner-size')) && laddaOption.spinnerSize) {
	  					element.attr('data-spinner-size', laddaOption.spinnerSize);
	  				}
	  				if (angular.isUndefined(element.attr('data-spinner-color')) && laddaOption.spinnerColor) {
	  					element.attr('data-spinner-color', laddaOption.spinnerColor);
	  				}

	  				// ladda breaks childNode's event property.
	  				// because ladda use innerHTML instead of append node
	  				if (!element[0].querySelector('.ladda-label')) {
	  					var labelWrapper = document.createElement('span');
	  					labelWrapper.className = 'ladda-label';
	  					angular.element(labelWrapper).append(element.contents());
	  					element.append(labelWrapper);
	  				}

	  				// create ladda button
	  				var ladda = Ladda.create(element[0]);

	  				// add watch!
	  				scope.$watch(attrs.ladda, function (loading) {
	  					if (!loading && !angular.isNumber(loading)) {
	  						ladda.stop();
	  						// When the button also have the ng-disabled directive it needs to be
	  						// re-evaluated since the disabled attribute is removed by the 'stop' method.
	  						if (attrs.ngDisabled) {
	  							element.attr('disabled', scope.$eval(attrs.ngDisabled));
	  						}
	  						return;
	  					}
	  					if (!ladda.isLoading()) {
	  						ladda.start();
	  					}
	  					if (angular.isNumber(loading)) {
	  						ladda.setProgress(loading);
	  					}
	  				});

	  				// use remove on scope destroy to stop memory leaks 
	  				scope.$on('$destroy', function () {
	  					if (ladda) { // prevent null reference
	  						ladda.remove();
	  					}
	  				});
	  			});
	  		}
	  	};
	  }]);

	return moduleName;
}));;
/*!
 * Bootstrap-select v1.7.4 (http://silviomoreto.github.io/bootstrap-select)
 *
 * Copyright 2013-2015 bootstrap-select
 * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
 */
!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,function(a){!function(a){"use strict";function b(b){var c=[{re:/[\xC0-\xC6]/g,ch:"A"},{re:/[\xE0-\xE6]/g,ch:"a"},{re:/[\xC8-\xCB]/g,ch:"E"},{re:/[\xE8-\xEB]/g,ch:"e"},{re:/[\xCC-\xCF]/g,ch:"I"},{re:/[\xEC-\xEF]/g,ch:"i"},{re:/[\xD2-\xD6]/g,ch:"O"},{re:/[\xF2-\xF6]/g,ch:"o"},{re:/[\xD9-\xDC]/g,ch:"U"},{re:/[\xF9-\xFC]/g,ch:"u"},{re:/[\xC7-\xE7]/g,ch:"c"},{re:/[\xD1]/g,ch:"N"},{re:/[\xF1]/g,ch:"n"}];return a.each(c,function(){b=b.replace(this.re,this.ch)}),b}function c(a){var b={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},c="(?:"+Object.keys(b).join("|")+")",d=new RegExp(c),e=new RegExp(c,"g"),f=null==a?"":""+a;return d.test(f)?f.replace(e,function(a){return b[a]}):f}function d(b,c){var d=arguments,f=b,g=c;[].shift.apply(d);var h,i=this.each(function(){var b=a(this);if(b.is("select")){var c=b.data("selectpicker"),i="object"==typeof f&&f;if(c){if(i)for(var j in i)i.hasOwnProperty(j)&&(c.options[j]=i[j])}else{var k=a.extend({},e.DEFAULTS,a.fn.selectpicker.defaults||{},b.data(),i);k.template=a.extend({},e.DEFAULTS.template,a.fn.selectpicker.defaults?a.fn.selectpicker.defaults.template:{},b.data().template,i.template),b.data("selectpicker",c=new e(this,k,g))}"string"==typeof f&&(h=c[f]instanceof Function?c[f].apply(c,d):c.options[f])}});return"undefined"!=typeof h?h:i}String.prototype.includes||!function(){var a={}.toString,b=function(){try{var a={},b=Object.defineProperty,c=b(a,a,a)&&b}catch(d){}return c}(),c="".indexOf,d=function(b){if(null==this)throw new TypeError;var d=String(this);if(b&&"[object RegExp]"==a.call(b))throw new TypeError;var e=d.length,f=String(b),g=f.length,h=arguments.length>1?arguments[1]:void 0,i=h?Number(h):0;i!=i&&(i=0);var j=Math.min(Math.max(i,0),e);return g+j>e?!1:-1!=c.call(d,f,i)};b?b(String.prototype,"includes",{value:d,configurable:!0,writable:!0}):String.prototype.includes=d}(),String.prototype.startsWith||!function(){var a=function(){try{var a={},b=Object.defineProperty,c=b(a,a,a)&&b}catch(d){}return c}(),b={}.toString,c=function(a){if(null==this)throw new TypeError;var c=String(this);if(a&&"[object RegExp]"==b.call(a))throw new TypeError;var d=c.length,e=String(a),f=e.length,g=arguments.length>1?arguments[1]:void 0,h=g?Number(g):0;h!=h&&(h=0);var i=Math.min(Math.max(h,0),d);if(f+i>d)return!1;for(var j=-1;++j<f;)if(c.charCodeAt(i+j)!=e.charCodeAt(j))return!1;return!0};a?a(String.prototype,"startsWith",{value:c,configurable:!0,writable:!0}):String.prototype.startsWith=c}(),Object.keys||(Object.keys=function(a,b,c){c=[];for(b in a)c.hasOwnProperty.call(a,b)&&c.push(b);return c}),a.fn.triggerNative=function(a){var b,c=this[0];c.dispatchEvent?("function"==typeof Event?b=new Event(a,{bubbles:!0}):(b=document.createEvent("Event"),b.initEvent(a,!0,!1)),c.dispatchEvent(b)):(c.fireEvent&&(b=document.createEventObject(),b.eventType=a,c.fireEvent("on"+a,b)),this.trigger(a))},a.expr[":"].icontains=function(b,c,d){var e=a(b),f=(e.data("tokens")||e.text()).toUpperCase();return f.includes(d[3].toUpperCase())},a.expr[":"].ibegins=function(b,c,d){var e=a(b),f=(e.data("tokens")||e.text()).toUpperCase();return f.startsWith(d[3].toUpperCase())},a.expr[":"].aicontains=function(b,c,d){var e=a(b),f=(e.data("tokens")||e.data("normalizedText")||e.text()).toUpperCase();return f.includes(d[3].toUpperCase())},a.expr[":"].aibegins=function(b,c,d){var e=a(b),f=(e.data("tokens")||e.data("normalizedText")||e.text()).toUpperCase();return f.startsWith(d[3].toUpperCase())};var e=function(b,c,d){d&&(d.stopPropagation(),d.preventDefault()),this.$element=a(b),this.$newElement=null,this.$button=null,this.$menu=null,this.$lis=null,this.options=c,null===this.options.title&&(this.options.title=this.$element.attr("title")),this.val=e.prototype.val,this.render=e.prototype.render,this.refresh=e.prototype.refresh,this.setStyle=e.prototype.setStyle,this.selectAll=e.prototype.selectAll,this.deselectAll=e.prototype.deselectAll,this.destroy=e.prototype.remove,this.remove=e.prototype.remove,this.show=e.prototype.show,this.hide=e.prototype.hide,this.init()};e.VERSION="1.7.2",e.DEFAULTS={noneSelectedText:"Nothing selected",noneResultsText:"No results matched {0}",countSelectedText:function(a,b){return 1==a?"{0} item selected":"{0} items selected"},maxOptionsText:function(a,b){return[1==a?"Limit reached ({n} item max)":"Limit reached ({n} items max)",1==b?"Group limit reached ({n} item max)":"Group limit reached ({n} items max)"]},selectAllText:"Select All",deselectAllText:"Deselect All",doneButton:!1,doneButtonText:"Close",multipleSeparator:", ",styleBase:"btn",style:"btn-default",size:"auto",title:null,selectedTextFormat:"values",width:!1,container:!1,hideDisabled:!1,showSubtext:!1,showIcon:!0,showContent:!0,dropupAuto:!0,header:!1,liveSearch:!1,liveSearchPlaceholder:null,liveSearchNormalize:!1,liveSearchStyle:"contains",actionsBox:!1,iconBase:"glyphicon",tickIcon:"glyphicon-ok",template:{caret:'<span class="caret"></span>'},maxOptions:!1,mobile:!1,selectOnTab:!1,dropdownAlignRight:!1},e.prototype={constructor:e,init:function(){var b=this,c=this.$element.attr("id");this.$element.addClass("bs-select-hidden"),this.liObj={},this.multiple=this.$element.prop("multiple"),this.autofocus=this.$element.prop("autofocus"),this.$newElement=this.createView(),this.$element.after(this.$newElement),this.$button=this.$newElement.children("button"),this.$menu=this.$newElement.children(".dropdown-menu"),this.$menuInner=this.$menu.children(".inner"),this.$searchbox=this.$menu.find("input"),this.options.dropdownAlignRight&&this.$menu.addClass("dropdown-menu-right"),"undefined"!=typeof c&&(this.$button.attr("data-id",c),a('label[for="'+c+'"]').click(function(a){a.preventDefault(),b.$button.focus()})),this.checkDisabled(),this.clickListener(),this.options.liveSearch&&this.liveSearchListener(),this.render(),this.setStyle(),this.setWidth(),this.options.container&&this.selectPosition(),this.$menu.data("this",this),this.$newElement.data("this",this),this.options.mobile&&this.mobile(),this.$newElement.on({"hide.bs.dropdown":function(a){b.$element.trigger("hide.bs.select",a)},"hidden.bs.dropdown":function(a){b.$element.trigger("hidden.bs.select",a)},"show.bs.dropdown":function(a){b.$element.trigger("show.bs.select",a)},"shown.bs.dropdown":function(a){b.$element.trigger("shown.bs.select",a)}}),setTimeout(function(){b.$element.trigger("loaded.bs.select")})},createDropdown:function(){var b=this.multiple?" show-tick":"",d=this.$element.parent().hasClass("input-group")?" input-group-btn":"",e=this.autofocus?" autofocus":"",f=this.options.header?'<div class="popover-title"><button type="button" class="close" aria-hidden="true">&times;</button>'+this.options.header+"</div>":"",g=this.options.liveSearch?'<div class="bs-searchbox"><input type="text" class="form-control" autocomplete="off"'+(null===this.options.liveSearchPlaceholder?"":' placeholder="'+c(this.options.liveSearchPlaceholder)+'"')+"></div>":"",h=this.multiple&&this.options.actionsBox?'<div class="bs-actionsbox"><div class="btn-group btn-group-sm btn-block"><button type="button" class="actions-btn bs-select-all btn btn-default">'+this.options.selectAllText+'</button><button type="button" class="actions-btn bs-deselect-all btn btn-default">'+this.options.deselectAllText+"</button></div></div>":"",i=this.multiple&&this.options.doneButton?'<div class="bs-donebutton"><div class="btn-group btn-block"><button type="button" class="btn btn-sm btn-default">'+this.options.doneButtonText+"</button></div></div>":"",j='<div class="btn-group bootstrap-select'+b+d+'"><button type="button" class="'+this.options.styleBase+' dropdown-toggle" data-toggle="dropdown"'+e+'><span class="filter-option pull-left"></span>&nbsp;<span class="bs-caret">'+this.options.template.caret+'</span></button><div class="dropdown-menu open">'+f+g+h+'<ul class="dropdown-menu inner" role="menu"></ul>'+i+"</div></div>";return a(j)},createView:function(){var a=this.createDropdown(),b=this.createLi();return a.find("ul")[0].innerHTML=b,a},reloadLi:function(){this.destroyLi();var a=this.createLi();this.$menuInner[0].innerHTML=a},destroyLi:function(){this.$menu.find("li").remove()},createLi:function(){var d=this,e=[],f=0,g=document.createElement("option"),h=-1,i=function(a,b,c,d){return"<li"+("undefined"!=typeof c&""!==c?' class="'+c+'"':"")+("undefined"!=typeof b&null!==b?' data-original-index="'+b+'"':"")+("undefined"!=typeof d&null!==d?'data-optgroup="'+d+'"':"")+">"+a+"</li>"},j=function(a,e,f,g){return'<a tabindex="0"'+("undefined"!=typeof e?' class="'+e+'"':"")+("undefined"!=typeof f?' style="'+f+'"':"")+(d.options.liveSearchNormalize?' data-normalized-text="'+b(c(a))+'"':"")+("undefined"!=typeof g||null!==g?' data-tokens="'+g+'"':"")+">"+a+'<span class="'+d.options.iconBase+" "+d.options.tickIcon+' check-mark"></span></a>'};if(this.options.title&&!this.multiple&&(h--,!this.$element.find(".bs-title-option").length)){var k=this.$element[0];g.className="bs-title-option",g.appendChild(document.createTextNode(this.options.title)),g.value="",k.insertBefore(g,k.firstChild),void 0===a(k.options[k.selectedIndex]).attr("selected")&&(g.selected=!0)}return this.$element.find("option").each(function(b){var c=a(this);if(h++,!c.hasClass("bs-title-option")){var g=this.className||"",k=this.style.cssText,l=c.data("content")?c.data("content"):c.html(),m=c.data("tokens")?c.data("tokens"):null,n="undefined"!=typeof c.data("subtext")?'<small class="text-muted">'+c.data("subtext")+"</small>":"",o="undefined"!=typeof c.data("icon")?'<span class="'+d.options.iconBase+" "+c.data("icon")+'"></span> ':"",p=this.disabled||"OPTGROUP"===this.parentElement.tagName&&this.parentElement.disabled;if(""!==o&&p&&(o="<span>"+o+"</span>"),d.options.hideDisabled&&p)return void h--;if(c.data("content")||(l=o+'<span class="text">'+l+n+"</span>"),"OPTGROUP"===this.parentElement.tagName&&c.data("divider")!==!0){var q=" "+this.parentElement.className||"";if(0===c.index()){f+=1;var r=this.parentElement.label,s="undefined"!=typeof c.parent().data("subtext")?'<small class="text-muted">'+c.parent().data("subtext")+"</small>":"",t=c.parent().data("icon")?'<span class="'+d.options.iconBase+" "+c.parent().data("icon")+'"></span> ':"";r=t+'<span class="text">'+r+s+"</span>",0!==b&&e.length>0&&(h++,e.push(i("",null,"divider",f+"div"))),h++,e.push(i(r,null,"dropdown-header"+q,f))}e.push(i(j(l,"opt "+g+q,k,m),b,"",f))}else c.data("divider")===!0?e.push(i("",b,"divider")):c.data("hidden")===!0?e.push(i(j(l,g,k,m),b,"hidden is-hidden")):(this.previousElementSibling&&"OPTGROUP"===this.previousElementSibling.tagName&&(h++,e.push(i("",null,"divider",f+"div"))),e.push(i(j(l,g,k,m),b)));d.liObj[b]=h}}),this.multiple||0!==this.$element.find("option:selected").length||this.options.title||this.$element.find("option").eq(0).prop("selected",!0).attr("selected","selected"),e.join("")},findLis:function(){return null==this.$lis&&(this.$lis=this.$menu.find("li")),this.$lis},render:function(b){var c,d=this;b!==!1&&this.$element.find("option").each(function(a){var b=d.findLis().eq(d.liObj[a]);d.setDisabled(a,this.disabled||"OPTGROUP"===this.parentElement.tagName&&this.parentElement.disabled,b),d.setSelected(a,this.selected,b)}),this.tabIndex();var e=this.$element.find("option").map(function(){if(this.selected){if(d.options.hideDisabled&&(this.disabled||"OPTGROUP"===this.parentElement.tagName&&this.parentElement.disabled))return;var b,c=a(this),e=c.data("icon")&&d.options.showIcon?'<i class="'+d.options.iconBase+" "+c.data("icon")+'"></i> ':"";return b=d.options.showSubtext&&c.data("subtext")&&!d.multiple?' <small class="text-muted">'+c.data("subtext")+"</small>":"","undefined"!=typeof c.attr("title")?c.attr("title"):c.data("content")&&d.options.showContent?c.data("content"):e+c.html()+b}}).toArray(),f=this.multiple?e.join(this.options.multipleSeparator):e[0];if(this.multiple&&this.options.selectedTextFormat.indexOf("count")>-1){var g=this.options.selectedTextFormat.split(">");if(g.length>1&&e.length>g[1]||1==g.length&&e.length>=2){c=this.options.hideDisabled?", [disabled]":"";var h=this.$element.find("option").not('[data-divider="true"], [data-hidden="true"]'+c).length,i="function"==typeof this.options.countSelectedText?this.options.countSelectedText(e.length,h):this.options.countSelectedText;f=i.replace("{0}",e.length.toString()).replace("{1}",h.toString())}}void 0==this.options.title&&(this.options.title=this.$element.attr("title")),"static"==this.options.selectedTextFormat&&(f=this.options.title),f||(f="undefined"!=typeof this.options.title?this.options.title:this.options.noneSelectedText),this.$button.attr("title",a.trim(f.replace(/<[^>]*>?/g,""))),this.$button.children(".filter-option").html(f),this.$element.trigger("rendered.bs.select")},setStyle:function(a,b){this.$element.attr("class")&&this.$newElement.addClass(this.$element.attr("class").replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi,""));var c=a?a:this.options.style;"add"==b?this.$button.addClass(c):"remove"==b?this.$button.removeClass(c):(this.$button.removeClass(this.options.style),this.$button.addClass(c))},liHeight:function(b){if(b||this.options.size!==!1&&!this.sizeInfo){var c=document.createElement("div"),d=document.createElement("div"),e=document.createElement("ul"),f=document.createElement("li"),g=document.createElement("li"),h=document.createElement("a"),i=document.createElement("span"),j=this.options.header?this.$menu.find(".popover-title")[0].cloneNode(!0):null,k=this.options.liveSearch?document.createElement("div"):null,l=this.options.actionsBox&&this.multiple?this.$menu.find(".bs-actionsbox")[0].cloneNode(!0):null,m=this.options.doneButton&&this.multiple?this.$menu.find(".bs-donebutton")[0].cloneNode(!0):null;if(i.className="text",c.className=this.$menu[0].parentNode.className+" open",d.className="dropdown-menu open",e.className="dropdown-menu inner",f.className="divider",i.appendChild(document.createTextNode("Inner text")),h.appendChild(i),g.appendChild(h),e.appendChild(g),e.appendChild(f),j&&d.appendChild(j),k){var n=document.createElement("span");k.className="bs-searchbox",n.className="form-control",k.appendChild(n),d.appendChild(k)}l&&d.appendChild(l),d.appendChild(e),m&&d.appendChild(m),c.appendChild(d),document.body.appendChild(c);var o=h.offsetHeight,p=j?j.offsetHeight:0,q=k?k.offsetHeight:0,r=l?l.offsetHeight:0,s=m?m.offsetHeight:0,t=a(f).outerHeight(!0),u="function"==typeof getComputedStyle?getComputedStyle(d):!1,v=u?null:a(d),w=parseInt(u?u.paddingTop:v.css("paddingTop"))+parseInt(u?u.paddingBottom:v.css("paddingBottom"))+parseInt(u?u.borderTopWidth:v.css("borderTopWidth"))+parseInt(u?u.borderBottomWidth:v.css("borderBottomWidth")),x=w+parseInt(u?u.marginTop:v.css("marginTop"))+parseInt(u?u.marginBottom:v.css("marginBottom"))+2;document.body.removeChild(c),this.sizeInfo={liHeight:o,headerHeight:p,searchHeight:q,actionsHeight:r,doneButtonHeight:s,dividerHeight:t,menuPadding:w,menuExtras:x}}},setSize:function(){if(this.findLis(),this.liHeight(),this.options.header&&this.$menu.css("padding-top",0),this.options.size!==!1){var b,c,d,e,f=this,g=this.$menu,h=this.$menuInner,i=a(window),j=this.$newElement[0].offsetHeight,k=this.sizeInfo.liHeight,l=this.sizeInfo.headerHeight,m=this.sizeInfo.searchHeight,n=this.sizeInfo.actionsHeight,o=this.sizeInfo.doneButtonHeight,p=this.sizeInfo.dividerHeight,q=this.sizeInfo.menuPadding,r=this.sizeInfo.menuExtras,s=this.options.hideDisabled?".disabled":"",t=function(){d=f.$newElement.offset().top-i.scrollTop(),e=i.height()-d-j};if(t(),"auto"===this.options.size){var u=function(){var i,j=function(b,c){return function(d){return c?d.classList?d.classList.contains(b):a(d).hasClass(b):!(d.classList?d.classList.contains(b):a(d).hasClass(b))}},p=f.$menuInner[0].getElementsByTagName("li"),s=Array.prototype.filter?Array.prototype.filter.call(p,j("hidden",!1)):f.$lis.not(".hidden"),u=Array.prototype.filter?Array.prototype.filter.call(s,j("dropdown-header",!0)):s.filter(".dropdown-header");t(),b=e-r,f.options.container?(g.data("height")||g.data("height",g.height()),c=g.data("height")):c=g.height(),f.options.dropupAuto&&f.$newElement.toggleClass("dropup",d>e&&c>b-r),f.$newElement.hasClass("dropup")&&(b=d-r),i=s.length+u.length>3?3*k+r-2:0,g.css({"max-height":b+"px",overflow:"hidden","min-height":i+l+m+n+o+"px"}),h.css({"max-height":b-l-m-n-o-q+"px","overflow-y":"auto","min-height":Math.max(i-q,0)+"px"})};u(),this.$searchbox.off("input.getSize propertychange.getSize").on("input.getSize propertychange.getSize",u),i.off("resize.getSize scroll.getSize").on("resize.getSize scroll.getSize",u)}else if(this.options.size&&"auto"!=this.options.size&&this.$lis.not(s).length>this.options.size){var v=this.$lis.not(".divider").not(s).children().slice(0,this.options.size).last().parent().index(),w=this.$lis.slice(0,v+1).filter(".divider").length;b=k*this.options.size+w*p+q,f.options.container?(g.data("height")||g.data("height",g.height()),c=g.data("height")):c=g.height(),f.options.dropupAuto&&this.$newElement.toggleClass("dropup",d>e&&c>b-r),g.css({"max-height":b+l+m+n+o+"px",overflow:"hidden","min-height":""}),h.css({"max-height":b-q+"px","overflow-y":"auto","min-height":""})}}},setWidth:function(){if("auto"===this.options.width){this.$menu.css("min-width","0");var a=this.$menu.parent().clone().appendTo("body"),b=this.options.container?this.$newElement.clone().appendTo("body"):a,c=a.children(".dropdown-menu").outerWidth(),d=b.css("width","auto").children("button").outerWidth();a.remove(),b.remove(),this.$newElement.css("width",Math.max(c,d)+"px")}else"fit"===this.options.width?(this.$menu.css("min-width",""),this.$newElement.css("width","").addClass("fit-width")):this.options.width?(this.$menu.css("min-width",""),this.$newElement.css("width",this.options.width)):(this.$menu.css("min-width",""),this.$newElement.css("width",""));this.$newElement.hasClass("fit-width")&&"fit"!==this.options.width&&this.$newElement.removeClass("fit-width")},selectPosition:function(){var b,c,d=this,e=a('<div class="bs-container" />'),f=function(a){e.addClass(a.attr("class").replace(/form-control|fit-width/gi,"")).toggleClass("dropup",a.hasClass("dropup")),b=a.offset(),c=a.hasClass("dropup")?0:a[0].offsetHeight,e.css({top:b.top+c,left:b.left,width:a[0].offsetWidth})};this.$newElement.on("click",function(){d.isDisabled()||(f(a(this)),e.appendTo(d.options.container),e.toggleClass("open",!a(this).hasClass("open")),e.append(d.$menu))}),a(window).on("resize scroll",function(){f(d.$newElement)}),this.$element.on("hide.bs.select",function(){d.$menu.data("height",d.$menu.height()),e.detach()})},setSelected:function(a,b,c){if(!c)var c=this.findLis().eq(this.liObj[a]);c.toggleClass("selected",b)},setDisabled:function(a,b,c){if(!c)var c=this.findLis().eq(this.liObj[a]);b?c.addClass("disabled").children("a").attr("href","#").attr("tabindex",-1):c.removeClass("disabled").children("a").removeAttr("href").attr("tabindex",0)},isDisabled:function(){return this.$element[0].disabled},checkDisabled:function(){var a=this;this.isDisabled()?(this.$newElement.addClass("disabled"),this.$button.addClass("disabled").attr("tabindex",-1)):(this.$button.hasClass("disabled")&&(this.$newElement.removeClass("disabled"),this.$button.removeClass("disabled")),-1!=this.$button.attr("tabindex")||this.$element.data("tabindex")||this.$button.removeAttr("tabindex")),this.$button.click(function(){return!a.isDisabled()})},tabIndex:function(){this.$element.is("[tabindex]")&&(this.$element.data("tabindex",this.$element.attr("tabindex")),this.$button.attr("tabindex",this.$element.data("tabindex")))},clickListener:function(){var b=this,c=a(document);this.$newElement.on("touchstart.dropdown",".dropdown-menu",function(a){a.stopPropagation()}),c.data("spaceSelect",!1),this.$button.on("keyup",function(a){/(32)/.test(a.keyCode.toString(10))&&c.data("spaceSelect")&&(a.preventDefault(),c.data("spaceSelect",!1))}),this.$newElement.on("click",function(){b.setSize(),b.$element.on("shown.bs.select",function(){if(b.options.liveSearch||b.multiple){if(!b.multiple){var a=b.liObj[b.$element[0].selectedIndex];if("number"!=typeof a||b.options.size===!1)return;var c=b.$lis.eq(a)[0].offsetTop-b.$menuInner[0].offsetTop;c=c-b.$menuInner[0].offsetHeight/2+b.sizeInfo.liHeight/2,b.$menuInner[0].scrollTop=c}}else b.$menuInner.find(".selected a").focus()})}),this.$menuInner.on("click","li a",function(c){var d=a(this),e=d.parent().data("originalIndex"),f=b.$element.val(),g=b.$element.prop("selectedIndex");if(b.multiple&&c.stopPropagation(),c.preventDefault(),!b.isDisabled()&&!d.parent().hasClass("disabled")){var h=b.$element.find("option"),i=h.eq(e),j=i.prop("selected"),k=i.parent("optgroup"),l=b.options.maxOptions,m=k.data("maxOptions")||!1;if(b.multiple){if(i.prop("selected",!j),b.setSelected(e,!j),d.blur(),l!==!1||m!==!1){var n=l<h.filter(":selected").length,o=m<k.find("option:selected").length;if(l&&n||m&&o)if(l&&1==l)h.prop("selected",!1),i.prop("selected",!0),b.$menuInner.find(".selected").removeClass("selected"),b.setSelected(e,!0);else if(m&&1==m){k.find("option:selected").prop("selected",!1),i.prop("selected",!0);var p=d.parent().data("optgroup");b.$menuInner.find('[data-optgroup="'+p+'"]').removeClass("selected"),b.setSelected(e,!0)}else{var q="function"==typeof b.options.maxOptionsText?b.options.maxOptionsText(l,m):b.options.maxOptionsText,r=q[0].replace("{n}",l),s=q[1].replace("{n}",m),t=a('<div class="notify"></div>');q[2]&&(r=r.replace("{var}",q[2][l>1?0:1]),s=s.replace("{var}",q[2][m>1?0:1])),i.prop("selected",!1),b.$menu.append(t),l&&n&&(t.append(a("<div>"+r+"</div>")),b.$element.trigger("maxReached.bs.select")),m&&o&&(t.append(a("<div>"+s+"</div>")),b.$element.trigger("maxReachedGrp.bs.select")),setTimeout(function(){b.setSelected(e,!1)},10),t.delay(750).fadeOut(300,function(){a(this).remove()})}}}else h.prop("selected",!1),i.prop("selected",!0),b.$menuInner.find(".selected").removeClass("selected"),b.setSelected(e,!0);b.multiple?b.options.liveSearch&&b.$searchbox.focus():b.$button.focus(),(f!=b.$element.val()&&b.multiple||g!=b.$element.prop("selectedIndex")&&!b.multiple)&&(b.$element.triggerNative("change"),b.$element.trigger("changed.bs.select",[e,i.prop("selected"),j]))}}),this.$menu.on("click","li.disabled a, .popover-title, .popover-title :not(.close)",function(c){c.currentTarget==this&&(c.preventDefault(),c.stopPropagation(),b.options.liveSearch&&!a(c.target).hasClass("close")?b.$searchbox.focus():b.$button.focus())}),this.$menuInner.on("click",".divider, .dropdown-header",function(a){a.preventDefault(),a.stopPropagation(),b.options.liveSearch?b.$searchbox.focus():b.$button.focus()}),this.$menu.on("click",".popover-title .close",function(){b.$button.click()}),this.$searchbox.on("click",function(a){a.stopPropagation()}),this.$menu.on("click",".actions-btn",function(c){b.options.liveSearch?b.$searchbox.focus():b.$button.focus(),c.preventDefault(),c.stopPropagation(),a(this).hasClass("bs-select-all")?b.selectAll():b.deselectAll(),b.$element.triggerNative("change")}),this.$element.change(function(){b.render(!1)})},liveSearchListener:function(){var d=this,e=a('<li class="no-results"></li>');this.$newElement.on("click.dropdown.data-api touchstart.dropdown.data-api",function(){d.$menuInner.find(".active").removeClass("active"),d.$searchbox.val()&&(d.$searchbox.val(""),d.$lis.not(".is-hidden").removeClass("hidden"),e.parent().length&&e.remove()),d.multiple||d.$menuInner.find(".selected").addClass("active"),setTimeout(function(){d.$searchbox.focus()},10)}),this.$searchbox.on("click.dropdown.data-api focus.dropdown.data-api touchend.dropdown.data-api",function(a){a.stopPropagation()}),this.$searchbox.on("input propertychange",function(){if(d.$searchbox.val()){var f=d.$lis.not(".is-hidden").removeClass("hidden").children("a");f=d.options.liveSearchNormalize?f.not(":a"+d._searchStyle()+'("'+b(d.$searchbox.val())+'")'):f.not(":"+d._searchStyle()+'("'+d.$searchbox.val()+'")'),f.parent().addClass("hidden"),d.$lis.filter(".dropdown-header").each(function(){var b=a(this),c=b.data("optgroup");0===d.$lis.filter("[data-optgroup="+c+"]").not(b).not(".hidden").length&&(b.addClass("hidden"),d.$lis.filter("[data-optgroup="+c+"div]").addClass("hidden"))});var g=d.$lis.not(".hidden");g.each(function(b){var c=a(this);c.hasClass("divider")&&(c.index()===g.first().index()||c.index()===g.last().index()||g.eq(b+1).hasClass("divider"))&&c.addClass("hidden")}),d.$lis.not(".hidden, .no-results").length?e.parent().length&&e.remove():(e.parent().length&&e.remove(),e.html(d.options.noneResultsText.replace("{0}",'"'+c(d.$searchbox.val())+'"')).show(),d.$menuInner.append(e))}else d.$lis.not(".is-hidden").removeClass("hidden"),e.parent().length&&e.remove();d.$lis.filter(".active").removeClass("active"),d.$searchbox.val()&&d.$lis.not(".hidden, .divider, .dropdown-header").eq(0).addClass("active").children("a").focus(),a(this).focus()})},_searchStyle:function(){var a="icontains";switch(this.options.liveSearchStyle){case"begins":case"startsWith":a="ibegins";break;case"contains":}return a},val:function(a){return"undefined"!=typeof a?(this.$element.val(a),this.render(),this.$element):this.$element.val()},selectAll:function(){this.findLis(),this.$element.find("option:enabled").not("[data-divider], [data-hidden]").prop("selected",!0),this.$lis.not(".divider, .dropdown-header, .disabled, .hidden").addClass("selected"),this.render(!1)},deselectAll:function(){this.findLis(),this.$element.find("option:enabled").not("[data-divider], [data-hidden]").prop("selected",!1),this.$lis.not(".divider, .dropdown-header, .disabled, .hidden").removeClass("selected"),this.render(!1)},keydown:function(c){var d,e,f,g,h,i,j,k,l,m=a(this),n=m.is("input")?m.parent().parent():m.parent(),o=n.data("this"),p=":not(.disabled, .hidden, .dropdown-header, .divider)",q={32:" ",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9"};if(o.options.liveSearch&&(n=m.parent().parent()),o.options.container&&(n=o.$menu),d=a("[role=menu] li",n),l=o.$menu.parent().hasClass("open"),!l&&(c.keyCode>=48&&c.keyCode<=57||c.keyCode>=65&&c.keyCode<=90)&&(o.options.container?o.$newElement.trigger("click"):(o.setSize(),o.$menu.parent().addClass("open"),l=!0),o.$searchbox.focus()),o.options.liveSearch&&(/(^9$|27)/.test(c.keyCode.toString(10))&&l&&0===o.$menu.find(".active").length&&(c.preventDefault(),o.$menu.parent().removeClass("open"),o.options.container&&o.$newElement.removeClass("open"),o.$button.focus()),d=a("[role=menu] li"+p,n),m.val()||/(38|40)/.test(c.keyCode.toString(10))||0===d.filter(".active").length&&(d=o.$menuInner.find("li"),d=o.options.liveSearchNormalize?d.filter(":a"+o._searchStyle()+"("+b(q[c.keyCode])+")"):d.filter(":"+o._searchStyle()+"("+q[c.keyCode]+")"))),d.length){if(/(38|40)/.test(c.keyCode.toString(10)))e=d.index(d.find("a").filter(":focus").parent()),g=d.filter(p).first().index(),h=d.filter(p).last().index(),f=d.eq(e).nextAll(p).eq(0).index(),i=d.eq(e).prevAll(p).eq(0).index(),j=d.eq(f).prevAll(p).eq(0).index(),o.options.liveSearch&&(d.each(function(b){a(this).hasClass("disabled")||a(this).data("index",b)}),e=d.index(d.filter(".active")),g=d.first().data("index"),h=d.last().data("index"),f=d.eq(e).nextAll().eq(0).data("index"),i=d.eq(e).prevAll().eq(0).data("index"),j=d.eq(f).prevAll().eq(0).data("index")),k=m.data("prevIndex"),38==c.keyCode?(o.options.liveSearch&&e--,e!=j&&e>i&&(e=i),g>e&&(e=g),e==k&&(e=h)):40==c.keyCode&&(o.options.liveSearch&&e++,-1==e&&(e=0),e!=j&&f>e&&(e=f),e>h&&(e=h),e==k&&(e=g)),m.data("prevIndex",e),o.options.liveSearch?(c.preventDefault(),m.hasClass("dropdown-toggle")||(d.removeClass("active").eq(e).addClass("active").children("a").focus(),m.focus())):d.eq(e).children("a").focus();else if(!m.is("input")){var r,s,t=[];d.each(function(){a(this).hasClass("disabled")||a.trim(a(this).children("a").text().toLowerCase()).substring(0,1)==q[c.keyCode]&&t.push(a(this).index())}),r=a(document).data("keycount"),r++,a(document).data("keycount",r),s=a.trim(a(":focus").text().toLowerCase()).substring(0,1),s!=q[c.keyCode]?(r=1,a(document).data("keycount",r)):r>=t.length&&(a(document).data("keycount",0),r>t.length&&(r=1)),d.eq(t[r-1]).children("a").focus()}if((/(13|32)/.test(c.keyCode.toString(10))||/(^9$)/.test(c.keyCode.toString(10))&&o.options.selectOnTab)&&l){if(/(32)/.test(c.keyCode.toString(10))||c.preventDefault(),o.options.liveSearch)/(32)/.test(c.keyCode.toString(10))||(o.$menuInner.find(".active a").click(),m.focus());else{var u=a(":focus");u.click(),u.focus(),c.preventDefault(),a(document).data("spaceSelect",!0)}a(document).data("keycount",0)}(/(^9$|27)/.test(c.keyCode.toString(10))&&l&&(o.multiple||o.options.liveSearch)||/(27)/.test(c.keyCode.toString(10))&&!l)&&(o.$menu.parent().removeClass("open"),o.options.container&&o.$newElement.removeClass("open"),o.$button.focus())}},mobile:function(){this.$element.addClass("mobile-device").appendTo(this.$newElement),this.options.container&&this.$menu.hide()},refresh:function(){this.$lis=null,this.liObj={},this.reloadLi(),this.render(),this.checkDisabled(),this.liHeight(!0),this.setStyle(),this.setWidth(),this.$lis&&this.$searchbox.trigger("propertychange"),this.$element.trigger("refreshed.bs.select")},hide:function(){this.$newElement.hide()},show:function(){this.$newElement.show()},remove:function(){this.$newElement.remove(),this.$element.remove()}};var f=a.fn.selectpicker;a.fn.selectpicker=d,a.fn.selectpicker.Constructor=e,a.fn.selectpicker.noConflict=function(){return a.fn.selectpicker=f,this},a(document).data("keycount",0).on("keydown",'.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="menu"], .bs-searchbox input',e.prototype.keydown).on("focusin.modal",'.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="menu"], .bs-searchbox input',function(a){a.stopPropagation()}),a(window).on("load.bs.select.data-api",function(){a(".selectpicker").each(function(){var b=a(this);d.call(b,b.data())})})}(a)});
//# sourceMappingURL=bootstrap-select.js.map;
/*! elasticsearch - v2.1.1 - 2014-04-01
 * http://www.elasticsearch.org/guide/en/elasticsearch/client/javascript-api/current/index.html
 * Copyright (c) 2014 Elasticsearch BV; Licensed Apache 2.0 */
;(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

},{}],2:[function(require,module,exports){


//
// The shims in this file are not fully implemented shims for the ES5
// features, but do work for the particular usecases there is in
// the other modules.
//

var toString = Object.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;

// Array.isArray is supported in IE9
function isArray(xs) {
  return toString.call(xs) === '[object Array]';
}
exports.isArray = typeof Array.isArray === 'function' ? Array.isArray : isArray;

// Array.prototype.indexOf is supported in IE9
exports.indexOf = function indexOf(xs, x) {
  if (xs.indexOf) return xs.indexOf(x);
  for (var i = 0; i < xs.length; i++) {
    if (x === xs[i]) return i;
  }
  return -1;
};

// Array.prototype.filter is supported in IE9
exports.filter = function filter(xs, fn) {
  if (xs.filter) return xs.filter(fn);
  var res = [];
  for (var i = 0; i < xs.length; i++) {
    if (fn(xs[i], i, xs)) res.push(xs[i]);
  }
  return res;
};

// Array.prototype.forEach is supported in IE9
exports.forEach = function forEach(xs, fn, self) {
  if (xs.forEach) return xs.forEach(fn, self);
  for (var i = 0; i < xs.length; i++) {
    fn.call(self, xs[i], i, xs);
  }
};

// Array.prototype.map is supported in IE9
exports.map = function map(xs, fn) {
  if (xs.map) return xs.map(fn);
  var out = new Array(xs.length);
  for (var i = 0; i < xs.length; i++) {
    out[i] = fn(xs[i], i, xs);
  }
  return out;
};

// Array.prototype.reduce is supported in IE9
exports.reduce = function reduce(array, callback, opt_initialValue) {
  if (array.reduce) return array.reduce(callback, opt_initialValue);
  var value, isValueSet = false;

  if (2 < arguments.length) {
    value = opt_initialValue;
    isValueSet = true;
  }
  for (var i = 0, l = array.length; l > i; ++i) {
    if (array.hasOwnProperty(i)) {
      if (isValueSet) {
        value = callback(value, array[i], i, array);
      }
      else {
        value = array[i];
        isValueSet = true;
      }
    }
  }

  return value;
};

// String.prototype.substr - negative index don't work in IE8
if ('ab'.substr(-1) !== 'b') {
  exports.substr = function (str, start, length) {
    // did we get a negative start, calculate how much it is from the beginning of the string
    if (start < 0) start = str.length + start;

    // call the original function
    return str.substr(start, length);
  };
} else {
  exports.substr = function (str, start, length) {
    return str.substr(start, length);
  };
}

// String.prototype.trim is supported in IE9
exports.trim = function (str) {
  if (str.trim) return str.trim();
  return str.replace(/^\s+|\s+$/g, '');
};

// Function.prototype.bind is supported in IE9
exports.bind = function () {
  var args = Array.prototype.slice.call(arguments);
  var fn = args.shift();
  if (fn.bind) return fn.bind.apply(fn, args);
  var self = args.shift();
  return function () {
    fn.apply(self, args.concat([Array.prototype.slice.call(arguments)]));
  };
};

// Object.create is supported in IE9
function create(prototype, properties) {
  var object;
  if (prototype === null) {
    object = { '__proto__' : null };
  }
  else {
    if (typeof prototype !== 'object') {
      throw new TypeError(
        'typeof prototype[' + (typeof prototype) + '] != \'object\''
      );
    }
    var Type = function () {};
    Type.prototype = prototype;
    object = new Type();
    object.__proto__ = prototype;
  }
  if (typeof properties !== 'undefined' && Object.defineProperties) {
    Object.defineProperties(object, properties);
  }
  return object;
}
exports.create = typeof Object.create === 'function' ? Object.create : create;

// Object.keys and Object.getOwnPropertyNames is supported in IE9 however
// they do show a description and number property on Error objects
function notObject(object) {
  return ((typeof object != "object" && typeof object != "function") || object === null);
}

function keysShim(object) {
  if (notObject(object)) {
    throw new TypeError("Object.keys called on a non-object");
  }

  var result = [];
  for (var name in object) {
    if (hasOwnProperty.call(object, name)) {
      result.push(name);
    }
  }
  return result;
}

// getOwnPropertyNames is almost the same as Object.keys one key feature
//  is that it returns hidden properties, since that can't be implemented,
//  this feature gets reduced so it just shows the length property on arrays
function propertyShim(object) {
  if (notObject(object)) {
    throw new TypeError("Object.getOwnPropertyNames called on a non-object");
  }

  var result = keysShim(object);
  if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) {
    result.push('length');
  }
  return result;
}

var keys = typeof Object.keys === 'function' ? Object.keys : keysShim;
var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ?
  Object.getOwnPropertyNames : propertyShim;

if (new Error().hasOwnProperty('description')) {
  var ERROR_PROPERTY_FILTER = function (obj, array) {
    if (toString.call(obj) === '[object Error]') {
      array = exports.filter(array, function (name) {
        return name !== 'description' && name !== 'number' && name !== 'message';
      });
    }
    return array;
  };

  exports.keys = function (object) {
    return ERROR_PROPERTY_FILTER(object, keys(object));
  };
  exports.getOwnPropertyNames = function (object) {
    return ERROR_PROPERTY_FILTER(object, getOwnPropertyNames(object));
  };
} else {
  exports.keys = keys;
  exports.getOwnPropertyNames = getOwnPropertyNames;
}

// Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements
function valueObject(value, key) {
  return { value: value[key] };
}

if (typeof Object.getOwnPropertyDescriptor === 'function') {
  try {
    Object.getOwnPropertyDescriptor({'a': 1}, 'a');
    exports.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  } catch (e) {
    // IE8 dom element issue - use a try catch and default to valueObject
    exports.getOwnPropertyDescriptor = function (value, key) {
      try {
        return Object.getOwnPropertyDescriptor(value, key);
      } catch (e) {
        return valueObject(value, key);
      }
    };
  }
} else {
  exports.getOwnPropertyDescriptor = valueObject;
}

},{}],3:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// UTILITY
var util = require('util');
var shims = require('_shims');
var pSlice = Array.prototype.slice;

// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.

var assert = module.exports = ok;

// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
//                             actual: actual,
//                             expected: expected })

assert.AssertionError = function AssertionError(options) {
  this.name = 'AssertionError';
  this.actual = options.actual;
  this.expected = options.expected;
  this.operator = options.operator;
  this.message = options.message || getMessage(this);
};

// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);

function replacer(key, value) {
  if (util.isUndefined(value)) {
    return '' + value;
  }
  if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) {
    return value.toString();
  }
  if (util.isFunction(value) || util.isRegExp(value)) {
    return value.toString();
  }
  return value;
}

function truncate(s, n) {
  if (util.isString(s)) {
    return s.length < n ? s : s.slice(0, n);
  } else {
    return s;
  }
}

function getMessage(self) {
  return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
         self.operator + ' ' +
         truncate(JSON.stringify(self.expected, replacer), 128);
}

// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.

// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided.  All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.

function fail(actual, expected, message, operator, stackStartFunction) {
  throw new assert.AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: operator,
    stackStartFunction: stackStartFunction
  });
}

// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;

// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.

function ok(value, message) {
  if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;

// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);

assert.equal = function equal(actual, expected, message) {
  if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};

// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);

assert.notEqual = function notEqual(actual, expected, message) {
  if (actual == expected) {
    fail(actual, expected, message, '!=', assert.notEqual);
  }
};

// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);

assert.deepEqual = function deepEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected)) {
    fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  }
};

function _deepEqual(actual, expected) {
  // 7.1. All identical values are equivalent, as determined by ===.
  if (actual === expected) {
    return true;

  } else if (util.isBuffer(actual) && util.isBuffer(expected)) {
    if (actual.length != expected.length) return false;

    for (var i = 0; i < actual.length; i++) {
      if (actual[i] !== expected[i]) return false;
    }

    return true;

  // 7.2. If the expected value is a Date object, the actual value is
  // equivalent if it is also a Date object that refers to the same time.
  } else if (util.isDate(actual) && util.isDate(expected)) {
    return actual.getTime() === expected.getTime();

  // 7.3 If the expected value is a RegExp object, the actual value is
  // equivalent if it is also a RegExp object with the same source and
  // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
    return actual.source === expected.source &&
           actual.global === expected.global &&
           actual.multiline === expected.multiline &&
           actual.lastIndex === expected.lastIndex &&
           actual.ignoreCase === expected.ignoreCase;

  // 7.4. Other pairs that do not both pass typeof value == 'object',
  // equivalence is determined by ==.
  } else if (!util.isObject(actual) && !util.isObject(expected)) {
    return actual == expected;

  // 7.5 For all other Object pairs, including Array objects, equivalence is
  // determined by having the same number of owned properties (as verified
  // with Object.prototype.hasOwnProperty.call), the same set of keys
  // (although not necessarily the same order), equivalent values for every
  // corresponding key, and an identical 'prototype' property. Note: this
  // accounts for both named and indexed properties on Arrays.
  } else {
    return objEquiv(actual, expected);
  }
}

function isArguments(object) {
  return Object.prototype.toString.call(object) == '[object Arguments]';
}

function objEquiv(a, b) {
  if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
    return false;
  // an identical 'prototype' property.
  if (a.prototype !== b.prototype) return false;
  //~~~I've managed to break Object.keys through screwy arguments passing.
  //   Converting to array solves the problem.
  if (isArguments(a)) {
    if (!isArguments(b)) {
      return false;
    }
    a = pSlice.call(a);
    b = pSlice.call(b);
    return _deepEqual(a, b);
  }
  try {
    var ka = shims.keys(a),
        kb = shims.keys(b),
        key, i;
  } catch (e) {//happens when one is a string literal and the other isn't
    return false;
  }
  // having the same number of owned properties (keys incorporates
  // hasOwnProperty)
  if (ka.length != kb.length)
    return false;
  //the same set of keys (although not necessarily the same order),
  ka.sort();
  kb.sort();
  //~~~cheap key test
  for (i = ka.length - 1; i >= 0; i--) {
    if (ka[i] != kb[i])
      return false;
  }
  //equivalent values for every corresponding key, and
  //~~~possibly expensive deep test
  for (i = ka.length - 1; i >= 0; i--) {
    key = ka[i];
    if (!_deepEqual(a[key], b[key])) return false;
  }
  return true;
}

// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);

assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  if (_deepEqual(actual, expected)) {
    fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  }
};

// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);

assert.strictEqual = function strictEqual(actual, expected, message) {
  if (actual !== expected) {
    fail(actual, expected, message, '===', assert.strictEqual);
  }
};

// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==.  assert.notStrictEqual(actual, expected, message_opt);

assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (actual === expected) {
    fail(actual, expected, message, '!==', assert.notStrictEqual);
  }
};

function expectedException(actual, expected) {
  if (!actual || !expected) {
    return false;
  }

  if (Object.prototype.toString.call(expected) == '[object RegExp]') {
    return expected.test(actual);
  } else if (actual instanceof expected) {
    return true;
  } else if (expected.call({}, actual) === true) {
    return true;
  }

  return false;
}

function _throws(shouldThrow, block, expected, message) {
  var actual;

  if (util.isString(expected)) {
    message = expected;
    expected = null;
  }

  try {
    block();
  } catch (e) {
    actual = e;
  }

  message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
            (message ? ' ' + message : '.');

  if (shouldThrow && !actual) {
    fail(actual, expected, 'Missing expected exception' + message);
  }

  if (!shouldThrow && expectedException(actual, expected)) {
    fail(actual, expected, 'Got unwanted exception' + message);
  }

  if ((shouldThrow && actual && expected &&
      !expectedException(actual, expected)) || (!shouldThrow && actual)) {
    throw actual;
  }
}

// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);

assert.throws = function(block, /*optional*/error, /*optional*/message) {
  _throws.apply(this, [true].concat(pSlice.call(arguments)));
};

// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/message) {
  _throws.apply(this, [false].concat(pSlice.call(arguments)));
};

assert.ifError = function(err) { if (err) {throw err;}};
},{"_shims":2,"util":8}],4:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var util = require('util');

function EventEmitter() {
  this._events = this._events || {};
  this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;

// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;

// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
  if (!util.isNumber(n) || n < 0)
    throw TypeError('n must be a positive number');
  this._maxListeners = n;
  return this;
};

EventEmitter.prototype.emit = function(type) {
  var er, handler, len, args, i, listeners;

  if (!this._events)
    this._events = {};

  // If there is no 'error' event listener then throw.
  if (type === 'error') {
    if (!this._events.error ||
        (util.isObject(this._events.error) && !this._events.error.length)) {
      er = arguments[1];
      if (er instanceof Error) {
        throw er; // Unhandled 'error' event
      } else {
        throw TypeError('Uncaught, unspecified "error" event.');
      }
      return false;
    }
  }

  handler = this._events[type];

  if (util.isUndefined(handler))
    return false;

  if (util.isFunction(handler)) {
    switch (arguments.length) {
      // fast cases
      case 1:
        handler.call(this);
        break;
      case 2:
        handler.call(this, arguments[1]);
        break;
      case 3:
        handler.call(this, arguments[1], arguments[2]);
        break;
      // slower
      default:
        len = arguments.length;
        args = new Array(len - 1);
        for (i = 1; i < len; i++)
          args[i - 1] = arguments[i];
        handler.apply(this, args);
    }
  } else if (util.isObject(handler)) {
    len = arguments.length;
    args = new Array(len - 1);
    for (i = 1; i < len; i++)
      args[i - 1] = arguments[i];

    listeners = handler.slice();
    len = listeners.length;
    for (i = 0; i < len; i++)
      listeners[i].apply(this, args);
  }

  return true;
};

EventEmitter.prototype.addListener = function(type, listener) {
  var m;

  if (!util.isFunction(listener))
    throw TypeError('listener must be a function');

  if (!this._events)
    this._events = {};

  // To avoid recursion in the case that type === "newListener"! Before
  // adding it to the listeners, first emit "newListener".
  if (this._events.newListener)
    this.emit('newListener', type,
              util.isFunction(listener.listener) ?
              listener.listener : listener);

  if (!this._events[type])
    // Optimize the case of one listener. Don't need the extra array object.
    this._events[type] = listener;
  else if (util.isObject(this._events[type]))
    // If we've already got an array, just append.
    this._events[type].push(listener);
  else
    // Adding the second element, need to change to array.
    this._events[type] = [this._events[type], listener];

  // Check for listener leak
  if (util.isObject(this._events[type]) && !this._events[type].warned) {
    var m;
    if (!util.isUndefined(this._maxListeners)) {
      m = this._maxListeners;
    } else {
      m = EventEmitter.defaultMaxListeners;
    }

    if (m && m > 0 && this._events[type].length > m) {
      this._events[type].warned = true;
      console.error('(node) warning: possible EventEmitter memory ' +
                    'leak detected. %d listeners added. ' +
                    'Use emitter.setMaxListeners() to increase limit.',
                    this._events[type].length);
      console.trace();
    }
  }

  return this;
};

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

EventEmitter.prototype.once = function(type, listener) {
  if (!util.isFunction(listener))
    throw TypeError('listener must be a function');

  function g() {
    this.removeListener(type, g);
    listener.apply(this, arguments);
  }

  g.listener = listener;
  this.on(type, g);

  return this;
};

// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
  var list, position, length, i;

  if (!util.isFunction(listener))
    throw TypeError('listener must be a function');

  if (!this._events || !this._events[type])
    return this;

  list = this._events[type];
  length = list.length;
  position = -1;

  if (list === listener ||
      (util.isFunction(list.listener) && list.listener === listener)) {
    delete this._events[type];
    if (this._events.removeListener)
      this.emit('removeListener', type, listener);

  } else if (util.isObject(list)) {
    for (i = length; i-- > 0;) {
      if (list[i] === listener ||
          (list[i].listener && list[i].listener === listener)) {
        position = i;
        break;
      }
    }

    if (position < 0)
      return this;

    if (list.length === 1) {
      list.length = 0;
      delete this._events[type];
    } else {
      list.splice(position, 1);
    }

    if (this._events.removeListener)
      this.emit('removeListener', type, listener);
  }

  return this;
};

EventEmitter.prototype.removeAllListeners = function(type) {
  var key, listeners;

  if (!this._events)
    return this;

  // not listening for removeListener, no need to emit
  if (!this._events.removeListener) {
    if (arguments.length === 0)
      this._events = {};
    else if (this._events[type])
      delete this._events[type];
    return this;
  }

  // emit removeListener for all listeners on all events
  if (arguments.length === 0) {
    for (key in this._events) {
      if (key === 'removeListener') continue;
      this.removeAllListeners(key);
    }
    this.removeAllListeners('removeListener');
    this._events = {};
    return this;
  }

  listeners = this._events[type];

  if (util.isFunction(listeners)) {
    this.removeListener(type, listeners);
  } else {
    // LIFO order
    while (listeners.length)
      this.removeListener(type, listeners[listeners.length - 1]);
  }
  delete this._events[type];

  return this;
};

EventEmitter.prototype.listeners = function(type) {
  var ret;
  if (!this._events || !this._events[type])
    ret = [];
  else if (util.isFunction(this._events[type]))
    ret = [this._events[type]];
  else
    ret = this._events[type].slice();
  return ret;
};

EventEmitter.listenerCount = function(emitter, type) {
  var ret;
  if (!emitter._events || !emitter._events[type])
    ret = 0;
  else if (util.isFunction(emitter._events[type]))
    ret = 1;
  else
    ret = emitter._events[type].length;
  return ret;
};
},{"util":8}],5:[function(require,module,exports){
var process=require("__browserify_process");// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var util = require('util');
var shims = require('_shims');

// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
  // if the path tries to go above the root, `up` ends up > 0
  var up = 0;
  for (var i = parts.length - 1; i >= 0; i--) {
    var last = parts[i];
    if (last === '.') {
      parts.splice(i, 1);
    } else if (last === '..') {
      parts.splice(i, 1);
      up++;
    } else if (up) {
      parts.splice(i, 1);
      up--;
    }
  }

  // if the path is allowed to go above the root, restore leading ..s
  if (allowAboveRoot) {
    for (; up--; up) {
      parts.unshift('..');
    }
  }

  return parts;
}

// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
    /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
  return splitPathRe.exec(filename).slice(1);
};

// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
  var resolvedPath = '',
      resolvedAbsolute = false;

  for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    var path = (i >= 0) ? arguments[i] : process.cwd();

    // Skip empty and invalid entries
    if (!util.isString(path)) {
      throw new TypeError('Arguments to path.resolve must be strings');
    } else if (!path) {
      continue;
    }

    resolvedPath = path + '/' + resolvedPath;
    resolvedAbsolute = path.charAt(0) === '/';
  }

  // At this point the path should be resolved to a full absolute path, but
  // handle relative paths to be safe (might happen when process.cwd() fails)

  // Normalize the path
  resolvedPath = normalizeArray(shims.filter(resolvedPath.split('/'), function(p) {
    return !!p;
  }), !resolvedAbsolute).join('/');

  return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};

// path.normalize(path)
// posix version
exports.normalize = function(path) {
  var isAbsolute = exports.isAbsolute(path),
      trailingSlash = shims.substr(path, -1) === '/';

  // Normalize the path
  path = normalizeArray(shims.filter(path.split('/'), function(p) {
    return !!p;
  }), !isAbsolute).join('/');

  if (!path && !isAbsolute) {
    path = '.';
  }
  if (path && trailingSlash) {
    path += '/';
  }

  return (isAbsolute ? '/' : '') + path;
};

// posix version
exports.isAbsolute = function(path) {
  return path.charAt(0) === '/';
};

// posix version
exports.join = function() {
  var paths = Array.prototype.slice.call(arguments, 0);
  return exports.normalize(shims.filter(paths, function(p, index) {
    if (!util.isString(p)) {
      throw new TypeError('Arguments to path.join must be strings');
    }
    return p;
  }).join('/'));
};


// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
  from = exports.resolve(from).substr(1);
  to = exports.resolve(to).substr(1);

  function trim(arr) {
    var start = 0;
    for (; start < arr.length; start++) {
      if (arr[start] !== '') break;
    }

    var end = arr.length - 1;
    for (; end >= 0; end--) {
      if (arr[end] !== '') break;
    }

    if (start > end) return [];
    return arr.slice(start, end - start + 1);
  }

  var fromParts = trim(from.split('/'));
  var toParts = trim(to.split('/'));

  var length = Math.min(fromParts.length, toParts.length);
  var samePartsLength = length;
  for (var i = 0; i < length; i++) {
    if (fromParts[i] !== toParts[i]) {
      samePartsLength = i;
      break;
    }
  }

  var outputParts = [];
  for (var i = samePartsLength; i < fromParts.length; i++) {
    outputParts.push('..');
  }

  outputParts = outputParts.concat(toParts.slice(samePartsLength));

  return outputParts.join('/');
};

exports.sep = '/';
exports.delimiter = ':';

exports.dirname = function(path) {
  var result = splitPath(path),
      root = result[0],
      dir = result[1];

  if (!root && !dir) {
    // No dirname whatsoever
    return '.';
  }

  if (dir) {
    // It has a dirname, strip trailing slash
    dir = dir.substr(0, dir.length - 1);
  }

  return root + dir;
};


exports.basename = function(path, ext) {
  var f = splitPath(path)[2];
  // : make this comparison case-insensitive on windows?
  if (ext && f.substr(-1 * ext.length) === ext) {
    f = f.substr(0, f.length - ext.length);
  }
  return f;
};


exports.extname = function(path) {
  return splitPath(path)[3];
};

},{"__browserify_process":13,"_shims":2,"util":8}],6:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// Query String Utilities

var QueryString = exports;
var util = require('util');
var shims = require('_shims');
var Buffer = require('buffer').Buffer;

// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}


function charCode(c) {
  return c.charCodeAt(0);
}


// a safe fast alternative to decodeURIComponent
QueryString.unescapeBuffer = function(s, decodeSpaces) {
  var out = new Buffer(s.length);
  var state = 'CHAR'; // states: CHAR, HEX0, HEX1
  var n, m, hexchar;

  for (var inIndex = 0, outIndex = 0; inIndex <= s.length; inIndex++) {
    var c = s.charCodeAt(inIndex);
    switch (state) {
      case 'CHAR':
        switch (c) {
          case charCode('%'):
            n = 0;
            m = 0;
            state = 'HEX0';
            break;
          case charCode('+'):
            if (decodeSpaces) c = charCode(' ');
            // pass thru
          default:
            out[outIndex++] = c;
            break;
        }
        break;

      case 'HEX0':
        state = 'HEX1';
        hexchar = c;
        if (charCode('0') <= c && c <= charCode('9')) {
          n = c - charCode('0');
        } else if (charCode('a') <= c && c <= charCode('f')) {
          n = c - charCode('a') + 10;
        } else if (charCode('A') <= c && c <= charCode('F')) {
          n = c - charCode('A') + 10;
        } else {
          out[outIndex++] = charCode('%');
          out[outIndex++] = c;
          state = 'CHAR';
          break;
        }
        break;

      case 'HEX1':
        state = 'CHAR';
        if (charCode('0') <= c && c <= charCode('9')) {
          m = c - charCode('0');
        } else if (charCode('a') <= c && c <= charCode('f')) {
          m = c - charCode('a') + 10;
        } else if (charCode('A') <= c && c <= charCode('F')) {
          m = c - charCode('A') + 10;
        } else {
          out[outIndex++] = charCode('%');
          out[outIndex++] = hexchar;
          out[outIndex++] = c;
          break;
        }
        out[outIndex++] = 16 * n + m;
        break;
    }
  }

  //  support returning arbitrary buffers.

  return out.slice(0, outIndex - 1);
};


QueryString.unescape = function(s, decodeSpaces) {
  return QueryString.unescapeBuffer(s, decodeSpaces).toString();
};


QueryString.escape = function(str) {
  return encodeURIComponent(str);
};

var stringifyPrimitive = function(v) {
  if (util.isString(v))
    return v;
  if (util.isBoolean(v))
    return v ? 'true' : 'false';
  if (util.isNumber(v))
    return isFinite(v) ? v : '';
  return '';
};


QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) {
  sep = sep || '&';
  eq = eq || '=';
  if (util.isNull(obj)) {
    obj = undefined;
  }

  if (util.isObject(obj)) {
    return shims.map(shims.keys(obj), function(k) {
      var ks = QueryString.escape(stringifyPrimitive(k)) + eq;
      if (util.isArray(obj[k])) {
        return shims.map(obj[k], function(v) {
          return ks + QueryString.escape(stringifyPrimitive(v));
        }).join(sep);
      } else {
        return ks + QueryString.escape(stringifyPrimitive(obj[k]));
      }
    }).join(sep);

  }

  if (!name) return '';
  return QueryString.escape(stringifyPrimitive(name)) + eq +
         QueryString.escape(stringifyPrimitive(obj));
};

// Parse a key=val string.
QueryString.parse = QueryString.decode = function(qs, sep, eq, options) {
  sep = sep || '&';
  eq = eq || '=';
  var obj = {};

  if (!util.isString(qs) || qs.length === 0) {
    return obj;
  }

  var regexp = /\+/g;
  qs = qs.split(sep);

  var maxKeys = 1000;
  if (options && util.isNumber(options.maxKeys)) {
    maxKeys = options.maxKeys;
  }

  var len = qs.length;
  // maxKeys <= 0 means that we should not limit keys count
  if (maxKeys > 0 && len > maxKeys) {
    len = maxKeys;
  }

  for (var i = 0; i < len; ++i) {
    var x = qs[i].replace(regexp, '%20'),
        idx = x.indexOf(eq),
        kstr, vstr, k, v;

    if (idx >= 0) {
      kstr = x.substr(0, idx);
      vstr = x.substr(idx + 1);
    } else {
      kstr = x;
      vstr = '';
    }

    try {
      k = decodeURIComponent(kstr);
      v = decodeURIComponent(vstr);
    } catch (e) {
      k = QueryString.unescape(kstr, true);
      v = QueryString.unescape(vstr, true);
    }

    if (!hasOwnProperty(obj, k)) {
      obj[k] = v;
    } else if (util.isArray(obj[k])) {
      obj[k].push(v);
    } else {
      obj[k] = [obj[k], v];
    }
  }

  return obj;
};
},{"_shims":2,"buffer":10,"util":8}],7:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var punycode = { encode : function (s) { return s } };
var util = require('util');
var shims = require('_shims');

exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;

exports.Url = Url;

function Url() {
  this.protocol = null;
  this.slashes = null;
  this.auth = null;
  this.host = null;
  this.port = null;
  this.hostname = null;
  this.hash = null;
  this.search = null;
  this.query = null;
  this.pathname = null;
  this.path = null;
  this.href = null;
}

// Reference: RFC 3986, RFC 1808, RFC 2396

// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
    portPattern = /:[0-9]*$/,

    // RFC 2396: characters reserved for delimiting URLs.
    // We actually just auto-escape these.
    delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],

    // RFC 2396: characters not allowed for various reasons.
    unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),

    // Allowed by RFCs, but cause of XSS attacks.  Always escape these.
    autoEscape = ['\''].concat(unwise),
    // Characters that are never ever allowed in a hostname.
    // Note that any invalid chars are also handled, but these
    // are the ones that are *expected* to be seen, so we fast-path
    // them.
    nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
    hostEndingChars = ['/', '?', '#'],
    hostnameMaxLen = 255,
    hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
    hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
    // protocols that can allow "unsafe" and "unwise" chars.
    unsafeProtocol = {
      'javascript': true,
      'javascript:': true
    },
    // protocols that never have a hostname.
    hostlessProtocol = {
      'javascript': true,
      'javascript:': true
    },
    // protocols that always contain a // bit.
    slashedProtocol = {
      'http': true,
      'https': true,
      'ftp': true,
      'gopher': true,
      'file': true,
      'http:': true,
      'https:': true,
      'ftp:': true,
      'gopher:': true,
      'file:': true
    },
    querystring = require('querystring');

function urlParse(url, parseQueryString, slashesDenoteHost) {
  if (url && util.isObject(url) && url instanceof Url) return url;

  var u = new Url;
  u.parse(url, parseQueryString, slashesDenoteHost);
  return u;
}

Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  if (!util.isString(url)) {
    throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  }

  var rest = url;

  // trim before proceeding.
  // This is to support parse stuff like "  http://foo.com  \n"
  rest = shims.trim(rest);

  var proto = protocolPattern.exec(rest);
  if (proto) {
    proto = proto[0];
    var lowerProto = proto.toLowerCase();
    this.protocol = lowerProto;
    rest = rest.substr(proto.length);
  }

  // figure out if it's got a host
  // user@server is *always* interpreted as a hostname, and url
  // resolution will treat //foo/bar as host=foo,path=bar because that's
  // how the browser resolves relative URLs.
  if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
    var slashes = rest.substr(0, 2) === '//';
    if (slashes && !(proto && hostlessProtocol[proto])) {
      rest = rest.substr(2);
      this.slashes = true;
    }
  }

  if (!hostlessProtocol[proto] &&
      (slashes || (proto && !slashedProtocol[proto]))) {

    // there's a hostname.
    // the first instance of /, ?, ;, or # ends the host.
    //
    // If there is an @ in the hostname, then non-host chars *are* allowed
    // to the left of the last @ sign, unless some host-ending character
    // comes *before* the @-sign.
    // URLs are obnoxious.
    //
    // ex:
    // http://a@b@c/ => user:a@b host:c
    // http://a@b?@c => user:a host:c path:/?@c

    // v0.12 (isaacs): This is not quite how Chrome does things.
    // Review our test case against browsers more comprehensively.

    // find the first instance of any hostEndingChars
    var hostEnd = -1;
    for (var i = 0; i < hostEndingChars.length; i++) {
      var hec = rest.indexOf(hostEndingChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
        hostEnd = hec;
    }

    // at this point, either we have an explicit point where the
    // auth portion cannot go past, or the last @ char is the decider.
    var auth, atSign;
    if (hostEnd === -1) {
      // atSign can be anywhere.
      atSign = rest.lastIndexOf('@');
    } else {
      // atSign must be in auth portion.
      // http://a@b/c@d => host:b auth:a path:/c@d
      atSign = rest.lastIndexOf('@', hostEnd);
    }

    // Now we have a portion which is definitely the auth.
    // Pull that off.
    if (atSign !== -1) {
      auth = rest.slice(0, atSign);
      rest = rest.slice(atSign + 1);
      this.auth = decodeURIComponent(auth);
    }

    // the host is the remaining to the left of the first non-host char
    hostEnd = -1;
    for (var i = 0; i < nonHostChars.length; i++) {
      var hec = rest.indexOf(nonHostChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
        hostEnd = hec;
    }
    // if we still have not hit it, then the entire thing is a host.
    if (hostEnd === -1)
      hostEnd = rest.length;

    this.host = rest.slice(0, hostEnd);
    rest = rest.slice(hostEnd);

    // pull out port.
    this.parseHost();

    // we've indicated that there is a hostname,
    // so even if it's empty, it has to be present.
    this.hostname = this.hostname || '';

    // if hostname begins with [ and ends with ]
    // assume that it's an IPv6 address.
    var ipv6Hostname = this.hostname[0] === '[' &&
        this.hostname[this.hostname.length - 1] === ']';

    // validate a little.
    if (!ipv6Hostname) {
      var hostparts = this.hostname.split(/\./);
      for (var i = 0, l = hostparts.length; i < l; i++) {
        var part = hostparts[i];
        if (!part) continue;
        if (!part.match(hostnamePartPattern)) {
          var newpart = '';
          for (var j = 0, k = part.length; j < k; j++) {
            if (part.charCodeAt(j) > 127) {
              // we replace non-ASCII char with a temporary placeholder
              // we need this to make sure size of hostname is not
              // broken by replacing non-ASCII by nothing
              newpart += 'x';
            } else {
              newpart += part[j];
            }
          }
          // we test again with ASCII char only
          if (!newpart.match(hostnamePartPattern)) {
            var validParts = hostparts.slice(0, i);
            var notHost = hostparts.slice(i + 1);
            var bit = part.match(hostnamePartStart);
            if (bit) {
              validParts.push(bit[1]);
              notHost.unshift(bit[2]);
            }
            if (notHost.length) {
              rest = '/' + notHost.join('.') + rest;
            }
            this.hostname = validParts.join('.');
            break;
          }
        }
      }
    }

    if (this.hostname.length > hostnameMaxLen) {
      this.hostname = '';
    } else {
      // hostnames are always lower case.
      this.hostname = this.hostname.toLowerCase();
    }

    if (!ipv6Hostname) {
      // IDNA Support: Returns a puny coded representation of "domain".
      // It only converts the part of the domain name that
      // has non ASCII characters. I.e. it dosent matter if
      // you call it with a domain that already is in ASCII.
      var domainArray = this.hostname.split('.');
      var newOut = [];
      for (var i = 0; i < domainArray.length; ++i) {
        var s = domainArray[i];
        newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
            'xn--' + punycode.encode(s) : s);
      }
      this.hostname = newOut.join('.');
    }

    var p = this.port ? ':' + this.port : '';
    var h = this.hostname || '';
    this.host = h + p;
    this.href += this.host;

    // strip [ and ] from the hostname
    // the host field still retains them, though
    if (ipv6Hostname) {
      this.hostname = this.hostname.substr(1, this.hostname.length - 2);
      if (rest[0] !== '/') {
        rest = '/' + rest;
      }
    }
  }

  // now rest is set to the post-host stuff.
  // chop off any delim chars.
  if (!unsafeProtocol[lowerProto]) {

    // First, make 100% sure that any "autoEscape" chars get
    // escaped, even if encodeURIComponent doesn't think they
    // need to be.
    for (var i = 0, l = autoEscape.length; i < l; i++) {
      var ae = autoEscape[i];
      var esc = encodeURIComponent(ae);
      if (esc === ae) {
        esc = escape(ae);
      }
      rest = rest.split(ae).join(esc);
    }
  }


  // chop off from the tail first.
  var hash = rest.indexOf('#');
  if (hash !== -1) {
    // got a fragment string.
    this.hash = rest.substr(hash);
    rest = rest.slice(0, hash);
  }
  var qm = rest.indexOf('?');
  if (qm !== -1) {
    this.search = rest.substr(qm);
    this.query = rest.substr(qm + 1);
    if (parseQueryString) {
      this.query = querystring.parse(this.query);
    }
    rest = rest.slice(0, qm);
  } else if (parseQueryString) {
    // no query string, but parseQueryString still requested
    this.search = '';
    this.query = {};
  }
  if (rest) this.pathname = rest;
  if (slashedProtocol[lowerProto] &&
      this.hostname && !this.pathname) {
    this.pathname = '/';
  }

  //to support http.request
  if (this.pathname || this.search) {
    var p = this.pathname || '';
    var s = this.search || '';
    this.path = p + s;
  }

  // finally, reconstruct the href based on what has been validated.
  this.href = this.format();
  return this;
};

// format a parsed object into a url string
function urlFormat(obj) {
  // ensure it's an object, and not a string url.
  // If it's an obj, this is a no-op.
  // this way, you can call url_format() on strings
  // to clean up potentially wonky urls.
  if (util.isString(obj)) obj = urlParse(obj);
  if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  return obj.format();
}

Url.prototype.format = function() {
  var auth = this.auth || '';
  if (auth) {
    auth = encodeURIComponent(auth);
    auth = auth.replace(/%3A/i, ':');
    auth += '@';
  }

  var protocol = this.protocol || '',
      pathname = this.pathname || '',
      hash = this.hash || '',
      host = false,
      query = '';

  if (this.host) {
    host = auth + this.host;
  } else if (this.hostname) {
    host = auth + (this.hostname.indexOf(':') === -1 ?
        this.hostname :
        '[' + this.hostname + ']');
    if (this.port) {
      host += ':' + this.port;
    }
  }

  if (this.query &&
      util.isObject(this.query) &&
      shims.keys(this.query).length) {
    query = querystring.stringify(this.query);
  }

  var search = this.search || (query && ('?' + query)) || '';

  if (protocol && shims.substr(protocol, -1) !== ':') protocol += ':';

  // only the slashedProtocols get the //.  Not mailto:, xmpp:, etc.
  // unless they had them to begin with.
  if (this.slashes ||
      (!protocol || slashedProtocol[protocol]) && host !== false) {
    host = '//' + (host || '');
    if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  } else if (!host) {
    host = '';
  }

  if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  if (search && search.charAt(0) !== '?') search = '?' + search;

  pathname = pathname.replace(/[?#]/g, function(match) {
    return encodeURIComponent(match);
  });
  search = search.replace('#', '%23');

  return protocol + host + pathname + search + hash;
};

function urlResolve(source, relative) {
  return urlParse(source, false, true).resolve(relative);
}

Url.prototype.resolve = function(relative) {
  return this.resolveObject(urlParse(relative, false, true)).format();
};

function urlResolveObject(source, relative) {
  if (!source) return relative;
  return urlParse(source, false, true).resolveObject(relative);
}

Url.prototype.resolveObject = function(relative) {
  if (util.isString(relative)) {
    var rel = new Url();
    rel.parse(relative, false, true);
    relative = rel;
  }

  var result = new Url();
  shims.forEach(shims.keys(this), function(k) {
    result[k] = this[k];
  }, this);

  // hash is always overridden, no matter what.
  // even href="" will remove it.
  result.hash = relative.hash;

  // if the relative url is empty, then there's nothing left to do here.
  if (relative.href === '') {
    result.href = result.format();
    return result;
  }

  // hrefs like //foo/bar always cut to the protocol.
  if (relative.slashes && !relative.protocol) {
    // take everything except the protocol from relative
    shims.forEach(shims.keys(relative), function(k) {
      if (k !== 'protocol')
        result[k] = relative[k];
    });

    //urlParse appends trailing / to urls like http://www.example.com
    if (slashedProtocol[result.protocol] &&
        result.hostname && !result.pathname) {
      result.path = result.pathname = '/';
    }

    result.href = result.format();
    return result;
  }

  if (relative.protocol && relative.protocol !== result.protocol) {
    // if it's a known url protocol, then changing
    // the protocol does weird things
    // first, if it's not file:, then we MUST have a host,
    // and if there was a path
    // to begin with, then we MUST have a path.
    // if it is file:, then the host is dropped,
    // because that's known to be hostless.
    // anything else is assumed to be absolute.
    if (!slashedProtocol[relative.protocol]) {
      shims.forEach(shims.keys(relative), function(k) {
        result[k] = relative[k];
      });
      result.href = result.format();
      return result;
    }

    result.protocol = relative.protocol;
    if (!relative.host && !hostlessProtocol[relative.protocol]) {
      var relPath = (relative.pathname || '').split('/');
      while (relPath.length && !(relative.host = relPath.shift()));
      if (!relative.host) relative.host = '';
      if (!relative.hostname) relative.hostname = '';
      if (relPath[0] !== '') relPath.unshift('');
      if (relPath.length < 2) relPath.unshift('');
      result.pathname = relPath.join('/');
    } else {
      result.pathname = relative.pathname;
    }
    result.search = relative.search;
    result.query = relative.query;
    result.host = relative.host || '';
    result.auth = relative.auth;
    result.hostname = relative.hostname || relative.host;
    result.port = relative.port;
    // to support http.request
    if (result.pathname || result.search) {
      var p = result.pathname || '';
      var s = result.search || '';
      result.path = p + s;
    }
    result.slashes = result.slashes || relative.slashes;
    result.href = result.format();
    return result;
  }

  var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
      isRelAbs = (
          relative.host ||
          relative.pathname && relative.pathname.charAt(0) === '/'
      ),
      mustEndAbs = (isRelAbs || isSourceAbs ||
                    (result.host && relative.pathname)),
      removeAllDots = mustEndAbs,
      srcPath = result.pathname && result.pathname.split('/') || [],
      relPath = relative.pathname && relative.pathname.split('/') || [],
      psychotic = result.protocol && !slashedProtocol[result.protocol];

  // if the url is a non-slashed url, then relative
  // links like ../.. should be able
  // to crawl up to the hostname, as well.  This is strange.
  // result.protocol has already been set by now.
  // Later on, put the first path part into the host field.
  if (psychotic) {
    result.hostname = '';
    result.port = null;
    if (result.host) {
      if (srcPath[0] === '') srcPath[0] = result.host;
      else srcPath.unshift(result.host);
    }
    result.host = '';
    if (relative.protocol) {
      relative.hostname = null;
      relative.port = null;
      if (relative.host) {
        if (relPath[0] === '') relPath[0] = relative.host;
        else relPath.unshift(relative.host);
      }
      relative.host = null;
    }
    mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  }

  if (isRelAbs) {
    // it's absolute.
    result.host = (relative.host || relative.host === '') ?
                  relative.host : result.host;
    result.hostname = (relative.hostname || relative.hostname === '') ?
                      relative.hostname : result.hostname;
    result.search = relative.search;
    result.query = relative.query;
    srcPath = relPath;
    // fall through to the dot-handling below.
  } else if (relPath.length) {
    // it's relative
    // throw away the existing file, and take the new path instead.
    if (!srcPath) srcPath = [];
    srcPath.pop();
    srcPath = srcPath.concat(relPath);
    result.search = relative.search;
    result.query = relative.query;
  } else if (!util.isNullOrUndefined(relative.search)) {
    // just pull out the search.
    // like href='?foo'.
    // Put this after the other two cases because it simplifies the booleans
    if (psychotic) {
      result.hostname = result.host = srcPath.shift();
      //occationaly the auth can get stuck only in host
      //this especialy happens in cases like
      //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
      var authInHost = result.host && result.host.indexOf('@') > 0 ?
                       result.host.split('@') : false;
      if (authInHost) {
        result.auth = authInHost.shift();
        result.host = result.hostname = authInHost.shift();
      }
    }
    result.search = relative.search;
    result.query = relative.query;
    //to support http.request
    if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
      result.path = (result.pathname ? result.pathname : '') +
                    (result.search ? result.search : '');
    }
    result.href = result.format();
    return result;
  }

  if (!srcPath.length) {
    // no path at all.  easy.
    // we've already handled the other stuff above.
    result.pathname = null;
    //to support http.request
    if (result.search) {
      result.path = '/' + result.search;
    } else {
      result.path = null;
    }
    result.href = result.format();
    return result;
  }

  // if a url ENDs in . or .., then it must get a trailing slash.
  // however, if it ends in anything else non-slashy,
  // then it must NOT get a trailing slash.
  var last = srcPath.slice(-1)[0];
  var hasTrailingSlash = (
      (result.host || relative.host) && (last === '.' || last === '..') ||
      last === '');

  // strip single dots, resolve double dots to parent dir
  // if the path tries to go above the root, `up` ends up > 0
  var up = 0;
  for (var i = srcPath.length; i >= 0; i--) {
    last = srcPath[i];
    if (last == '.') {
      srcPath.splice(i, 1);
    } else if (last === '..') {
      srcPath.splice(i, 1);
      up++;
    } else if (up) {
      srcPath.splice(i, 1);
      up--;
    }
  }

  // if the path is allowed to go above the root, restore leading ..s
  if (!mustEndAbs && !removeAllDots) {
    for (; up--; up) {
      srcPath.unshift('..');
    }
  }

  if (mustEndAbs && srcPath[0] !== '' &&
      (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
    srcPath.unshift('');
  }

  if (hasTrailingSlash && (shims.substr(srcPath.join('/'), -1) !== '/')) {
    srcPath.push('');
  }

  var isAbsolute = srcPath[0] === '' ||
      (srcPath[0] && srcPath[0].charAt(0) === '/');

  // put the host back
  if (psychotic) {
    result.hostname = result.host = isAbsolute ? '' :
                                    srcPath.length ? srcPath.shift() : '';
    //occationaly the auth can get stuck only in host
    //this especialy happens in cases like
    //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
    var authInHost = result.host && result.host.indexOf('@') > 0 ?
                     result.host.split('@') : false;
    if (authInHost) {
      result.auth = authInHost.shift();
      result.host = result.hostname = authInHost.shift();
    }
  }

  mustEndAbs = mustEndAbs || (result.host && srcPath.length);

  if (mustEndAbs && !isAbsolute) {
    srcPath.unshift('');
  }

  if (!srcPath.length) {
    result.pathname = null;
    result.path = null;
  } else {
    result.pathname = srcPath.join('/');
  }

  //to support request.http
  if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
    result.path = (result.pathname ? result.pathname : '') +
                  (result.search ? result.search : '');
  }
  result.auth = relative.auth || result.auth;
  result.slashes = result.slashes || relative.slashes;
  result.href = result.format();
  return result;
};

Url.prototype.parseHost = function() {
  var host = this.host;
  var port = portPattern.exec(host);
  if (port) {
    port = port[0];
    if (port !== ':') {
      this.port = port.substr(1);
    }
    host = host.substr(0, host.length - port.length);
  }
  if (host) this.hostname = host;
};
},{"_shims":2,"querystring":6,"util":8}],8:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var shims = require('_shims');

var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
  if (!isString(f)) {
    var objects = [];
    for (var i = 0; i < arguments.length; i++) {
      objects.push(inspect(arguments[i]));
    }
    return objects.join(' ');
  }

  var i = 1;
  var args = arguments;
  var len = args.length;
  var str = String(f).replace(formatRegExp, function(x) {
    if (x === '%%') return '%';
    if (i >= len) return x;
    switch (x) {
      case '%s': return String(args[i++]);
      case '%d': return Number(args[i++]);
      case '%j':
        try {
          return JSON.stringify(args[i++]);
        } catch (_) {
          return '[Circular]';
        }
      default:
        return x;
    }
  });
  for (var x = args[i]; i < len; x = args[++i]) {
    if (isNull(x) || !isObject(x)) {
      str += ' ' + x;
    } else {
      str += ' ' + inspect(x);
    }
  }
  return str;
};

/**
 * Echos the value of a value. Trys to print the value out
 * in the best way possible given the different types.
 *
 * @param {Object} obj The object to print out.
 * @param {Object} opts Optional options object that alters the output.
 */
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
  // default options
  var ctx = {
    seen: [],
    stylize: stylizeNoColor
  };
  // legacy...
  if (arguments.length >= 3) ctx.depth = arguments[2];
  if (arguments.length >= 4) ctx.colors = arguments[3];
  if (isBoolean(opts)) {
    // legacy...
    ctx.showHidden = opts;
  } else if (opts) {
    // got an "options" object
    exports._extend(ctx, opts);
  }
  // set default options
  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  if (isUndefined(ctx.depth)) ctx.depth = 2;
  if (isUndefined(ctx.colors)) ctx.colors = false;
  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  if (ctx.colors) ctx.stylize = stylizeWithColor;
  return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;


// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
  'bold' : [1, 22],
  'italic' : [3, 23],
  'underline' : [4, 24],
  'inverse' : [7, 27],
  'white' : [37, 39],
  'grey' : [90, 39],
  'black' : [30, 39],
  'blue' : [34, 39],
  'cyan' : [36, 39],
  'green' : [32, 39],
  'magenta' : [35, 39],
  'red' : [31, 39],
  'yellow' : [33, 39]
};

// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
  'special': 'cyan',
  'number': 'yellow',
  'boolean': 'yellow',
  'undefined': 'grey',
  'null': 'bold',
  'string': 'green',
  'date': 'magenta',
  // "name": intentionally not styling
  'regexp': 'red'
};


function stylizeWithColor(str, styleType) {
  var style = inspect.styles[styleType];

  if (style) {
    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
           '\u001b[' + inspect.colors[style][1] + 'm';
  } else {
    return str;
  }
}


function stylizeNoColor(str, styleType) {
  return str;
}


function arrayToHash(array) {
  var hash = {};

  shims.forEach(array, function(val, idx) {
    hash[val] = true;
  });

  return hash;
}


function formatValue(ctx, value, recurseTimes) {
  // Provide a hook for user-specified inspect functions.
  // Check that value is an object with an inspect function on it
  if (ctx.customInspect &&
      value &&
      isFunction(value.inspect) &&
      // Filter out the util module, it's inspect function is special
      value.inspect !== exports.inspect &&
      // Also filter out any prototype objects using the circular check.
      !(value.constructor && value.constructor.prototype === value)) {
    var ret = value.inspect(recurseTimes);
    if (!isString(ret)) {
      ret = formatValue(ctx, ret, recurseTimes);
    }
    return ret;
  }

  // Primitive types cannot have properties
  var primitive = formatPrimitive(ctx, value);
  if (primitive) {
    return primitive;
  }

  // Look up the keys of the object.
  var keys = shims.keys(value);
  var visibleKeys = arrayToHash(keys);

  if (ctx.showHidden) {
    keys = shims.getOwnPropertyNames(value);
  }

  // Some type of object without properties can be shortcutted.
  if (keys.length === 0) {
    if (isFunction(value)) {
      var name = value.name ? ': ' + value.name : '';
      return ctx.stylize('[Function' + name + ']', 'special');
    }
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    }
    if (isDate(value)) {
      return ctx.stylize(Date.prototype.toString.call(value), 'date');
    }
    if (isError(value)) {
      return formatError(value);
    }
  }

  var base = '', array = false, braces = ['{', '}'];

  // Make Array say that they are Array
  if (isArray(value)) {
    array = true;
    braces = ['[', ']'];
  }

  // Make functions say that they are functions
  if (isFunction(value)) {
    var n = value.name ? ': ' + value.name : '';
    base = ' [Function' + n + ']';
  }

  // Make RegExps say that they are RegExps
  if (isRegExp(value)) {
    base = ' ' + RegExp.prototype.toString.call(value);
  }

  // Make dates with properties first say the date
  if (isDate(value)) {
    base = ' ' + Date.prototype.toUTCString.call(value);
  }

  // Make error with message first say the error
  if (isError(value)) {
    base = ' ' + formatError(value);
  }

  if (keys.length === 0 && (!array || value.length == 0)) {
    return braces[0] + base + braces[1];
  }

  if (recurseTimes < 0) {
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    } else {
      return ctx.stylize('[Object]', 'special');
    }
  }

  ctx.seen.push(value);

  var output;
  if (array) {
    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  } else {
    output = keys.map(function(key) {
      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
    });
  }

  ctx.seen.pop();

  return reduceToSingleString(output, base, braces);
}


function formatPrimitive(ctx, value) {
  if (isUndefined(value))
    return ctx.stylize('undefined', 'undefined');
  if (isString(value)) {
    var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                             .replace(/'/g, "\\'")
                                             .replace(/\\"/g, '"') + '\'';
    return ctx.stylize(simple, 'string');
  }
  if (isNumber(value))
    return ctx.stylize('' + value, 'number');
  if (isBoolean(value))
    return ctx.stylize('' + value, 'boolean');
  // For some reason typeof null is "object", so special case here.
  if (isNull(value))
    return ctx.stylize('null', 'null');
}


function formatError(value) {
  return '[' + Error.prototype.toString.call(value) + ']';
}


function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  var output = [];
  for (var i = 0, l = value.length; i < l; ++i) {
    if (hasOwnProperty(value, String(i))) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          String(i), true));
    } else {
      output.push('');
    }
  }

  shims.forEach(keys, function(key) {
    if (!key.match(/^\d+$/)) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          key, true));
    }
  });
  return output;
}


function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  var name, str, desc;
  desc = shims.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  if (desc.get) {
    if (desc.set) {
      str = ctx.stylize('[Getter/Setter]', 'special');
    } else {
      str = ctx.stylize('[Getter]', 'special');
    }
  } else {
    if (desc.set) {
      str = ctx.stylize('[Setter]', 'special');
    }
  }

  if (!hasOwnProperty(visibleKeys, key)) {
    name = '[' + key + ']';
  }
  if (!str) {
    if (shims.indexOf(ctx.seen, desc.value) < 0) {
      if (isNull(recurseTimes)) {
        str = formatValue(ctx, desc.value, null);
      } else {
        str = formatValue(ctx, desc.value, recurseTimes - 1);
      }
      if (str.indexOf('\n') > -1) {
        if (array) {
          str = str.split('\n').map(function(line) {
            return '  ' + line;
          }).join('\n').substr(2);
        } else {
          str = '\n' + str.split('\n').map(function(line) {
            return '   ' + line;
          }).join('\n');
        }
      }
    } else {
      str = ctx.stylize('[Circular]', 'special');
    }
  }
  if (isUndefined(name)) {
    if (array && key.match(/^\d+$/)) {
      return str;
    }
    name = JSON.stringify('' + key);
    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
      name = name.substr(1, name.length - 2);
      name = ctx.stylize(name, 'name');
    } else {
      name = name.replace(/'/g, "\\'")
                 .replace(/\\"/g, '"')
                 .replace(/(^"|"$)/g, "'");
      name = ctx.stylize(name, 'string');
    }
  }

  return name + ': ' + str;
}


function reduceToSingleString(output, base, braces) {
  var numLinesEst = 0;
  var length = shims.reduce(output, function(prev, cur) {
    numLinesEst++;
    if (cur.indexOf('\n') >= 0) numLinesEst++;
    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  }, 0);

  if (length > 60) {
    return braces[0] +
           (base === '' ? '' : base + '\n ') +
           ' ' +
           output.join(',\n  ') +
           ' ' +
           braces[1];
  }

  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}


// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
  return shims.isArray(ar);
}
exports.isArray = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;

function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;

function isRegExp(re) {
  return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg;
}
exports.isObject = isObject;

function isDate(d) {
  return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;

function isError(e) {
  return isObject(e) && objectToString(e) === '[object Error]';
}
exports.isError = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;

function isBuffer(arg) {
  return arg && typeof arg === 'object'
    && typeof arg.copy === 'function'
    && typeof arg.fill === 'function'
    && typeof arg.binarySlice === 'function'
  ;
}
exports.isBuffer = isBuffer;

function objectToString(o) {
  return Object.prototype.toString.call(o);
}


function pad(n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}


var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
              'Oct', 'Nov', 'Dec'];

// 26 Feb 16:19:34
function timestamp() {
  var d = new Date();
  var time = [pad(d.getHours()),
              pad(d.getMinutes()),
              pad(d.getSeconds())].join(':');
  return [d.getDate(), months[d.getMonth()], time].join(' ');
}


// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};


/**
 * Inherit the prototype methods from one constructor into another.
 *
 * The Function.prototype.inherits from lang.js rewritten as a standalone
 * function (not on Function.prototype). NOTE: If this file is to be loaded
 * during bootstrapping this function needs to be rewritten using some native
 * functions as prototype setup using normal JavaScript does not work as
 * expected during bootstrapping (see mirror.js in r114903).
 *
 * @param {function} ctor Constructor function which needs to inherit the
 *     prototype.
 * @param {function} superCtor Constructor function to inherit prototype from.
 */
exports.inherits = function(ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = shims.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
};

exports._extend = function(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || !isObject(add)) return origin;

  var keys = shims.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
};

function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}

},{"_shims":2}],9:[function(require,module,exports){
exports.readIEEE754 = function(buffer, offset, isBE, mLen, nBytes) {
  var e, m,
      eLen = nBytes * 8 - mLen - 1,
      eMax = (1 << eLen) - 1,
      eBias = eMax >> 1,
      nBits = -7,
      i = isBE ? 0 : (nBytes - 1),
      d = isBE ? 1 : -1,
      s = buffer[offset + i];

  i += d;

  e = s & ((1 << (-nBits)) - 1);
  s >>= (-nBits);
  nBits += eLen;
  for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);

  m = e & ((1 << (-nBits)) - 1);
  e >>= (-nBits);
  nBits += mLen;
  for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);

  if (e === 0) {
    e = 1 - eBias;
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity);
  } else {
    m = m + Math.pow(2, mLen);
    e = e - eBias;
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};

exports.writeIEEE754 = function(buffer, value, offset, isBE, mLen, nBytes) {
  var e, m, c,
      eLen = nBytes * 8 - mLen - 1,
      eMax = (1 << eLen) - 1,
      eBias = eMax >> 1,
      rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
      i = isBE ? (nBytes - 1) : 0,
      d = isBE ? -1 : 1,
      s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;

  value = Math.abs(value);

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0;
    e = eMax;
  } else {
    e = Math.floor(Math.log(value) / Math.LN2);
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--;
      c *= 2;
    }
    if (e + eBias >= 1) {
      value += rt / c;
    } else {
      value += rt * Math.pow(2, 1 - eBias);
    }
    if (value * c >= 2) {
      e++;
      c /= 2;
    }

    if (e + eBias >= eMax) {
      m = 0;
      e = eMax;
    } else if (e + eBias >= 1) {
      m = (value * c - 1) * Math.pow(2, mLen);
      e = e + eBias;
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
      e = 0;
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);

  e = (e << mLen) | m;
  eLen += mLen;
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);

  buffer[offset + i - d] |= s * 128;
};

},{}],10:[function(require,module,exports){
var assert;
exports.Buffer = Buffer;
exports.SlowBuffer = Buffer;
Buffer.poolSize = 8192;
exports.INSPECT_MAX_BYTES = 50;

function stringtrim(str) {
  if (str.trim) return str.trim();
  return str.replace(/^\s+|\s+$/g, '');
}

function Buffer(subject, encoding, offset) {
  if(!assert) assert= require('assert');
  if (!(this instanceof Buffer)) {
    return new Buffer(subject, encoding, offset);
  }
  this.parent = this;
  this.offset = 0;

  // Work-around: node's base64 implementation
  // allows for non-padded strings while base64-js
  // does not..
  if (encoding == "base64" && typeof subject == "string") {
    subject = stringtrim(subject);
    while (subject.length % 4 != 0) {
      subject = subject + "="; 
    }
  }

  var type;

  // Are we slicing?
  if (typeof offset === 'number') {
    this.length = coerce(encoding);
    // slicing works, with limitations (no parent tracking/update)
    // check https://github.com/toots/buffer-browserify/issues/19
    for (var i = 0; i < this.length; i++) {
        this[i] = subject.get(i+offset);
    }
  } else {
    // Find the length
    switch (type = typeof subject) {
      case 'number':
        this.length = coerce(subject);
        break;

      case 'string':
        this.length = Buffer.byteLength(subject, encoding);
        break;

      case 'object': // Assume object is an array
        this.length = coerce(subject.length);
        break;

      default:
        throw new Error('First argument needs to be a number, ' +
                        'array or string.');
    }

    // Treat array-ish objects as a byte array.
    if (isArrayIsh(subject)) {
      for (var i = 0; i < this.length; i++) {
        if (subject instanceof Buffer) {
          this[i] = subject.readUInt8(i);
        }
        else {
          this[i] = subject[i];
        }
      }
    } else if (type == 'string') {
      // We are a string
      this.length = this.write(subject, 0, encoding);
    } else if (type === 'number') {
      for (var i = 0; i < this.length; i++) {
        this[i] = 0;
      }
    }
  }
}

Buffer.prototype.get = function get(i) {
  if (i < 0 || i >= this.length) throw new Error('oob');
  return this[i];
};

Buffer.prototype.set = function set(i, v) {
  if (i < 0 || i >= this.length) throw new Error('oob');
  return this[i] = v;
};

Buffer.byteLength = function (str, encoding) {
  switch (encoding || "utf8") {
    case 'hex':
      return str.length / 2;

    case 'utf8':
    case 'utf-8':
      return utf8ToBytes(str).length;

    case 'ascii':
    case 'binary':
      return str.length;

    case 'base64':
      return base64ToBytes(str).length;

    default:
      throw new Error('Unknown encoding');
  }
};

Buffer.prototype.utf8Write = function (string, offset, length) {
  var bytes, pos;
  return Buffer._charsWritten =  blitBuffer(utf8ToBytes(string), this, offset, length);
};

Buffer.prototype.asciiWrite = function (string, offset, length) {
  var bytes, pos;
  return Buffer._charsWritten =  blitBuffer(asciiToBytes(string), this, offset, length);
};

Buffer.prototype.binaryWrite = Buffer.prototype.asciiWrite;

Buffer.prototype.base64Write = function (string, offset, length) {
  var bytes, pos;
  return Buffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length);
};

Buffer.prototype.base64Slice = function (start, end) {
  var bytes = Array.prototype.slice.apply(this, arguments)
  return require("base64-js").fromByteArray(bytes);
};

Buffer.prototype.utf8Slice = function () {
  var bytes = Array.prototype.slice.apply(this, arguments);
  var res = "";
  var tmp = "";
  var i = 0;
  while (i < bytes.length) {
    if (bytes[i] <= 0x7F) {
      res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]);
      tmp = "";
    } else
      tmp += "%" + bytes[i].toString(16);

    i++;
  }

  return res + decodeUtf8Char(tmp);
}

Buffer.prototype.asciiSlice = function () {
  var bytes = Array.prototype.slice.apply(this, arguments);
  var ret = "";
  for (var i = 0; i < bytes.length; i++)
    ret += String.fromCharCode(bytes[i]);
  return ret;
}

Buffer.prototype.binarySlice = Buffer.prototype.asciiSlice;

Buffer.prototype.inspect = function() {
  var out = [],
      len = this.length;
  for (var i = 0; i < len; i++) {
    out[i] = toHex(this[i]);
    if (i == exports.INSPECT_MAX_BYTES) {
      out[i + 1] = '...';
      break;
    }
  }
  return '<Buffer ' + out.join(' ') + '>';
};


Buffer.prototype.hexSlice = function(start, end) {
  var len = this.length;

  if (!start || start < 0) start = 0;
  if (!end || end < 0 || end > len) end = len;

  var out = '';
  for (var i = start; i < end; i++) {
    out += toHex(this[i]);
  }
  return out;
};


Buffer.prototype.toString = function(encoding, start, end) {
  encoding = String(encoding || 'utf8').toLowerCase();
  start = +start || 0;
  if (typeof end == 'undefined') end = this.length;

  // Fastpath empty strings
  if (+end == start) {
    return '';
  }

  switch (encoding) {
    case 'hex':
      return this.hexSlice(start, end);

    case 'utf8':
    case 'utf-8':
      return this.utf8Slice(start, end);

    case 'ascii':
      return this.asciiSlice(start, end);

    case 'binary':
      return this.binarySlice(start, end);

    case 'base64':
      return this.base64Slice(start, end);

    case 'ucs2':
    case 'ucs-2':
      return this.ucs2Slice(start, end);

    default:
      throw new Error('Unknown encoding');
  }
};


Buffer.prototype.hexWrite = function(string, offset, length) {
  offset = +offset || 0;
  var remaining = this.length - offset;
  if (!length) {
    length = remaining;
  } else {
    length = +length;
    if (length > remaining) {
      length = remaining;
    }
  }

  // must be an even number of digits
  var strLen = string.length;
  if (strLen % 2) {
    throw new Error('Invalid hex string');
  }
  if (length > strLen / 2) {
    length = strLen / 2;
  }
  for (var i = 0; i < length; i++) {
    var byte = parseInt(string.substr(i * 2, 2), 16);
    if (isNaN(byte)) throw new Error('Invalid hex string');
    this[offset + i] = byte;
  }
  Buffer._charsWritten = i * 2;
  return i;
};


Buffer.prototype.write = function(string, offset, length, encoding) {
  // Support both (string, offset, length, encoding)
  // and the legacy (string, encoding, offset, length)
  if (isFinite(offset)) {
    if (!isFinite(length)) {
      encoding = length;
      length = undefined;
    }
  } else {  // legacy
    var swap = encoding;
    encoding = offset;
    offset = length;
    length = swap;
  }

  offset = +offset || 0;
  var remaining = this.length - offset;
  if (!length) {
    length = remaining;
  } else {
    length = +length;
    if (length > remaining) {
      length = remaining;
    }
  }
  encoding = String(encoding || 'utf8').toLowerCase();

  switch (encoding) {
    case 'hex':
      return this.hexWrite(string, offset, length);

    case 'utf8':
    case 'utf-8':
      return this.utf8Write(string, offset, length);

    case 'ascii':
      return this.asciiWrite(string, offset, length);

    case 'binary':
      return this.binaryWrite(string, offset, length);

    case 'base64':
      return this.base64Write(string, offset, length);

    case 'ucs2':
    case 'ucs-2':
      return this.ucs2Write(string, offset, length);

    default:
      throw new Error('Unknown encoding');
  }
};

// slice(start, end)
function clamp(index, len, defaultValue) {
  if (typeof index !== 'number') return defaultValue;
  index = ~~index;  // Coerce to integer.
  if (index >= len) return len;
  if (index >= 0) return index;
  index += len;
  if (index >= 0) return index;
  return 0;
}

Buffer.prototype.slice = function(start, end) {
  var len = this.length;
  start = clamp(start, len, 0);
  end = clamp(end, len, len);
  return new Buffer(this, end - start, +start);
};

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function(target, target_start, start, end) {
  var source = this;
  start || (start = 0);
  if (end === undefined || isNaN(end)) {
    end = this.length;
  }
  target_start || (target_start = 0);

  if (end < start) throw new Error('sourceEnd < sourceStart');

  // Copy 0 bytes; we're done
  if (end === start) return 0;
  if (target.length == 0 || source.length == 0) return 0;

  if (target_start < 0 || target_start >= target.length) {
    throw new Error('targetStart out of bounds');
  }

  if (start < 0 || start >= source.length) {
    throw new Error('sourceStart out of bounds');
  }

  if (end < 0 || end > source.length) {
    throw new Error('sourceEnd out of bounds');
  }

  // Are we oob?
  if (end > this.length) {
    end = this.length;
  }

  if (target.length - target_start < end - start) {
    end = target.length - target_start + start;
  }

  var temp = [];
  for (var i=start; i<end; i++) {
    assert.ok(typeof this[i] !== 'undefined', "copying undefined buffer bytes!");
    temp.push(this[i]);
  }

  for (var i=target_start; i<target_start+temp.length; i++) {
    target[i] = temp[i-target_start];
  }
};

// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function fill(value, start, end) {
  value || (value = 0);
  start || (start = 0);
  end || (end = this.length);

  if (typeof value === 'string') {
    value = value.charCodeAt(0);
  }
  if (!(typeof value === 'number') || isNaN(value)) {
    throw new Error('value is not a number');
  }

  if (end < start) throw new Error('end < start');

  // Fill 0 bytes; we're done
  if (end === start) return 0;
  if (this.length == 0) return 0;

  if (start < 0 || start >= this.length) {
    throw new Error('start out of bounds');
  }

  if (end < 0 || end > this.length) {
    throw new Error('end out of bounds');
  }

  for (var i = start; i < end; i++) {
    this[i] = value;
  }
}

// Static methods
Buffer.isBuffer = function isBuffer(b) {
  return b instanceof Buffer || b instanceof Buffer;
};

Buffer.concat = function (list, totalLength) {
  if (!isArray(list)) {
    throw new Error("Usage: Buffer.concat(list, [totalLength])\n \
      list should be an Array.");
  }

  if (list.length === 0) {
    return new Buffer(0);
  } else if (list.length === 1) {
    return list[0];
  }

  if (typeof totalLength !== 'number') {
    totalLength = 0;
    for (var i = 0; i < list.length; i++) {
      var buf = list[i];
      totalLength += buf.length;
    }
  }

  var buffer = new Buffer(totalLength);
  var pos = 0;
  for (var i = 0; i < list.length; i++) {
    var buf = list[i];
    buf.copy(buffer, pos);
    pos += buf.length;
  }
  return buffer;
};

Buffer.isEncoding = function(encoding) {
  switch ((encoding + '').toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
    case 'raw':
      return true;

    default:
      return false;
  }
};

// helpers

function coerce(length) {
  // Coerce length to a number (possibly NaN), round up
  // in case it's fractional (e.g. 123.456) then do a
  // double negate to coerce a NaN to 0. Easy, right?
  length = ~~Math.ceil(+length);
  return length < 0 ? 0 : length;
}

function isArray(subject) {
  return (Array.isArray ||
    function(subject){
      return {}.toString.apply(subject) == '[object Array]'
    })
    (subject)
}

function isArrayIsh(subject) {
  return isArray(subject) || Buffer.isBuffer(subject) ||
         subject && typeof subject === 'object' &&
         typeof subject.length === 'number';
}

function toHex(n) {
  if (n < 16) return '0' + n.toString(16);
  return n.toString(16);
}

function utf8ToBytes(str) {
  var byteArray = [];
  for (var i = 0; i < str.length; i++)
    if (str.charCodeAt(i) <= 0x7F)
      byteArray.push(str.charCodeAt(i));
    else {
      var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');
      for (var j = 0; j < h.length; j++)
        byteArray.push(parseInt(h[j], 16));
    }

  return byteArray;
}

function asciiToBytes(str) {
  var byteArray = []
  for (var i = 0; i < str.length; i++ )
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push( str.charCodeAt(i) & 0xFF );

  return byteArray;
}

function base64ToBytes(str) {
  return require("base64-js").toByteArray(str);
}

function blitBuffer(src, dst, offset, length) {
  var pos, i = 0;
  while (i < length) {
    if ((i+offset >= dst.length) || (i >= src.length))
      break;

    dst[i + offset] = src[i];
    i++;
  }
  return i;
}

function decodeUtf8Char(str) {
  try {
    return decodeURIComponent(str);
  } catch (err) {
    return String.fromCharCode(0xFFFD); // UTF 8 invalid char
  }
}

// read/write bit-twiddling

Buffer.prototype.readUInt8 = function(offset, noAssert) {
  var buffer = this;

  if (!noAssert) {
    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset < buffer.length,
        'Trying to read beyond buffer length');
  }

  if (offset >= buffer.length) return;

  return buffer[offset];
};

function readUInt16(buffer, offset, isBigEndian, noAssert) {
  var val = 0;


  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 1 < buffer.length,
        'Trying to read beyond buffer length');
  }

  if (offset >= buffer.length) return 0;

  if (isBigEndian) {
    val = buffer[offset] << 8;
    if (offset + 1 < buffer.length) {
      val |= buffer[offset + 1];
    }
  } else {
    val = buffer[offset];
    if (offset + 1 < buffer.length) {
      val |= buffer[offset + 1] << 8;
    }
  }

  return val;
}

Buffer.prototype.readUInt16LE = function(offset, noAssert) {
  return readUInt16(this, offset, false, noAssert);
};

Buffer.prototype.readUInt16BE = function(offset, noAssert) {
  return readUInt16(this, offset, true, noAssert);
};

function readUInt32(buffer, offset, isBigEndian, noAssert) {
  var val = 0;

  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 3 < buffer.length,
        'Trying to read beyond buffer length');
  }

  if (offset >= buffer.length) return 0;

  if (isBigEndian) {
    if (offset + 1 < buffer.length)
      val = buffer[offset + 1] << 16;
    if (offset + 2 < buffer.length)
      val |= buffer[offset + 2] << 8;
    if (offset + 3 < buffer.length)
      val |= buffer[offset + 3];
    val = val + (buffer[offset] << 24 >>> 0);
  } else {
    if (offset + 2 < buffer.length)
      val = buffer[offset + 2] << 16;
    if (offset + 1 < buffer.length)
      val |= buffer[offset + 1] << 8;
    val |= buffer[offset];
    if (offset + 3 < buffer.length)
      val = val + (buffer[offset + 3] << 24 >>> 0);
  }

  return val;
}

Buffer.prototype.readUInt32LE = function(offset, noAssert) {
  return readUInt32(this, offset, false, noAssert);
};

Buffer.prototype.readUInt32BE = function(offset, noAssert) {
  return readUInt32(this, offset, true, noAssert);
};


/*
 * Signed integer types, yay team! A reminder on how two's complement actually
 * works. The first bit is the signed bit, i.e. tells us whether or not the
 * number should be positive or negative. If the two's complement value is
 * positive, then we're done, as it's equivalent to the unsigned representation.
 *
 * Now if the number is positive, you're pretty much done, you can just leverage
 * the unsigned translations and return those. Unfortunately, negative numbers
 * aren't quite that straightforward.
 *
 * At first glance, one might be inclined to use the traditional formula to
 * translate binary numbers between the positive and negative values in two's
 * complement. (Though it doesn't quite work for the most negative value)
 * Mainly:
 *  - invert all the bits
 *  - add one to the result
 *
 * Of course, this doesn't quite work in Javascript. Take for example the value
 * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
 * course, Javascript will do the following:
 *
 * > ~0xff80
 * -65409
 *
 * Whoh there, Javascript, that's not quite right. But wait, according to
 * Javascript that's perfectly correct. When Javascript ends up seeing the
 * constant 0xff80, it has no notion that it is actually a signed number. It
 * assumes that we've input the unsigned value 0xff80. Thus, when it does the
 * binary negation, it casts it into a signed value, (positive 0xff80). Then
 * when you perform binary negation on that, it turns it into a negative number.
 *
 * Instead, we're going to have to use the following general formula, that works
 * in a rather Javascript friendly way. I'm glad we don't support this kind of
 * weird numbering scheme in the kernel.
 *
 * (BIT-MAX - (unsigned)val + 1) * -1
 *
 * The astute observer, may think that this doesn't make sense for 8-bit numbers
 * (really it isn't necessary for them). However, when you get 16-bit numbers,
 * you do. Let's go back to our prior example and see how this will look:
 *
 * (0xffff - 0xff80 + 1) * -1
 * (0x007f + 1) * -1
 * (0x0080) * -1
 */
Buffer.prototype.readInt8 = function(offset, noAssert) {
  var buffer = this;
  var neg;

  if (!noAssert) {
    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset < buffer.length,
        'Trying to read beyond buffer length');
  }

  if (offset >= buffer.length) return;

  neg = buffer[offset] & 0x80;
  if (!neg) {
    return (buffer[offset]);
  }

  return ((0xff - buffer[offset] + 1) * -1);
};

function readInt16(buffer, offset, isBigEndian, noAssert) {
  var neg, val;

  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 1 < buffer.length,
        'Trying to read beyond buffer length');
  }

  val = readUInt16(buffer, offset, isBigEndian, noAssert);
  neg = val & 0x8000;
  if (!neg) {
    return val;
  }

  return (0xffff - val + 1) * -1;
}

Buffer.prototype.readInt16LE = function(offset, noAssert) {
  return readInt16(this, offset, false, noAssert);
};

Buffer.prototype.readInt16BE = function(offset, noAssert) {
  return readInt16(this, offset, true, noAssert);
};

function readInt32(buffer, offset, isBigEndian, noAssert) {
  var neg, val;

  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 3 < buffer.length,
        'Trying to read beyond buffer length');
  }

  val = readUInt32(buffer, offset, isBigEndian, noAssert);
  neg = val & 0x80000000;
  if (!neg) {
    return (val);
  }

  return (0xffffffff - val + 1) * -1;
}

Buffer.prototype.readInt32LE = function(offset, noAssert) {
  return readInt32(this, offset, false, noAssert);
};

Buffer.prototype.readInt32BE = function(offset, noAssert) {
  return readInt32(this, offset, true, noAssert);
};

function readFloat(buffer, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset + 3 < buffer.length,
        'Trying to read beyond buffer length');
  }

  return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian,
      23, 4);
}

Buffer.prototype.readFloatLE = function(offset, noAssert) {
  return readFloat(this, offset, false, noAssert);
};

Buffer.prototype.readFloatBE = function(offset, noAssert) {
  return readFloat(this, offset, true, noAssert);
};

function readDouble(buffer, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset + 7 < buffer.length,
        'Trying to read beyond buffer length');
  }

  return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian,
      52, 8);
}

Buffer.prototype.readDoubleLE = function(offset, noAssert) {
  return readDouble(this, offset, false, noAssert);
};

Buffer.prototype.readDoubleBE = function(offset, noAssert) {
  return readDouble(this, offset, true, noAssert);
};


/*
 * We have to make sure that the value is a valid integer. This means that it is
 * non-negative. It has no fractional component and that it does not exceed the
 * maximum allowed value.
 *
 *      value           The number to check for validity
 *
 *      max             The maximum value
 */
function verifuint(value, max) {
  assert.ok(typeof (value) == 'number',
      'cannot write a non-number as a number');

  assert.ok(value >= 0,
      'specified a negative value for writing an unsigned value');

  assert.ok(value <= max, 'value is larger than maximum value for type');

  assert.ok(Math.floor(value) === value, 'value has a fractional component');
}

Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
  var buffer = this;

  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset < buffer.length,
        'trying to write beyond buffer length');

    verifuint(value, 0xff);
  }

  if (offset < buffer.length) {
    buffer[offset] = value;
  }
};

function writeUInt16(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 1 < buffer.length,
        'trying to write beyond buffer length');

    verifuint(value, 0xffff);
  }

  for (var i = 0; i < Math.min(buffer.length - offset, 2); i++) {
    buffer[offset + i] =
        (value & (0xff << (8 * (isBigEndian ? 1 - i : i)))) >>>
            (isBigEndian ? 1 - i : i) * 8;
  }

}

Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
  writeUInt16(this, value, offset, false, noAssert);
};

Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
  writeUInt16(this, value, offset, true, noAssert);
};

function writeUInt32(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 3 < buffer.length,
        'trying to write beyond buffer length');

    verifuint(value, 0xffffffff);
  }

  for (var i = 0; i < Math.min(buffer.length - offset, 4); i++) {
    buffer[offset + i] =
        (value >>> (isBigEndian ? 3 - i : i) * 8) & 0xff;
  }
}

Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
  writeUInt32(this, value, offset, false, noAssert);
};

Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
  writeUInt32(this, value, offset, true, noAssert);
};


/*
 * We now move onto our friends in the signed number category. Unlike unsigned
 * numbers, we're going to have to worry a bit more about how we put values into
 * arrays. Since we are only worrying about signed 32-bit values, we're in
 * slightly better shape. Unfortunately, we really can't do our favorite binary
 * & in this system. It really seems to do the wrong thing. For example:
 *
 * > -32 & 0xff
 * 224
 *
 * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
 * this aren't treated as a signed number. Ultimately a bad thing.
 *
 * What we're going to want to do is basically create the unsigned equivalent of
 * our representation and pass that off to the wuint* functions. To do that
 * we're going to do the following:
 *
 *  - if the value is positive
 *      we can pass it directly off to the equivalent wuint
 *  - if the value is negative
 *      we do the following computation:
 *         mb + val + 1, where
 *         mb   is the maximum unsigned value in that byte size
 *         val  is the Javascript negative integer
 *
 *
 * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
 * you do out the computations:
 *
 * 0xffff - 128 + 1
 * 0xffff - 127
 * 0xff80
 *
 * You can then encode this value as the signed version. This is really rather
 * hacky, but it should work and get the job done which is our goal here.
 */

/*
 * A series of checks to make sure we actually have a signed 32-bit number
 */
function verifsint(value, max, min) {
  assert.ok(typeof (value) == 'number',
      'cannot write a non-number as a number');

  assert.ok(value <= max, 'value larger than maximum allowed value');

  assert.ok(value >= min, 'value smaller than minimum allowed value');

  assert.ok(Math.floor(value) === value, 'value has a fractional component');
}

function verifIEEE754(value, max, min) {
  assert.ok(typeof (value) == 'number',
      'cannot write a non-number as a number');

  assert.ok(value <= max, 'value larger than maximum allowed value');

  assert.ok(value >= min, 'value smaller than minimum allowed value');
}

Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
  var buffer = this;

  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset < buffer.length,
        'Trying to write beyond buffer length');

    verifsint(value, 0x7f, -0x80);
  }

  if (value >= 0) {
    buffer.writeUInt8(value, offset, noAssert);
  } else {
    buffer.writeUInt8(0xff + value + 1, offset, noAssert);
  }
};

function writeInt16(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 1 < buffer.length,
        'Trying to write beyond buffer length');

    verifsint(value, 0x7fff, -0x8000);
  }

  if (value >= 0) {
    writeUInt16(buffer, value, offset, isBigEndian, noAssert);
  } else {
    writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert);
  }
}

Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
  writeInt16(this, value, offset, false, noAssert);
};

Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
  writeInt16(this, value, offset, true, noAssert);
};

function writeInt32(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 3 < buffer.length,
        'Trying to write beyond buffer length');

    verifsint(value, 0x7fffffff, -0x80000000);
  }

  if (value >= 0) {
    writeUInt32(buffer, value, offset, isBigEndian, noAssert);
  } else {
    writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert);
  }
}

Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
  writeInt32(this, value, offset, false, noAssert);
};

Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
  writeInt32(this, value, offset, true, noAssert);
};

function writeFloat(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 3 < buffer.length,
        'Trying to write beyond buffer length');

    verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38);
  }

  require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian,
      23, 4);
}

Buffer.prototype.writeFloatLE = function(value, offset, noAssert) {
  writeFloat(this, value, offset, false, noAssert);
};

Buffer.prototype.writeFloatBE = function(value, offset, noAssert) {
  writeFloat(this, value, offset, true, noAssert);
};

function writeDouble(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 7 < buffer.length,
        'Trying to write beyond buffer length');

    verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308);
  }

  require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian,
      52, 8);
}

Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) {
  writeDouble(this, value, offset, false, noAssert);
};

Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) {
  writeDouble(this, value, offset, true, noAssert);
};

},{"./buffer_ieee754":9,"assert":3,"base64-js":11}],11:[function(require,module,exports){
(function (exports) {
	'use strict';

	var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

	function b64ToByteArray(b64) {
		var i, j, l, tmp, placeHolders, arr;
	
		if (b64.length % 4 > 0) {
			throw 'Invalid string. Length must be a multiple of 4';
		}

		// the number of equal signs (place holders)
		// if there are two placeholders, than the two characters before it
		// represent one byte
		// if there is only one, then the three characters before it represent 2 bytes
		// this is just a cheap hack to not do indexOf twice
		placeHolders = b64.indexOf('=');
		placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0;

		// base64 is 4/3 + up to two characters of the original data
		arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders);

		// if there are placeholders, only get up to the last complete 4 chars
		l = placeHolders > 0 ? b64.length - 4 : b64.length;

		for (i = 0, j = 0; i < l; i += 4, j += 3) {
			tmp = (lookup.indexOf(b64[i]) << 18) | (lookup.indexOf(b64[i + 1]) << 12) | (lookup.indexOf(b64[i + 2]) << 6) | lookup.indexOf(b64[i + 3]);
			arr.push((tmp & 0xFF0000) >> 16);
			arr.push((tmp & 0xFF00) >> 8);
			arr.push(tmp & 0xFF);
		}

		if (placeHolders === 2) {
			tmp = (lookup.indexOf(b64[i]) << 2) | (lookup.indexOf(b64[i + 1]) >> 4);
			arr.push(tmp & 0xFF);
		} else if (placeHolders === 1) {
			tmp = (lookup.indexOf(b64[i]) << 10) | (lookup.indexOf(b64[i + 1]) << 4) | (lookup.indexOf(b64[i + 2]) >> 2);
			arr.push((tmp >> 8) & 0xFF);
			arr.push(tmp & 0xFF);
		}

		return arr;
	}

	function uint8ToBase64(uint8) {
		var i,
			extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
			output = "",
			temp, length;

		function tripletToBase64 (num) {
			return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
		};

		// go through the array every three bytes, we'll deal with trailing stuff later
		for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
			temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
			output += tripletToBase64(temp);
		}

		// pad the end with zeros, but make sure to not forget the extra bytes
		switch (extraBytes) {
			case 1:
				temp = uint8[uint8.length - 1];
				output += lookup[temp >> 2];
				output += lookup[(temp << 4) & 0x3F];
				output += '==';
				break;
			case 2:
				temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]);
				output += lookup[temp >> 10];
				output += lookup[(temp >> 4) & 0x3F];
				output += lookup[(temp << 2) & 0x3F];
				output += '=';
				break;
		}

		return output;
	}

	module.exports.toByteArray = b64ToByteArray;
	module.exports.fromByteArray = uint8ToBase64;
}());

},{}],12:[function(require,module,exports){
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
exports.readIEEE754 = function(buffer, offset, isBE, mLen, nBytes) {
  var e, m,
      eLen = nBytes * 8 - mLen - 1,
      eMax = (1 << eLen) - 1,
      eBias = eMax >> 1,
      nBits = -7,
      i = isBE ? 0 : (nBytes - 1),
      d = isBE ? 1 : -1,
      s = buffer[offset + i];

  i += d;

  e = s & ((1 << (-nBits)) - 1);
  s >>= (-nBits);
  nBits += eLen;
  for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);

  m = e & ((1 << (-nBits)) - 1);
  e >>= (-nBits);
  nBits += mLen;
  for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);

  if (e === 0) {
    e = 1 - eBias;
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity);
  } else {
    m = m + Math.pow(2, mLen);
    e = e - eBias;
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};

exports.writeIEEE754 = function(buffer, value, offset, isBE, mLen, nBytes) {
  var e, m, c,
      eLen = nBytes * 8 - mLen - 1,
      eMax = (1 << eLen) - 1,
      eBias = eMax >> 1,
      rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
      i = isBE ? (nBytes - 1) : 0,
      d = isBE ? -1 : 1,
      s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;

  value = Math.abs(value);

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0;
    e = eMax;
  } else {
    e = Math.floor(Math.log(value) / Math.LN2);
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--;
      c *= 2;
    }
    if (e + eBias >= 1) {
      value += rt / c;
    } else {
      value += rt * Math.pow(2, 1 - eBias);
    }
    if (value * c >= 2) {
      e++;
      c /= 2;
    }

    if (e + eBias >= eMax) {
      m = 0;
      e = eMax;
    } else if (e + eBias >= 1) {
      m = (value * c - 1) * Math.pow(2, mLen);
      e = e + eBias;
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
      e = 0;
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);

  e = (e << mLen) | m;
  eLen += mLen;
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);

  buffer[offset + i - d] |= s * 128;
};

},{}],"q9TxCC":[function(require,module,exports){
var assert;
exports.Buffer = Buffer;
exports.SlowBuffer = Buffer;
Buffer.poolSize = 8192;
exports.INSPECT_MAX_BYTES = 50;

function stringtrim(str) {
  if (str.trim) return str.trim();
  return str.replace(/^\s+|\s+$/g, '');
}

function Buffer(subject, encoding, offset) {
  if(!assert) assert= require('assert');
  if (!(this instanceof Buffer)) {
    return new Buffer(subject, encoding, offset);
  }
  this.parent = this;
  this.offset = 0;

  // Work-around: node's base64 implementation
  // allows for non-padded strings while base64-js
  // does not..
  if (encoding == "base64" && typeof subject == "string") {
    subject = stringtrim(subject);
    while (subject.length % 4 != 0) {
      subject = subject + "="; 
    }
  }

  var type;

  // Are we slicing?
  if (typeof offset === 'number') {
    this.length = coerce(encoding);
    // slicing works, with limitations (no parent tracking/update)
    // check https://github.com/toots/buffer-browserify/issues/19
    for (var i = 0; i < this.length; i++) {
        this[i] = subject.get(i+offset);
    }
  } else {
    // Find the length
    switch (type = typeof subject) {
      case 'number':
        this.length = coerce(subject);
        break;

      case 'string':
        this.length = Buffer.byteLength(subject, encoding);
        break;

      case 'object': // Assume object is an array
        this.length = coerce(subject.length);
        break;

      default:
        throw new Error('First argument needs to be a number, ' +
                        'array or string.');
    }

    // Treat array-ish objects as a byte array.
    if (isArrayIsh(subject)) {
      for (var i = 0; i < this.length; i++) {
        if (subject instanceof Buffer) {
          this[i] = subject.readUInt8(i);
        }
        else {
          this[i] = subject[i];
        }
      }
    } else if (type == 'string') {
      // We are a string
      this.length = this.write(subject, 0, encoding);
    } else if (type === 'number') {
      for (var i = 0; i < this.length; i++) {
        this[i] = 0;
      }
    }
  }
}

Buffer.prototype.get = function get(i) {
  if (i < 0 || i >= this.length) throw new Error('oob');
  return this[i];
};

Buffer.prototype.set = function set(i, v) {
  if (i < 0 || i >= this.length) throw new Error('oob');
  return this[i] = v;
};

Buffer.byteLength = function (str, encoding) {
  switch (encoding || "utf8") {
    case 'hex':
      return str.length / 2;

    case 'utf8':
    case 'utf-8':
      return utf8ToBytes(str).length;

    case 'ascii':
    case 'binary':
      return str.length;

    case 'base64':
      return base64ToBytes(str).length;

    default:
      throw new Error('Unknown encoding');
  }
};

Buffer.prototype.utf8Write = function (string, offset, length) {
  var bytes, pos;
  return Buffer._charsWritten =  blitBuffer(utf8ToBytes(string), this, offset, length);
};

Buffer.prototype.asciiWrite = function (string, offset, length) {
  var bytes, pos;
  return Buffer._charsWritten =  blitBuffer(asciiToBytes(string), this, offset, length);
};

Buffer.prototype.binaryWrite = Buffer.prototype.asciiWrite;

Buffer.prototype.base64Write = function (string, offset, length) {
  var bytes, pos;
  return Buffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length);
};

Buffer.prototype.base64Slice = function (start, end) {
  var bytes = Array.prototype.slice.apply(this, arguments)
  return require("base64-js").fromByteArray(bytes);
};

Buffer.prototype.utf8Slice = function () {
  var bytes = Array.prototype.slice.apply(this, arguments);
  var res = "";
  var tmp = "";
  var i = 0;
  while (i < bytes.length) {
    if (bytes[i] <= 0x7F) {
      res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]);
      tmp = "";
    } else
      tmp += "%" + bytes[i].toString(16);

    i++;
  }

  return res + decodeUtf8Char(tmp);
}

Buffer.prototype.asciiSlice = function () {
  var bytes = Array.prototype.slice.apply(this, arguments);
  var ret = "";
  for (var i = 0; i < bytes.length; i++)
    ret += String.fromCharCode(bytes[i]);
  return ret;
}

Buffer.prototype.binarySlice = Buffer.prototype.asciiSlice;

Buffer.prototype.inspect = function() {
  var out = [],
      len = this.length;
  for (var i = 0; i < len; i++) {
    out[i] = toHex(this[i]);
    if (i == exports.INSPECT_MAX_BYTES) {
      out[i + 1] = '...';
      break;
    }
  }
  return '<Buffer ' + out.join(' ') + '>';
};


Buffer.prototype.hexSlice = function(start, end) {
  var len = this.length;

  if (!start || start < 0) start = 0;
  if (!end || end < 0 || end > len) end = len;

  var out = '';
  for (var i = start; i < end; i++) {
    out += toHex(this[i]);
  }
  return out;
};


Buffer.prototype.toString = function(encoding, start, end) {
  encoding = String(encoding || 'utf8').toLowerCase();
  start = +start || 0;
  if (typeof end == 'undefined') end = this.length;

  // Fastpath empty strings
  if (+end == start) {
    return '';
  }

  switch (encoding) {
    case 'hex':
      return this.hexSlice(start, end);

    case 'utf8':
    case 'utf-8':
      return this.utf8Slice(start, end);

    case 'ascii':
      return this.asciiSlice(start, end);

    case 'binary':
      return this.binarySlice(start, end);

    case 'base64':
      return this.base64Slice(start, end);

    case 'ucs2':
    case 'ucs-2':
      return this.ucs2Slice(start, end);

    default:
      throw new Error('Unknown encoding');
  }
};


Buffer.prototype.hexWrite = function(string, offset, length) {
  offset = +offset || 0;
  var remaining = this.length - offset;
  if (!length) {
    length = remaining;
  } else {
    length = +length;
    if (length > remaining) {
      length = remaining;
    }
  }

  // must be an even number of digits
  var strLen = string.length;
  if (strLen % 2) {
    throw new Error('Invalid hex string');
  }
  if (length > strLen / 2) {
    length = strLen / 2;
  }
  for (var i = 0; i < length; i++) {
    var byte = parseInt(string.substr(i * 2, 2), 16);
    if (isNaN(byte)) throw new Error('Invalid hex string');
    this[offset + i] = byte;
  }
  Buffer._charsWritten = i * 2;
  return i;
};


Buffer.prototype.write = function(string, offset, length, encoding) {
  // Support both (string, offset, length, encoding)
  // and the legacy (string, encoding, offset, length)
  if (isFinite(offset)) {
    if (!isFinite(length)) {
      encoding = length;
      length = undefined;
    }
  } else {  // legacy
    var swap = encoding;
    encoding = offset;
    offset = length;
    length = swap;
  }

  offset = +offset || 0;
  var remaining = this.length - offset;
  if (!length) {
    length = remaining;
  } else {
    length = +length;
    if (length > remaining) {
      length = remaining;
    }
  }
  encoding = String(encoding || 'utf8').toLowerCase();

  switch (encoding) {
    case 'hex':
      return this.hexWrite(string, offset, length);

    case 'utf8':
    case 'utf-8':
      return this.utf8Write(string, offset, length);

    case 'ascii':
      return this.asciiWrite(string, offset, length);

    case 'binary':
      return this.binaryWrite(string, offset, length);

    case 'base64':
      return this.base64Write(string, offset, length);

    case 'ucs2':
    case 'ucs-2':
      return this.ucs2Write(string, offset, length);

    default:
      throw new Error('Unknown encoding');
  }
};

// slice(start, end)
function clamp(index, len, defaultValue) {
  if (typeof index !== 'number') return defaultValue;
  index = ~~index;  // Coerce to integer.
  if (index >= len) return len;
  if (index >= 0) return index;
  index += len;
  if (index >= 0) return index;
  return 0;
}

Buffer.prototype.slice = function(start, end) {
  var len = this.length;
  start = clamp(start, len, 0);
  end = clamp(end, len, len);
  return new Buffer(this, end - start, +start);
};

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function(target, target_start, start, end) {
  var source = this;
  start || (start = 0);
  if (end === undefined || isNaN(end)) {
    end = this.length;
  }
  target_start || (target_start = 0);

  if (end < start) throw new Error('sourceEnd < sourceStart');

  // Copy 0 bytes; we're done
  if (end === start) return 0;
  if (target.length == 0 || source.length == 0) return 0;

  if (target_start < 0 || target_start >= target.length) {
    throw new Error('targetStart out of bounds');
  }

  if (start < 0 || start >= source.length) {
    throw new Error('sourceStart out of bounds');
  }

  if (end < 0 || end > source.length) {
    throw new Error('sourceEnd out of bounds');
  }

  // Are we oob?
  if (end > this.length) {
    end = this.length;
  }

  if (target.length - target_start < end - start) {
    end = target.length - target_start + start;
  }

  var temp = [];
  for (var i=start; i<end; i++) {
    assert.ok(typeof this[i] !== 'undefined', "copying undefined buffer bytes!");
    temp.push(this[i]);
  }

  for (var i=target_start; i<target_start+temp.length; i++) {
    target[i] = temp[i-target_start];
  }
};

// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function fill(value, start, end) {
  value || (value = 0);
  start || (start = 0);
  end || (end = this.length);

  if (typeof value === 'string') {
    value = value.charCodeAt(0);
  }
  if (!(typeof value === 'number') || isNaN(value)) {
    throw new Error('value is not a number');
  }

  if (end < start) throw new Error('end < start');

  // Fill 0 bytes; we're done
  if (end === start) return 0;
  if (this.length == 0) return 0;

  if (start < 0 || start >= this.length) {
    throw new Error('start out of bounds');
  }

  if (end < 0 || end > this.length) {
    throw new Error('end out of bounds');
  }

  for (var i = start; i < end; i++) {
    this[i] = value;
  }
}

// Static methods
Buffer.isBuffer = function isBuffer(b) {
  return b instanceof Buffer || b instanceof Buffer;
};

Buffer.concat = function (list, totalLength) {
  if (!isArray(list)) {
    throw new Error("Usage: Buffer.concat(list, [totalLength])\n \
      list should be an Array.");
  }

  if (list.length === 0) {
    return new Buffer(0);
  } else if (list.length === 1) {
    return list[0];
  }

  if (typeof totalLength !== 'number') {
    totalLength = 0;
    for (var i = 0; i < list.length; i++) {
      var buf = list[i];
      totalLength += buf.length;
    }
  }

  var buffer = new Buffer(totalLength);
  var pos = 0;
  for (var i = 0; i < list.length; i++) {
    var buf = list[i];
    buf.copy(buffer, pos);
    pos += buf.length;
  }
  return buffer;
};

Buffer.isEncoding = function(encoding) {
  switch ((encoding + '').toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
    case 'raw':
      return true;

    default:
      return false;
  }
};

// helpers

function coerce(length) {
  // Coerce length to a number (possibly NaN), round up
  // in case it's fractional (e.g. 123.456) then do a
  // double negate to coerce a NaN to 0. Easy, right?
  length = ~~Math.ceil(+length);
  return length < 0 ? 0 : length;
}

function isArray(subject) {
  return (Array.isArray ||
    function(subject){
      return {}.toString.apply(subject) == '[object Array]'
    })
    (subject)
}

function isArrayIsh(subject) {
  return isArray(subject) || Buffer.isBuffer(subject) ||
         subject && typeof subject === 'object' &&
         typeof subject.length === 'number';
}

function toHex(n) {
  if (n < 16) return '0' + n.toString(16);
  return n.toString(16);
}

function utf8ToBytes(str) {
  var byteArray = [];
  for (var i = 0; i < str.length; i++)
    if (str.charCodeAt(i) <= 0x7F)
      byteArray.push(str.charCodeAt(i));
    else {
      var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');
      for (var j = 0; j < h.length; j++)
        byteArray.push(parseInt(h[j], 16));
    }

  return byteArray;
}

function asciiToBytes(str) {
  var byteArray = []
  for (var i = 0; i < str.length; i++ )
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push( str.charCodeAt(i) & 0xFF );

  return byteArray;
}

function base64ToBytes(str) {
  return require("base64-js").toByteArray(str);
}

function blitBuffer(src, dst, offset, length) {
  var pos, i = 0;
  while (i < length) {
    if ((i+offset >= dst.length) || (i >= src.length))
      break;

    dst[i + offset] = src[i];
    i++;
  }
  return i;
}

function decodeUtf8Char(str) {
  try {
    return decodeURIComponent(str);
  } catch (err) {
    return String.fromCharCode(0xFFFD); // UTF 8 invalid char
  }
}

// read/write bit-twiddling

Buffer.prototype.readUInt8 = function(offset, noAssert) {
  var buffer = this;

  if (!noAssert) {
    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset < buffer.length,
        'Trying to read beyond buffer length');
  }

  if (offset >= buffer.length) return;

  return buffer[offset];
};

function readUInt16(buffer, offset, isBigEndian, noAssert) {
  var val = 0;


  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 1 < buffer.length,
        'Trying to read beyond buffer length');
  }

  if (offset >= buffer.length) return 0;

  if (isBigEndian) {
    val = buffer[offset] << 8;
    if (offset + 1 < buffer.length) {
      val |= buffer[offset + 1];
    }
  } else {
    val = buffer[offset];
    if (offset + 1 < buffer.length) {
      val |= buffer[offset + 1] << 8;
    }
  }

  return val;
}

Buffer.prototype.readUInt16LE = function(offset, noAssert) {
  return readUInt16(this, offset, false, noAssert);
};

Buffer.prototype.readUInt16BE = function(offset, noAssert) {
  return readUInt16(this, offset, true, noAssert);
};

function readUInt32(buffer, offset, isBigEndian, noAssert) {
  var val = 0;

  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 3 < buffer.length,
        'Trying to read beyond buffer length');
  }

  if (offset >= buffer.length) return 0;

  if (isBigEndian) {
    if (offset + 1 < buffer.length)
      val = buffer[offset + 1] << 16;
    if (offset + 2 < buffer.length)
      val |= buffer[offset + 2] << 8;
    if (offset + 3 < buffer.length)
      val |= buffer[offset + 3];
    val = val + (buffer[offset] << 24 >>> 0);
  } else {
    if (offset + 2 < buffer.length)
      val = buffer[offset + 2] << 16;
    if (offset + 1 < buffer.length)
      val |= buffer[offset + 1] << 8;
    val |= buffer[offset];
    if (offset + 3 < buffer.length)
      val = val + (buffer[offset + 3] << 24 >>> 0);
  }

  return val;
}

Buffer.prototype.readUInt32LE = function(offset, noAssert) {
  return readUInt32(this, offset, false, noAssert);
};

Buffer.prototype.readUInt32BE = function(offset, noAssert) {
  return readUInt32(this, offset, true, noAssert);
};


/*
 * Signed integer types, yay team! A reminder on how two's complement actually
 * works. The first bit is the signed bit, i.e. tells us whether or not the
 * number should be positive or negative. If the two's complement value is
 * positive, then we're done, as it's equivalent to the unsigned representation.
 *
 * Now if the number is positive, you're pretty much done, you can just leverage
 * the unsigned translations and return those. Unfortunately, negative numbers
 * aren't quite that straightforward.
 *
 * At first glance, one might be inclined to use the traditional formula to
 * translate binary numbers between the positive and negative values in two's
 * complement. (Though it doesn't quite work for the most negative value)
 * Mainly:
 *  - invert all the bits
 *  - add one to the result
 *
 * Of course, this doesn't quite work in Javascript. Take for example the value
 * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
 * course, Javascript will do the following:
 *
 * > ~0xff80
 * -65409
 *
 * Whoh there, Javascript, that's not quite right. But wait, according to
 * Javascript that's perfectly correct. When Javascript ends up seeing the
 * constant 0xff80, it has no notion that it is actually a signed number. It
 * assumes that we've input the unsigned value 0xff80. Thus, when it does the
 * binary negation, it casts it into a signed value, (positive 0xff80). Then
 * when you perform binary negation on that, it turns it into a negative number.
 *
 * Instead, we're going to have to use the following general formula, that works
 * in a rather Javascript friendly way. I'm glad we don't support this kind of
 * weird numbering scheme in the kernel.
 *
 * (BIT-MAX - (unsigned)val + 1) * -1
 *
 * The astute observer, may think that this doesn't make sense for 8-bit numbers
 * (really it isn't necessary for them). However, when you get 16-bit numbers,
 * you do. Let's go back to our prior example and see how this will look:
 *
 * (0xffff - 0xff80 + 1) * -1
 * (0x007f + 1) * -1
 * (0x0080) * -1
 */
Buffer.prototype.readInt8 = function(offset, noAssert) {
  var buffer = this;
  var neg;

  if (!noAssert) {
    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset < buffer.length,
        'Trying to read beyond buffer length');
  }

  if (offset >= buffer.length) return;

  neg = buffer[offset] & 0x80;
  if (!neg) {
    return (buffer[offset]);
  }

  return ((0xff - buffer[offset] + 1) * -1);
};

function readInt16(buffer, offset, isBigEndian, noAssert) {
  var neg, val;

  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 1 < buffer.length,
        'Trying to read beyond buffer length');
  }

  val = readUInt16(buffer, offset, isBigEndian, noAssert);
  neg = val & 0x8000;
  if (!neg) {
    return val;
  }

  return (0xffff - val + 1) * -1;
}

Buffer.prototype.readInt16LE = function(offset, noAssert) {
  return readInt16(this, offset, false, noAssert);
};

Buffer.prototype.readInt16BE = function(offset, noAssert) {
  return readInt16(this, offset, true, noAssert);
};

function readInt32(buffer, offset, isBigEndian, noAssert) {
  var neg, val;

  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 3 < buffer.length,
        'Trying to read beyond buffer length');
  }

  val = readUInt32(buffer, offset, isBigEndian, noAssert);
  neg = val & 0x80000000;
  if (!neg) {
    return (val);
  }

  return (0xffffffff - val + 1) * -1;
}

Buffer.prototype.readInt32LE = function(offset, noAssert) {
  return readInt32(this, offset, false, noAssert);
};

Buffer.prototype.readInt32BE = function(offset, noAssert) {
  return readInt32(this, offset, true, noAssert);
};

function readFloat(buffer, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset + 3 < buffer.length,
        'Trying to read beyond buffer length');
  }

  return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian,
      23, 4);
}

Buffer.prototype.readFloatLE = function(offset, noAssert) {
  return readFloat(this, offset, false, noAssert);
};

Buffer.prototype.readFloatBE = function(offset, noAssert) {
  return readFloat(this, offset, true, noAssert);
};

function readDouble(buffer, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset + 7 < buffer.length,
        'Trying to read beyond buffer length');
  }

  return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian,
      52, 8);
}

Buffer.prototype.readDoubleLE = function(offset, noAssert) {
  return readDouble(this, offset, false, noAssert);
};

Buffer.prototype.readDoubleBE = function(offset, noAssert) {
  return readDouble(this, offset, true, noAssert);
};


/*
 * We have to make sure that the value is a valid integer. This means that it is
 * non-negative. It has no fractional component and that it does not exceed the
 * maximum allowed value.
 *
 *      value           The number to check for validity
 *
 *      max             The maximum value
 */
function verifuint(value, max) {
  assert.ok(typeof (value) == 'number',
      'cannot write a non-number as a number');

  assert.ok(value >= 0,
      'specified a negative value for writing an unsigned value');

  assert.ok(value <= max, 'value is larger than maximum value for type');

  assert.ok(Math.floor(value) === value, 'value has a fractional component');
}

Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
  var buffer = this;

  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset < buffer.length,
        'trying to write beyond buffer length');

    verifuint(value, 0xff);
  }

  if (offset < buffer.length) {
    buffer[offset] = value;
  }
};

function writeUInt16(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 1 < buffer.length,
        'trying to write beyond buffer length');

    verifuint(value, 0xffff);
  }

  for (var i = 0; i < Math.min(buffer.length - offset, 2); i++) {
    buffer[offset + i] =
        (value & (0xff << (8 * (isBigEndian ? 1 - i : i)))) >>>
            (isBigEndian ? 1 - i : i) * 8;
  }

}

Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
  writeUInt16(this, value, offset, false, noAssert);
};

Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
  writeUInt16(this, value, offset, true, noAssert);
};

function writeUInt32(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 3 < buffer.length,
        'trying to write beyond buffer length');

    verifuint(value, 0xffffffff);
  }

  for (var i = 0; i < Math.min(buffer.length - offset, 4); i++) {
    buffer[offset + i] =
        (value >>> (isBigEndian ? 3 - i : i) * 8) & 0xff;
  }
}

Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
  writeUInt32(this, value, offset, false, noAssert);
};

Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
  writeUInt32(this, value, offset, true, noAssert);
};


/*
 * We now move onto our friends in the signed number category. Unlike unsigned
 * numbers, we're going to have to worry a bit more about how we put values into
 * arrays. Since we are only worrying about signed 32-bit values, we're in
 * slightly better shape. Unfortunately, we really can't do our favorite binary
 * & in this system. It really seems to do the wrong thing. For example:
 *
 * > -32 & 0xff
 * 224
 *
 * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
 * this aren't treated as a signed number. Ultimately a bad thing.
 *
 * What we're going to want to do is basically create the unsigned equivalent of
 * our representation and pass that off to the wuint* functions. To do that
 * we're going to do the following:
 *
 *  - if the value is positive
 *      we can pass it directly off to the equivalent wuint
 *  - if the value is negative
 *      we do the following computation:
 *         mb + val + 1, where
 *         mb   is the maximum unsigned value in that byte size
 *         val  is the Javascript negative integer
 *
 *
 * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
 * you do out the computations:
 *
 * 0xffff - 128 + 1
 * 0xffff - 127
 * 0xff80
 *
 * You can then encode this value as the signed version. This is really rather
 * hacky, but it should work and get the job done which is our goal here.
 */

/*
 * A series of checks to make sure we actually have a signed 32-bit number
 */
function verifsint(value, max, min) {
  assert.ok(typeof (value) == 'number',
      'cannot write a non-number as a number');

  assert.ok(value <= max, 'value larger than maximum allowed value');

  assert.ok(value >= min, 'value smaller than minimum allowed value');

  assert.ok(Math.floor(value) === value, 'value has a fractional component');
}

function verifIEEE754(value, max, min) {
  assert.ok(typeof (value) == 'number',
      'cannot write a non-number as a number');

  assert.ok(value <= max, 'value larger than maximum allowed value');

  assert.ok(value >= min, 'value smaller than minimum allowed value');
}

Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
  var buffer = this;

  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset < buffer.length,
        'Trying to write beyond buffer length');

    verifsint(value, 0x7f, -0x80);
  }

  if (value >= 0) {
    buffer.writeUInt8(value, offset, noAssert);
  } else {
    buffer.writeUInt8(0xff + value + 1, offset, noAssert);
  }
};

function writeInt16(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 1 < buffer.length,
        'Trying to write beyond buffer length');

    verifsint(value, 0x7fff, -0x8000);
  }

  if (value >= 0) {
    writeUInt16(buffer, value, offset, isBigEndian, noAssert);
  } else {
    writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert);
  }
}

Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
  writeInt16(this, value, offset, false, noAssert);
};

Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
  writeInt16(this, value, offset, true, noAssert);
};

function writeInt32(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 3 < buffer.length,
        'Trying to write beyond buffer length');

    verifsint(value, 0x7fffffff, -0x80000000);
  }

  if (value >= 0) {
    writeUInt32(buffer, value, offset, isBigEndian, noAssert);
  } else {
    writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert);
  }
}

Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
  writeInt32(this, value, offset, false, noAssert);
};

Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
  writeInt32(this, value, offset, true, noAssert);
};

function writeFloat(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 3 < buffer.length,
        'Trying to write beyond buffer length');

    verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38);
  }

  require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian,
      23, 4);
}

Buffer.prototype.writeFloatLE = function(value, offset, noAssert) {
  writeFloat(this, value, offset, false, noAssert);
};

Buffer.prototype.writeFloatBE = function(value, offset, noAssert) {
  writeFloat(this, value, offset, true, noAssert);
};

function writeDouble(buffer, value, offset, isBigEndian, noAssert) {
  if (!noAssert) {
    assert.ok(value !== undefined && value !== null,
        'missing value');

    assert.ok(typeof (isBigEndian) === 'boolean',
        'missing or invalid endian');

    assert.ok(offset !== undefined && offset !== null,
        'missing offset');

    assert.ok(offset + 7 < buffer.length,
        'Trying to write beyond buffer length');

    verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308);
  }

  require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian,
      52, 8);
}

Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) {
  writeDouble(this, value, offset, false, noAssert);
};

Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) {
  writeDouble(this, value, offset, true, noAssert);
};

},{"./buffer_ieee754":1,"assert":6,"base64-js":4}],"buffer-browserify":[function(require,module,exports){
module.exports=require('q9TxCC');
},{}],4:[function(require,module,exports){
(function (exports) {
	'use strict';

	var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

	function b64ToByteArray(b64) {
		var i, j, l, tmp, placeHolders, arr;
	
		if (b64.length % 4 > 0) {
			throw 'Invalid string. Length must be a multiple of 4';
		}

		// the number of equal signs (place holders)
		// if there are two placeholders, than the two characters before it
		// represent one byte
		// if there is only one, then the three characters before it represent 2 bytes
		// this is just a cheap hack to not do indexOf twice
		placeHolders = b64.indexOf('=');
		placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0;

		// base64 is 4/3 + up to two characters of the original data
		arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders);

		// if there are placeholders, only get up to the last complete 4 chars
		l = placeHolders > 0 ? b64.length - 4 : b64.length;

		for (i = 0, j = 0; i < l; i += 4, j += 3) {
			tmp = (lookup.indexOf(b64[i]) << 18) | (lookup.indexOf(b64[i + 1]) << 12) | (lookup.indexOf(b64[i + 2]) << 6) | lookup.indexOf(b64[i + 3]);
			arr.push((tmp & 0xFF0000) >> 16);
			arr.push((tmp & 0xFF00) >> 8);
			arr.push(tmp & 0xFF);
		}

		if (placeHolders === 2) {
			tmp = (lookup.indexOf(b64[i]) << 2) | (lookup.indexOf(b64[i + 1]) >> 4);
			arr.push(tmp & 0xFF);
		} else if (placeHolders === 1) {
			tmp = (lookup.indexOf(b64[i]) << 10) | (lookup.indexOf(b64[i + 1]) << 4) | (lookup.indexOf(b64[i + 2]) >> 2);
			arr.push((tmp >> 8) & 0xFF);
			arr.push(tmp & 0xFF);
		}

		return arr;
	}

	function uint8ToBase64(uint8) {
		var i,
			extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
			output = "",
			temp, length;

		function tripletToBase64 (num) {
			return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
		};

		// go through the array every three bytes, we'll deal with trailing stuff later
		for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
			temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
			output += tripletToBase64(temp);
		}

		// pad the end with zeros, but make sure to not forget the extra bytes
		switch (extraBytes) {
			case 1:
				temp = uint8[uint8.length - 1];
				output += lookup[temp >> 2];
				output += lookup[(temp << 4) & 0x3F];
				output += '==';
				break;
			case 2:
				temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]);
				output += lookup[temp >> 10];
				output += lookup[(temp >> 4) & 0x3F];
				output += lookup[(temp << 2) & 0x3F];
				output += '=';
				break;
		}

		return output;
	}

	module.exports.toByteArray = b64ToByteArray;
	module.exports.fromByteArray = uint8ToBase64;
}());

},{}],5:[function(require,module,exports){


//
// The shims in this file are not fully implemented shims for the ES5
// features, but do work for the particular usecases there is in
// the other modules.
//

var toString = Object.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;

// Array.isArray is supported in IE9
function isArray(xs) {
  return toString.call(xs) === '[object Array]';
}
exports.isArray = typeof Array.isArray === 'function' ? Array.isArray : isArray;

// Array.prototype.indexOf is supported in IE9
exports.indexOf = function indexOf(xs, x) {
  if (xs.indexOf) return xs.indexOf(x);
  for (var i = 0; i < xs.length; i++) {
    if (x === xs[i]) return i;
  }
  return -1;
};

// Array.prototype.filter is supported in IE9
exports.filter = function filter(xs, fn) {
  if (xs.filter) return xs.filter(fn);
  var res = [];
  for (var i = 0; i < xs.length; i++) {
    if (fn(xs[i], i, xs)) res.push(xs[i]);
  }
  return res;
};

// Array.prototype.forEach is supported in IE9
exports.forEach = function forEach(xs, fn, self) {
  if (xs.forEach) return xs.forEach(fn, self);
  for (var i = 0; i < xs.length; i++) {
    fn.call(self, xs[i], i, xs);
  }
};

// Array.prototype.map is supported in IE9
exports.map = function map(xs, fn) {
  if (xs.map) return xs.map(fn);
  var out = new Array(xs.length);
  for (var i = 0; i < xs.length; i++) {
    out[i] = fn(xs[i], i, xs);
  }
  return out;
};

// Array.prototype.reduce is supported in IE9
exports.reduce = function reduce(array, callback, opt_initialValue) {
  if (array.reduce) return array.reduce(callback, opt_initialValue);
  var value, isValueSet = false;

  if (2 < arguments.length) {
    value = opt_initialValue;
    isValueSet = true;
  }
  for (var i = 0, l = array.length; l > i; ++i) {
    if (array.hasOwnProperty(i)) {
      if (isValueSet) {
        value = callback(value, array[i], i, array);
      }
      else {
        value = array[i];
        isValueSet = true;
      }
    }
  }

  return value;
};

// String.prototype.substr - negative index don't work in IE8
if ('ab'.substr(-1) !== 'b') {
  exports.substr = function (str, start, length) {
    // did we get a negative start, calculate how much it is from the beginning of the string
    if (start < 0) start = str.length + start;

    // call the original function
    return str.substr(start, length);
  };
} else {
  exports.substr = function (str, start, length) {
    return str.substr(start, length);
  };
}

// String.prototype.trim is supported in IE9
exports.trim = function (str) {
  if (str.trim) return str.trim();
  return str.replace(/^\s+|\s+$/g, '');
};

// Function.prototype.bind is supported in IE9
exports.bind = function () {
  var args = Array.prototype.slice.call(arguments);
  var fn = args.shift();
  if (fn.bind) return fn.bind.apply(fn, args);
  var self = args.shift();
  return function () {
    fn.apply(self, args.concat([Array.prototype.slice.call(arguments)]));
  };
};

// Object.create is supported in IE9
function create(prototype, properties) {
  var object;
  if (prototype === null) {
    object = { '__proto__' : null };
  }
  else {
    if (typeof prototype !== 'object') {
      throw new TypeError(
        'typeof prototype[' + (typeof prototype) + '] != \'object\''
      );
    }
    var Type = function () {};
    Type.prototype = prototype;
    object = new Type();
    object.__proto__ = prototype;
  }
  if (typeof properties !== 'undefined' && Object.defineProperties) {
    Object.defineProperties(object, properties);
  }
  return object;
}
exports.create = typeof Object.create === 'function' ? Object.create : create;

// Object.keys and Object.getOwnPropertyNames is supported in IE9 however
// they do show a description and number property on Error objects
function notObject(object) {
  return ((typeof object != "object" && typeof object != "function") || object === null);
}

function keysShim(object) {
  if (notObject(object)) {
    throw new TypeError("Object.keys called on a non-object");
  }

  var result = [];
  for (var name in object) {
    if (hasOwnProperty.call(object, name)) {
      result.push(name);
    }
  }
  return result;
}

// getOwnPropertyNames is almost the same as Object.keys one key feature
//  is that it returns hidden properties, since that can't be implemented,
//  this feature gets reduced so it just shows the length property on arrays
function propertyShim(object) {
  if (notObject(object)) {
    throw new TypeError("Object.getOwnPropertyNames called on a non-object");
  }

  var result = keysShim(object);
  if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) {
    result.push('length');
  }
  return result;
}

var keys = typeof Object.keys === 'function' ? Object.keys : keysShim;
var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ?
  Object.getOwnPropertyNames : propertyShim;

if (new Error().hasOwnProperty('description')) {
  var ERROR_PROPERTY_FILTER = function (obj, array) {
    if (toString.call(obj) === '[object Error]') {
      array = exports.filter(array, function (name) {
        return name !== 'description' && name !== 'number' && name !== 'message';
      });
    }
    return array;
  };

  exports.keys = function (object) {
    return ERROR_PROPERTY_FILTER(object, keys(object));
  };
  exports.getOwnPropertyNames = function (object) {
    return ERROR_PROPERTY_FILTER(object, getOwnPropertyNames(object));
  };
} else {
  exports.keys = keys;
  exports.getOwnPropertyNames = getOwnPropertyNames;
}

// Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements
function valueObject(value, key) {
  return { value: value[key] };
}

if (typeof Object.getOwnPropertyDescriptor === 'function') {
  try {
    Object.getOwnPropertyDescriptor({'a': 1}, 'a');
    exports.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  } catch (e) {
    // IE8 dom element issue - use a try catch and default to valueObject
    exports.getOwnPropertyDescriptor = function (value, key) {
      try {
        return Object.getOwnPropertyDescriptor(value, key);
      } catch (e) {
        return valueObject(value, key);
      }
    };
  }
} else {
  exports.getOwnPropertyDescriptor = valueObject;
}

},{}],6:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// UTILITY
var util = require('util');
var shims = require('_shims');
var pSlice = Array.prototype.slice;

// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.

var assert = module.exports = ok;

// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
//                             actual: actual,
//                             expected: expected })

assert.AssertionError = function AssertionError(options) {
  this.name = 'AssertionError';
  this.actual = options.actual;
  this.expected = options.expected;
  this.operator = options.operator;
  this.message = options.message || getMessage(this);
};

// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);

function replacer(key, value) {
  if (util.isUndefined(value)) {
    return '' + value;
  }
  if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) {
    return value.toString();
  }
  if (util.isFunction(value) || util.isRegExp(value)) {
    return value.toString();
  }
  return value;
}

function truncate(s, n) {
  if (util.isString(s)) {
    return s.length < n ? s : s.slice(0, n);
  } else {
    return s;
  }
}

function getMessage(self) {
  return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
         self.operator + ' ' +
         truncate(JSON.stringify(self.expected, replacer), 128);
}

// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.

// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided.  All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.

function fail(actual, expected, message, operator, stackStartFunction) {
  throw new assert.AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: operator,
    stackStartFunction: stackStartFunction
  });
}

// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;

// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.

function ok(value, message) {
  if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;

// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);

assert.equal = function equal(actual, expected, message) {
  if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};

// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);

assert.notEqual = function notEqual(actual, expected, message) {
  if (actual == expected) {
    fail(actual, expected, message, '!=', assert.notEqual);
  }
};

// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);

assert.deepEqual = function deepEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected)) {
    fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  }
};

function _deepEqual(actual, expected) {
  // 7.1. All identical values are equivalent, as determined by ===.
  if (actual === expected) {
    return true;

  } else if (util.isBuffer(actual) && util.isBuffer(expected)) {
    if (actual.length != expected.length) return false;

    for (var i = 0; i < actual.length; i++) {
      if (actual[i] !== expected[i]) return false;
    }

    return true;

  // 7.2. If the expected value is a Date object, the actual value is
  // equivalent if it is also a Date object that refers to the same time.
  } else if (util.isDate(actual) && util.isDate(expected)) {
    return actual.getTime() === expected.getTime();

  // 7.3 If the expected value is a RegExp object, the actual value is
  // equivalent if it is also a RegExp object with the same source and
  // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
    return actual.source === expected.source &&
           actual.global === expected.global &&
           actual.multiline === expected.multiline &&
           actual.lastIndex === expected.lastIndex &&
           actual.ignoreCase === expected.ignoreCase;

  // 7.4. Other pairs that do not both pass typeof value == 'object',
  // equivalence is determined by ==.
  } else if (!util.isObject(actual) && !util.isObject(expected)) {
    return actual == expected;

  // 7.5 For all other Object pairs, including Array objects, equivalence is
  // determined by having the same number of owned properties (as verified
  // with Object.prototype.hasOwnProperty.call), the same set of keys
  // (although not necessarily the same order), equivalent values for every
  // corresponding key, and an identical 'prototype' property. Note: this
  // accounts for both named and indexed properties on Arrays.
  } else {
    return objEquiv(actual, expected);
  }
}

function isArguments(object) {
  return Object.prototype.toString.call(object) == '[object Arguments]';
}

function objEquiv(a, b) {
  if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
    return false;
  // an identical 'prototype' property.
  if (a.prototype !== b.prototype) return false;
  //~~~I've managed to break Object.keys through screwy arguments passing.
  //   Converting to array solves the problem.
  if (isArguments(a)) {
    if (!isArguments(b)) {
      return false;
    }
    a = pSlice.call(a);
    b = pSlice.call(b);
    return _deepEqual(a, b);
  }
  try {
    var ka = shims.keys(a),
        kb = shims.keys(b),
        key, i;
  } catch (e) {//happens when one is a string literal and the other isn't
    return false;
  }
  // having the same number of owned properties (keys incorporates
  // hasOwnProperty)
  if (ka.length != kb.length)
    return false;
  //the same set of keys (although not necessarily the same order),
  ka.sort();
  kb.sort();
  //~~~cheap key test
  for (i = ka.length - 1; i >= 0; i--) {
    if (ka[i] != kb[i])
      return false;
  }
  //equivalent values for every corresponding key, and
  //~~~possibly expensive deep test
  for (i = ka.length - 1; i >= 0; i--) {
    key = ka[i];
    if (!_deepEqual(a[key], b[key])) return false;
  }
  return true;
}

// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);

assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  if (_deepEqual(actual, expected)) {
    fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  }
};

// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);

assert.strictEqual = function strictEqual(actual, expected, message) {
  if (actual !== expected) {
    fail(actual, expected, message, '===', assert.strictEqual);
  }
};

// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==.  assert.notStrictEqual(actual, expected, message_opt);

assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (actual === expected) {
    fail(actual, expected, message, '!==', assert.notStrictEqual);
  }
};

function expectedException(actual, expected) {
  if (!actual || !expected) {
    return false;
  }

  if (Object.prototype.toString.call(expected) == '[object RegExp]') {
    return expected.test(actual);
  } else if (actual instanceof expected) {
    return true;
  } else if (expected.call({}, actual) === true) {
    return true;
  }

  return false;
}

function _throws(shouldThrow, block, expected, message) {
  var actual;

  if (util.isString(expected)) {
    message = expected;
    expected = null;
  }

  try {
    block();
  } catch (e) {
    actual = e;
  }

  message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
            (message ? ' ' + message : '.');

  if (shouldThrow && !actual) {
    fail(actual, expected, 'Missing expected exception' + message);
  }

  if (!shouldThrow && expectedException(actual, expected)) {
    fail(actual, expected, 'Got unwanted exception' + message);
  }

  if ((shouldThrow && actual && expected &&
      !expectedException(actual, expected)) || (!shouldThrow && actual)) {
    throw actual;
  }
}

// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);

assert.throws = function(block, /*optional*/error, /*optional*/message) {
  _throws.apply(this, [true].concat(pSlice.call(arguments)));
};

// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/message) {
  _throws.apply(this, [false].concat(pSlice.call(arguments)));
};

assert.ifError = function(err) { if (err) {throw err;}};
},{"_shims":5,"util":7}],7:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var shims = require('_shims');

var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
  if (!isString(f)) {
    var objects = [];
    for (var i = 0; i < arguments.length; i++) {
      objects.push(inspect(arguments[i]));
    }
    return objects.join(' ');
  }

  var i = 1;
  var args = arguments;
  var len = args.length;
  var str = String(f).replace(formatRegExp, function(x) {
    if (x === '%%') return '%';
    if (i >= len) return x;
    switch (x) {
      case '%s': return String(args[i++]);
      case '%d': return Number(args[i++]);
      case '%j':
        try {
          return JSON.stringify(args[i++]);
        } catch (_) {
          return '[Circular]';
        }
      default:
        return x;
    }
  });
  for (var x = args[i]; i < len; x = args[++i]) {
    if (isNull(x) || !isObject(x)) {
      str += ' ' + x;
    } else {
      str += ' ' + inspect(x);
    }
  }
  return str;
};

/**
 * Echos the value of a value. Trys to print the value out
 * in the best way possible given the different types.
 *
 * @param {Object} obj The object to print out.
 * @param {Object} opts Optional options object that alters the output.
 */
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
  // default options
  var ctx = {
    seen: [],
    stylize: stylizeNoColor
  };
  // legacy...
  if (arguments.length >= 3) ctx.depth = arguments[2];
  if (arguments.length >= 4) ctx.colors = arguments[3];
  if (isBoolean(opts)) {
    // legacy...
    ctx.showHidden = opts;
  } else if (opts) {
    // got an "options" object
    exports._extend(ctx, opts);
  }
  // set default options
  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  if (isUndefined(ctx.depth)) ctx.depth = 2;
  if (isUndefined(ctx.colors)) ctx.colors = false;
  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  if (ctx.colors) ctx.stylize = stylizeWithColor;
  return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;


// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
  'bold' : [1, 22],
  'italic' : [3, 23],
  'underline' : [4, 24],
  'inverse' : [7, 27],
  'white' : [37, 39],
  'grey' : [90, 39],
  'black' : [30, 39],
  'blue' : [34, 39],
  'cyan' : [36, 39],
  'green' : [32, 39],
  'magenta' : [35, 39],
  'red' : [31, 39],
  'yellow' : [33, 39]
};

// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
  'special': 'cyan',
  'number': 'yellow',
  'boolean': 'yellow',
  'undefined': 'grey',
  'null': 'bold',
  'string': 'green',
  'date': 'magenta',
  // "name": intentionally not styling
  'regexp': 'red'
};


function stylizeWithColor(str, styleType) {
  var style = inspect.styles[styleType];

  if (style) {
    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
           '\u001b[' + inspect.colors[style][1] + 'm';
  } else {
    return str;
  }
}


function stylizeNoColor(str, styleType) {
  return str;
}


function arrayToHash(array) {
  var hash = {};

  shims.forEach(array, function(val, idx) {
    hash[val] = true;
  });

  return hash;
}


function formatValue(ctx, value, recurseTimes) {
  // Provide a hook for user-specified inspect functions.
  // Check that value is an object with an inspect function on it
  if (ctx.customInspect &&
      value &&
      isFunction(value.inspect) &&
      // Filter out the util module, it's inspect function is special
      value.inspect !== exports.inspect &&
      // Also filter out any prototype objects using the circular check.
      !(value.constructor && value.constructor.prototype === value)) {
    var ret = value.inspect(recurseTimes);
    if (!isString(ret)) {
      ret = formatValue(ctx, ret, recurseTimes);
    }
    return ret;
  }

  // Primitive types cannot have properties
  var primitive = formatPrimitive(ctx, value);
  if (primitive) {
    return primitive;
  }

  // Look up the keys of the object.
  var keys = shims.keys(value);
  var visibleKeys = arrayToHash(keys);

  if (ctx.showHidden) {
    keys = shims.getOwnPropertyNames(value);
  }

  // Some type of object without properties can be shortcutted.
  if (keys.length === 0) {
    if (isFunction(value)) {
      var name = value.name ? ': ' + value.name : '';
      return ctx.stylize('[Function' + name + ']', 'special');
    }
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    }
    if (isDate(value)) {
      return ctx.stylize(Date.prototype.toString.call(value), 'date');
    }
    if (isError(value)) {
      return formatError(value);
    }
  }

  var base = '', array = false, braces = ['{', '}'];

  // Make Array say that they are Array
  if (isArray(value)) {
    array = true;
    braces = ['[', ']'];
  }

  // Make functions say that they are functions
  if (isFunction(value)) {
    var n = value.name ? ': ' + value.name : '';
    base = ' [Function' + n + ']';
  }

  // Make RegExps say that they are RegExps
  if (isRegExp(value)) {
    base = ' ' + RegExp.prototype.toString.call(value);
  }

  // Make dates with properties first say the date
  if (isDate(value)) {
    base = ' ' + Date.prototype.toUTCString.call(value);
  }

  // Make error with message first say the error
  if (isError(value)) {
    base = ' ' + formatError(value);
  }

  if (keys.length === 0 && (!array || value.length == 0)) {
    return braces[0] + base + braces[1];
  }

  if (recurseTimes < 0) {
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    } else {
      return ctx.stylize('[Object]', 'special');
    }
  }

  ctx.seen.push(value);

  var output;
  if (array) {
    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  } else {
    output = keys.map(function(key) {
      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
    });
  }

  ctx.seen.pop();

  return reduceToSingleString(output, base, braces);
}


function formatPrimitive(ctx, value) {
  if (isUndefined(value))
    return ctx.stylize('undefined', 'undefined');
  if (isString(value)) {
    var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                             .replace(/'/g, "\\'")
                                             .replace(/\\"/g, '"') + '\'';
    return ctx.stylize(simple, 'string');
  }
  if (isNumber(value))
    return ctx.stylize('' + value, 'number');
  if (isBoolean(value))
    return ctx.stylize('' + value, 'boolean');
  // For some reason typeof null is "object", so special case here.
  if (isNull(value))
    return ctx.stylize('null', 'null');
}


function formatError(value) {
  return '[' + Error.prototype.toString.call(value) + ']';
}


function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  var output = [];
  for (var i = 0, l = value.length; i < l; ++i) {
    if (hasOwnProperty(value, String(i))) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          String(i), true));
    } else {
      output.push('');
    }
  }

  shims.forEach(keys, function(key) {
    if (!key.match(/^\d+$/)) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          key, true));
    }
  });
  return output;
}


function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  var name, str, desc;
  desc = shims.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  if (desc.get) {
    if (desc.set) {
      str = ctx.stylize('[Getter/Setter]', 'special');
    } else {
      str = ctx.stylize('[Getter]', 'special');
    }
  } else {
    if (desc.set) {
      str = ctx.stylize('[Setter]', 'special');
    }
  }

  if (!hasOwnProperty(visibleKeys, key)) {
    name = '[' + key + ']';
  }
  if (!str) {
    if (shims.indexOf(ctx.seen, desc.value) < 0) {
      if (isNull(recurseTimes)) {
        str = formatValue(ctx, desc.value, null);
      } else {
        str = formatValue(ctx, desc.value, recurseTimes - 1);
      }
      if (str.indexOf('\n') > -1) {
        if (array) {
          str = str.split('\n').map(function(line) {
            return '  ' + line;
          }).join('\n').substr(2);
        } else {
          str = '\n' + str.split('\n').map(function(line) {
            return '   ' + line;
          }).join('\n');
        }
      }
    } else {
      str = ctx.stylize('[Circular]', 'special');
    }
  }
  if (isUndefined(name)) {
    if (array && key.match(/^\d+$/)) {
      return str;
    }
    name = JSON.stringify('' + key);
    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
      name = name.substr(1, name.length - 2);
      name = ctx.stylize(name, 'name');
    } else {
      name = name.replace(/'/g, "\\'")
                 .replace(/\\"/g, '"')
                 .replace(/(^"|"$)/g, "'");
      name = ctx.stylize(name, 'string');
    }
  }

  return name + ': ' + str;
}


function reduceToSingleString(output, base, braces) {
  var numLinesEst = 0;
  var length = shims.reduce(output, function(prev, cur) {
    numLinesEst++;
    if (cur.indexOf('\n') >= 0) numLinesEst++;
    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  }, 0);

  if (length > 60) {
    return braces[0] +
           (base === '' ? '' : base + '\n ') +
           ' ' +
           output.join(',\n  ') +
           ' ' +
           braces[1];
  }

  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}


// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
  return shims.isArray(ar);
}
exports.isArray = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;

function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;

function isRegExp(re) {
  return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg;
}
exports.isObject = isObject;

function isDate(d) {
  return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;

function isError(e) {
  return isObject(e) && objectToString(e) === '[object Error]';
}
exports.isError = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;

function isBuffer(arg) {
  return arg instanceof Buffer;
}
exports.isBuffer = isBuffer;

function objectToString(o) {
  return Object.prototype.toString.call(o);
}


function pad(n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}


var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
              'Oct', 'Nov', 'Dec'];

// 26 Feb 16:19:34
function timestamp() {
  var d = new Date();
  var time = [pad(d.getHours()),
              pad(d.getMinutes()),
              pad(d.getSeconds())].join(':');
  return [d.getDate(), months[d.getMonth()], time].join(' ');
}


// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};


/**
 * Inherit the prototype methods from one constructor into another.
 *
 * The Function.prototype.inherits from lang.js rewritten as a standalone
 * function (not on Function.prototype). NOTE: If this file is to be loaded
 * during bootstrapping this function needs to be rewritten using some native
 * functions as prototype setup using normal JavaScript does not work as
 * expected during bootstrapping (see mirror.js in r114903).
 *
 * @param {function} ctor Constructor function which needs to inherit the
 *     prototype.
 * @param {function} superCtor Constructor function to inherit prototype from.
 */
exports.inherits = function(ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = shims.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
};

exports._extend = function(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || !isObject(add)) return origin;

  var keys = shims.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
};

function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}

},{"_shims":5}]},{},[])
;;module.exports=require("buffer-browserify")

},{}],13:[function(require,module,exports){
// shim for using process in browser

var process = module.exports = {};

process.nextTick = (function () {
    var canSetImmediate = typeof window !== 'undefined'
    && window.setImmediate;
    var canPost = typeof window !== 'undefined'
    && window.postMessage && window.addEventListener
    ;

    if (canSetImmediate) {
        return function (f) { return window.setImmediate(f) };
    }

    if (canPost) {
        var queue = [];
        window.addEventListener('message', function (ev) {
            var source = ev.source;
            if ((source === window || source === null) && ev.data === 'process-tick') {
                ev.stopPropagation();
                if (queue.length > 0) {
                    var fn = queue.shift();
                    fn();
                }
            }
        }, true);

        return function nextTick(fn) {
            queue.push(fn);
            window.postMessage('process-tick', '*');
        };
    }

    return function nextTick(fn) {
        setTimeout(fn, 0);
    };
})();

process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];

process.binding = function (name) {
    throw new Error('process.binding is not supported');
}

// (shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};

},{}],14:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

module.exports = {
  'compact': require('./arrays/compact'),
  'difference': require('./arrays/difference'),
  'drop': require('./arrays/rest'),
  'findIndex': require('./arrays/findIndex'),
  'findLastIndex': require('./arrays/findLastIndex'),
  'first': require('./arrays/first'),
  'flatten': require('./arrays/flatten'),
  'head': require('./arrays/first'),
  'indexOf': require('./arrays/indexOf'),
  'initial': require('./arrays/initial'),
  'intersection': require('./arrays/intersection'),
  'last': require('./arrays/last'),
  'lastIndexOf': require('./arrays/lastIndexOf'),
  'object': require('./arrays/zipObject'),
  'pull': require('./arrays/pull'),
  'range': require('./arrays/range'),
  'remove': require('./arrays/remove'),
  'rest': require('./arrays/rest'),
  'sortedIndex': require('./arrays/sortedIndex'),
  'tail': require('./arrays/rest'),
  'take': require('./arrays/first'),
  'union': require('./arrays/union'),
  'uniq': require('./arrays/uniq'),
  'unique': require('./arrays/uniq'),
  'unzip': require('./arrays/zip'),
  'without': require('./arrays/without'),
  'xor': require('./arrays/xor'),
  'zip': require('./arrays/zip'),
  'zipObject': require('./arrays/zipObject')
};

},{"./arrays/compact":15,"./arrays/difference":16,"./arrays/findIndex":17,"./arrays/findLastIndex":18,"./arrays/first":19,"./arrays/flatten":20,"./arrays/indexOf":21,"./arrays/initial":22,"./arrays/intersection":23,"./arrays/last":24,"./arrays/lastIndexOf":25,"./arrays/pull":26,"./arrays/range":27,"./arrays/remove":28,"./arrays/rest":29,"./arrays/sortedIndex":30,"./arrays/union":31,"./arrays/uniq":32,"./arrays/without":33,"./arrays/xor":34,"./arrays/zip":35,"./arrays/zipObject":36}],15:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Creates an array with all falsey values removed. The values `false`, `null`,
 * `0`, `""`, `undefined`, and `NaN` are all falsey.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to compact.
 * @returns {Array} Returns a new array of filtered values.
 * @example
 *
 * _.compact([0, 1, false, 2, '', 3]);
 * // => [1, 2, 3]
 */
function compact(array) {
  var index = -1,
      length = array ? array.length : 0,
      result = [];

  while (++index < length) {
    var value = array[index];
    if (value) {
      result.push(value);
    }
  }
  return result;
}

module.exports = compact;

},{}],16:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseDifference = require('../internals/baseDifference'),
    baseFlatten = require('../internals/baseFlatten');

/**
 * Creates an array excluding all values of the provided arrays using strict
 * equality for comparisons, i.e. `===`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to process.
 * @param {...Array} [values] The arrays of values to exclude.
 * @returns {Array} Returns a new array of filtered values.
 * @example
 *
 * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
 * // => [1, 3, 4]
 */
function difference(array) {
  return baseDifference(array, baseFlatten(arguments, true, true, 1));
}

module.exports = difference;

},{"../internals/baseDifference":94,"../internals/baseFlatten":95}],17:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback');

/**
 * This method is like `_.find` except that it returns the index of the first
 * element that passes the callback check, instead of the element itself.
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to search.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {number} Returns the index of the found element, else `-1`.
 * @example
 *
 * var characters = [
 *   { 'name': 'barney',  'age': 36, 'blocked': false },
 *   { 'name': 'fred',    'age': 40, 'blocked': true },
 *   { 'name': 'pebbles', 'age': 1,  'blocked': false }
 * ];
 *
 * _.findIndex(characters, function(chr) {
 *   return chr.age < 20;
 * });
 * // => 2
 *
 * // using "_.where" callback shorthand
 * _.findIndex(characters, { 'age': 36 });
 * // => 0
 *
 * // using "_.pluck" callback shorthand
 * _.findIndex(characters, 'blocked');
 * // => 1
 */
function findIndex(array, callback, thisArg) {
  var index = -1,
      length = array ? array.length : 0;

  callback = createCallback(callback, thisArg, 3);
  while (++index < length) {
    if (callback(array[index], index, array)) {
      return index;
    }
  }
  return -1;
}

module.exports = findIndex;

},{"../functions/createCallback":76}],18:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback');

/**
 * This method is like `_.findIndex` except that it iterates over elements
 * of a `collection` from right to left.
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to search.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {number} Returns the index of the found element, else `-1`.
 * @example
 *
 * var characters = [
 *   { 'name': 'barney',  'age': 36, 'blocked': true },
 *   { 'name': 'fred',    'age': 40, 'blocked': false },
 *   { 'name': 'pebbles', 'age': 1,  'blocked': true }
 * ];
 *
 * _.findLastIndex(characters, function(chr) {
 *   return chr.age > 30;
 * });
 * // => 1
 *
 * // using "_.where" callback shorthand
 * _.findLastIndex(characters, { 'age': 36 });
 * // => 0
 *
 * // using "_.pluck" callback shorthand
 * _.findLastIndex(characters, 'blocked');
 * // => 2
 */
function findLastIndex(array, callback, thisArg) {
  var length = array ? array.length : 0;
  callback = createCallback(callback, thisArg, 3);
  while (length--) {
    if (callback(array[length], length, array)) {
      return length;
    }
  }
  return -1;
}

module.exports = findLastIndex;

},{"../functions/createCallback":76}],19:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    slice = require('../internals/slice');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max,
    nativeMin = Math.min;

/**
 * Gets the first element or first `n` elements of an array. If a callback
 * is provided elements at the beginning of the array are returned as long
 * as the callback returns truey. The callback is bound to `thisArg` and
 * invoked with three arguments; (value, index, array).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @alias head, take
 * @category Arrays
 * @param {Array} array The array to query.
 * @param {Function|Object|number|string} [callback] The function called
 *  per element or the number of elements to return. If a property name or
 *  object is provided it will be used to create a "_.pluck" or "_.where"
 *  style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {*} Returns the first element(s) of `array`.
 * @example
 *
 * _.first([1, 2, 3]);
 * // => 1
 *
 * _.first([1, 2, 3], 2);
 * // => [1, 2]
 *
 * _.first([1, 2, 3], function(num) {
 *   return num < 3;
 * });
 * // => [1, 2]
 *
 * var characters = [
 *   { 'name': 'barney',  'blocked': true,  'employer': 'slate' },
 *   { 'name': 'fred',    'blocked': false, 'employer': 'slate' },
 *   { 'name': 'pebbles', 'blocked': true,  'employer': 'na' }
 * ];
 *
 * // using "_.pluck" callback shorthand
 * _.first(characters, 'blocked');
 * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }]
 *
 * // using "_.where" callback shorthand
 * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name');
 * // => ['barney', 'fred']
 */
function first(array, callback, thisArg) {
  var n = 0,
      length = array ? array.length : 0;

  if (typeof callback != 'number' && callback != null) {
    var index = -1;
    callback = createCallback(callback, thisArg, 3);
    while (++index < length && callback(array[index], index, array)) {
      n++;
    }
  } else {
    n = callback;
    if (n == null || thisArg) {
      return array ? array[0] : undefined;
    }
  }
  return slice(array, 0, nativeMin(nativeMax(0, n), length));
}

module.exports = first;

},{"../functions/createCallback":76,"../internals/slice":129}],20:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseFlatten = require('../internals/baseFlatten'),
    map = require('../collections/map');

/**
 * Flattens a nested array (the nesting can be to any depth). If `isShallow`
 * is truey, the array will only be flattened a single level. If a callback
 * is provided each element of the array is passed through the callback before
 * flattening. The callback is bound to `thisArg` and invoked with three
 * arguments; (value, index, array).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to flatten.
 * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array} Returns a new flattened array.
 * @example
 *
 * _.flatten([1, [2], [3, [[4]]]]);
 * // => [1, 2, 3, 4];
 *
 * _.flatten([1, [2], [3, [[4]]]], true);
 * // => [1, 2, 3, [[4]]];
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] },
 *   { 'name': 'fred',   'age': 40, 'pets': ['baby puss', 'dino'] }
 * ];
 *
 * // using "_.pluck" callback shorthand
 * _.flatten(characters, 'pets');
 * // => ['hoppy', 'baby puss', 'dino']
 */
function flatten(array, isShallow, callback, thisArg) {
  // juggle arguments
  if (typeof isShallow != 'boolean' && isShallow != null) {
    thisArg = callback;
    callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow;
    isShallow = false;
  }
  if (callback != null) {
    array = map(array, callback, thisArg);
  }
  return baseFlatten(array, isShallow);
}

module.exports = flatten;

},{"../collections/map":56,"../internals/baseFlatten":95}],21:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseIndexOf = require('../internals/baseIndexOf'),
    sortedIndex = require('./sortedIndex');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max;

/**
 * Gets the index at which the first occurrence of `value` is found using
 * strict equality for comparisons, i.e. `===`. If the array is already sorted
 * providing `true` for `fromIndex` will run a faster binary search.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to search.
 * @param {*} value The value to search for.
 * @param {boolean|number} [fromIndex=0] The index to search from or `true`
 *  to perform a binary search on a sorted array.
 * @returns {number} Returns the index of the matched value or `-1`.
 * @example
 *
 * _.indexOf([1, 2, 3, 1, 2, 3], 2);
 * // => 1
 *
 * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
 * // => 4
 *
 * _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
 * // => 2
 */
function indexOf(array, value, fromIndex) {
  if (typeof fromIndex == 'number') {
    var length = array ? array.length : 0;
    fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
  } else if (fromIndex) {
    var index = sortedIndex(array, value);
    return array[index] === value ? index : -1;
  }
  return baseIndexOf(array, value, fromIndex);
}

module.exports = indexOf;

},{"../internals/baseIndexOf":96,"./sortedIndex":30}],22:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    slice = require('../internals/slice');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max,
    nativeMin = Math.min;

/**
 * Gets all but the last element or last `n` elements of an array. If a
 * callback is provided elements at the end of the array are excluded from
 * the result as long as the callback returns truey. The callback is bound
 * to `thisArg` and invoked with three arguments; (value, index, array).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to query.
 * @param {Function|Object|number|string} [callback=1] The function called
 *  per element or the number of elements to exclude. If a property name or
 *  object is provided it will be used to create a "_.pluck" or "_.where"
 *  style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array} Returns a slice of `array`.
 * @example
 *
 * _.initial([1, 2, 3]);
 * // => [1, 2]
 *
 * _.initial([1, 2, 3], 2);
 * // => [1]
 *
 * _.initial([1, 2, 3], function(num) {
 *   return num > 1;
 * });
 * // => [1]
 *
 * var characters = [
 *   { 'name': 'barney',  'blocked': false, 'employer': 'slate' },
 *   { 'name': 'fred',    'blocked': true,  'employer': 'slate' },
 *   { 'name': 'pebbles', 'blocked': true,  'employer': 'na' }
 * ];
 *
 * // using "_.pluck" callback shorthand
 * _.initial(characters, 'blocked');
 * // => [{ 'name': 'barney',  'blocked': false, 'employer': 'slate' }]
 *
 * // using "_.where" callback shorthand
 * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name');
 * // => ['barney', 'fred']
 */
function initial(array, callback, thisArg) {
  var n = 0,
      length = array ? array.length : 0;

  if (typeof callback != 'number' && callback != null) {
    var index = length;
    callback = createCallback(callback, thisArg, 3);
    while (index-- && callback(array[index], index, array)) {
      n++;
    }
  } else {
    n = (callback == null || thisArg) ? 1 : callback || n;
  }
  return slice(array, 0, nativeMin(nativeMax(0, length - n), length));
}

module.exports = initial;

},{"../functions/createCallback":76,"../internals/slice":129}],23:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseIndexOf = require('../internals/baseIndexOf'),
    cacheIndexOf = require('../internals/cacheIndexOf'),
    createCache = require('../internals/createCache'),
    getArray = require('../internals/getArray'),
    isArguments = require('../objects/isArguments'),
    isArray = require('../objects/isArray'),
    largeArraySize = require('../internals/largeArraySize'),
    releaseArray = require('../internals/releaseArray'),
    releaseObject = require('../internals/releaseObject');

/**
 * Creates an array of unique values present in all provided arrays using
 * strict equality for comparisons, i.e. `===`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {...Array} [array] The arrays to inspect.
 * @returns {Array} Returns an array of shared values.
 * @example
 *
 * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]);
 * // => [1, 2]
 */
function intersection() {
  var args = [],
      argsIndex = -1,
      argsLength = arguments.length,
      caches = getArray(),
      indexOf = baseIndexOf,
      trustIndexOf = indexOf === baseIndexOf,
      seen = getArray();

  while (++argsIndex < argsLength) {
    var value = arguments[argsIndex];
    if (isArray(value) || isArguments(value)) {
      args.push(value);
      caches.push(trustIndexOf && value.length >= largeArraySize &&
        createCache(argsIndex ? args[argsIndex] : seen));
    }
  }
  var array = args[0],
      index = -1,
      length = array ? array.length : 0,
      result = [];

  outer:
  while (++index < length) {
    var cache = caches[0];
    value = array[index];

    if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) {
      argsIndex = argsLength;
      (cache || seen).push(value);
      while (--argsIndex) {
        cache = caches[argsIndex];
        if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
          continue outer;
        }
      }
      result.push(value);
    }
  }
  while (argsLength--) {
    cache = caches[argsLength];
    if (cache) {
      releaseObject(cache);
    }
  }
  releaseArray(caches);
  releaseArray(seen);
  return result;
}

module.exports = intersection;

},{"../internals/baseIndexOf":96,"../internals/cacheIndexOf":101,"../internals/createCache":106,"../internals/getArray":110,"../internals/largeArraySize":116,"../internals/releaseArray":124,"../internals/releaseObject":125,"../objects/isArguments":146,"../objects/isArray":147}],24:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    slice = require('../internals/slice');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max;

/**
 * Gets the last element or last `n` elements of an array. If a callback is
 * provided elements at the end of the array are returned as long as the
 * callback returns truey. The callback is bound to `thisArg` and invoked
 * with three arguments; (value, index, array).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to query.
 * @param {Function|Object|number|string} [callback] The function called
 *  per element or the number of elements to return. If a property name or
 *  object is provided it will be used to create a "_.pluck" or "_.where"
 *  style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {*} Returns the last element(s) of `array`.
 * @example
 *
 * _.last([1, 2, 3]);
 * // => 3
 *
 * _.last([1, 2, 3], 2);
 * // => [2, 3]
 *
 * _.last([1, 2, 3], function(num) {
 *   return num > 1;
 * });
 * // => [2, 3]
 *
 * var characters = [
 *   { 'name': 'barney',  'blocked': false, 'employer': 'slate' },
 *   { 'name': 'fred',    'blocked': true,  'employer': 'slate' },
 *   { 'name': 'pebbles', 'blocked': true,  'employer': 'na' }
 * ];
 *
 * // using "_.pluck" callback shorthand
 * _.pluck(_.last(characters, 'blocked'), 'name');
 * // => ['fred', 'pebbles']
 *
 * // using "_.where" callback shorthand
 * _.last(characters, { 'employer': 'na' });
 * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
 */
function last(array, callback, thisArg) {
  var n = 0,
      length = array ? array.length : 0;

  if (typeof callback != 'number' && callback != null) {
    var index = length;
    callback = createCallback(callback, thisArg, 3);
    while (index-- && callback(array[index], index, array)) {
      n++;
    }
  } else {
    n = callback;
    if (n == null || thisArg) {
      return array ? array[length - 1] : undefined;
    }
  }
  return slice(array, nativeMax(0, length - n));
}

module.exports = last;

},{"../functions/createCallback":76,"../internals/slice":129}],25:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max,
    nativeMin = Math.min;

/**
 * Gets the index at which the last occurrence of `value` is found using strict
 * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
 * as the offset from the end of the collection.
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to search.
 * @param {*} value The value to search for.
 * @param {number} [fromIndex=array.length-1] The index to search from.
 * @returns {number} Returns the index of the matched value or `-1`.
 * @example
 *
 * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
 * // => 4
 *
 * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
 * // => 1
 */
function lastIndexOf(array, value, fromIndex) {
  var index = array ? array.length : 0;
  if (typeof fromIndex == 'number') {
    index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
  }
  while (index--) {
    if (array[index] === value) {
      return index;
    }
  }
  return -1;
}

module.exports = lastIndexOf;

},{}],26:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Used for `Array` method references.
 *
 * Normally `Array.prototype` would suffice, however, using an array literal
 * avoids issues in Narwhal.
 */
var arrayRef = [];

/** Native method shortcuts */
var splice = arrayRef.splice;

/**
 * Removes all provided values from the given array using strict equality for
 * comparisons, i.e. `===`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to modify.
 * @param {...*} [value] The values to remove.
 * @returns {Array} Returns `array`.
 * @example
 *
 * var array = [1, 2, 3, 1, 2, 3];
 * _.pull(array, 2, 3);
 * console.log(array);
 * // => [1, 1]
 */
function pull(array) {
  var args = arguments,
      argsIndex = 0,
      argsLength = args.length,
      length = array ? array.length : 0;

  while (++argsIndex < argsLength) {
    var index = -1,
        value = args[argsIndex];
    while (++index < length) {
      if (array[index] === value) {
        splice.call(array, index--, 1);
        length--;
      }
    }
  }
  return array;
}

module.exports = pull;

},{}],27:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Native method shortcuts */
var ceil = Math.ceil;

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max;

/**
 * Creates an array of numbers (positive and/or negative) progressing from
 * `start` up to but not including `end`. If `start` is less than `stop` a
 * zero-length range is created unless a negative `step` is specified.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {number} [start=0] The start of the range.
 * @param {number} end The end of the range.
 * @param {number} [step=1] The value to increment or decrement by.
 * @returns {Array} Returns a new range array.
 * @example
 *
 * _.range(4);
 * // => [0, 1, 2, 3]
 *
 * _.range(1, 5);
 * // => [1, 2, 3, 4]
 *
 * _.range(0, 20, 5);
 * // => [0, 5, 10, 15]
 *
 * _.range(0, -4, -1);
 * // => [0, -1, -2, -3]
 *
 * _.range(1, 4, 0);
 * // => [1, 1, 1]
 *
 * _.range(0);
 * // => []
 */
function range(start, end, step) {
  start = +start || 0;
  step = typeof step == 'number' ? step : (+step || 1);

  if (end == null) {
    end = start;
    start = 0;
  }
  // use `Array(length)` so engines like Chakra and V8 avoid slower modes
  // http://youtu.be/XAqIpGU8ZZk#t=17m25s
  var index = -1,
      length = nativeMax(0, ceil((end - start) / (step || 1))),
      result = Array(length);

  while (++index < length) {
    result[index] = start;
    start += step;
  }
  return result;
}

module.exports = range;

},{}],28:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback');

/**
 * Used for `Array` method references.
 *
 * Normally `Array.prototype` would suffice, however, using an array literal
 * avoids issues in Narwhal.
 */
var arrayRef = [];

/** Native method shortcuts */
var splice = arrayRef.splice;

/**
 * Removes all elements from an array that the callback returns truey for
 * and returns an array of removed elements. The callback is bound to `thisArg`
 * and invoked with three arguments; (value, index, array).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to modify.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array} Returns a new array of removed elements.
 * @example
 *
 * var array = [1, 2, 3, 4, 5, 6];
 * var evens = _.remove(array, function(num) { return num % 2 == 0; });
 *
 * console.log(array);
 * // => [1, 3, 5]
 *
 * console.log(evens);
 * // => [2, 4, 6]
 */
function remove(array, callback, thisArg) {
  var index = -1,
      length = array ? array.length : 0,
      result = [];

  callback = createCallback(callback, thisArg, 3);
  while (++index < length) {
    var value = array[index];
    if (callback(value, index, array)) {
      result.push(value);
      splice.call(array, index--, 1);
      length--;
    }
  }
  return result;
}

module.exports = remove;

},{"../functions/createCallback":76}],29:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    slice = require('../internals/slice');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max;

/**
 * The opposite of `_.initial` this method gets all but the first element or
 * first `n` elements of an array. If a callback function is provided elements
 * at the beginning of the array are excluded from the result as long as the
 * callback returns truey. The callback is bound to `thisArg` and invoked
 * with three arguments; (value, index, array).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @alias drop, tail
 * @category Arrays
 * @param {Array} array The array to query.
 * @param {Function|Object|number|string} [callback=1] The function called
 *  per element or the number of elements to exclude. If a property name or
 *  object is provided it will be used to create a "_.pluck" or "_.where"
 *  style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array} Returns a slice of `array`.
 * @example
 *
 * _.rest([1, 2, 3]);
 * // => [2, 3]
 *
 * _.rest([1, 2, 3], 2);
 * // => [3]
 *
 * _.rest([1, 2, 3], function(num) {
 *   return num < 3;
 * });
 * // => [3]
 *
 * var characters = [
 *   { 'name': 'barney',  'blocked': true,  'employer': 'slate' },
 *   { 'name': 'fred',    'blocked': false,  'employer': 'slate' },
 *   { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
 * ];
 *
 * // using "_.pluck" callback shorthand
 * _.pluck(_.rest(characters, 'blocked'), 'name');
 * // => ['fred', 'pebbles']
 *
 * // using "_.where" callback shorthand
 * _.rest(characters, { 'employer': 'slate' });
 * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
 */
function rest(array, callback, thisArg) {
  if (typeof callback != 'number' && callback != null) {
    var n = 0,
        index = -1,
        length = array ? array.length : 0;

    callback = createCallback(callback, thisArg, 3);
    while (++index < length && callback(array[index], index, array)) {
      n++;
    }
  } else {
    n = (callback == null || thisArg) ? 1 : nativeMax(0, callback);
  }
  return slice(array, n);
}

module.exports = rest;

},{"../functions/createCallback":76,"../internals/slice":129}],30:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    identity = require('../utilities/identity');

/**
 * Uses a binary search to determine the smallest index at which a value
 * should be inserted into a given sorted array in order to maintain the sort
 * order of the array. If a callback is provided it will be executed for
 * `value` and each element of `array` to compute their sort ranking. The
 * callback is bound to `thisArg` and invoked with one argument; (value).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to inspect.
 * @param {*} value The value to evaluate.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {number} Returns the index at which `value` should be inserted
 *  into `array`.
 * @example
 *
 * _.sortedIndex([20, 30, 50], 40);
 * // => 2
 *
 * // using "_.pluck" callback shorthand
 * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
 * // => 2
 *
 * var dict = {
 *   'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
 * };
 *
 * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
 *   return dict.wordToNumber[word];
 * });
 * // => 2
 *
 * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
 *   return this.wordToNumber[word];
 * }, dict);
 * // => 2
 */
function sortedIndex(array, value, callback, thisArg) {
  var low = 0,
      high = array ? array.length : low;

  // explicitly reference `identity` for better inlining in Firefox
  callback = callback ? createCallback(callback, thisArg, 1) : identity;
  value = callback(value);

  while (low < high) {
    var mid = (low + high) >>> 1;
    (callback(array[mid]) < value)
      ? low = mid + 1
      : high = mid;
  }
  return low;
}

module.exports = sortedIndex;

},{"../functions/createCallback":76,"../utilities/identity":175}],31:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseFlatten = require('../internals/baseFlatten'),
    baseUniq = require('../internals/baseUniq');

/**
 * Creates an array of unique values, in order, of the provided arrays using
 * strict equality for comparisons, i.e. `===`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {...Array} [array] The arrays to inspect.
 * @returns {Array} Returns an array of combined values.
 * @example
 *
 * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]);
 * // => [1, 2, 3, 5, 4]
 */
function union() {
  return baseUniq(baseFlatten(arguments, true, true));
}

module.exports = union;

},{"../internals/baseFlatten":95,"../internals/baseUniq":100}],32:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseUniq = require('../internals/baseUniq'),
    createCallback = require('../functions/createCallback');

/**
 * Creates a duplicate-value-free version of an array using strict equality
 * for comparisons, i.e. `===`. If the array is sorted, providing
 * `true` for `isSorted` will use a faster algorithm. If a callback is provided
 * each element of `array` is passed through the callback before uniqueness
 * is computed. The callback is bound to `thisArg` and invoked with three
 * arguments; (value, index, array).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @alias unique
 * @category Arrays
 * @param {Array} array The array to process.
 * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array} Returns a duplicate-value-free array.
 * @example
 *
 * _.uniq([1, 2, 1, 3, 1]);
 * // => [1, 2, 3]
 *
 * _.uniq([1, 1, 2, 2, 3], true);
 * // => [1, 2, 3]
 *
 * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
 * // => ['A', 'b', 'C']
 *
 * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
 * // => [1, 2.5, 3]
 *
 * // using "_.pluck" callback shorthand
 * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
 * // => [{ 'x': 1 }, { 'x': 2 }]
 */
function uniq(array, isSorted, callback, thisArg) {
  // juggle arguments
  if (typeof isSorted != 'boolean' && isSorted != null) {
    thisArg = callback;
    callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted;
    isSorted = false;
  }
  if (callback != null) {
    callback = createCallback(callback, thisArg, 3);
  }
  return baseUniq(array, isSorted, callback);
}

module.exports = uniq;

},{"../functions/createCallback":76,"../internals/baseUniq":100}],33:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseDifference = require('../internals/baseDifference'),
    slice = require('../internals/slice');

/**
 * Creates an array excluding all provided values using strict equality for
 * comparisons, i.e. `===`.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {Array} array The array to filter.
 * @param {...*} [value] The values to exclude.
 * @returns {Array} Returns a new array of filtered values.
 * @example
 *
 * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
 * // => [2, 3, 4]
 */
function without(array) {
  return baseDifference(array, slice(arguments, 1));
}

module.exports = without;

},{"../internals/baseDifference":94,"../internals/slice":129}],34:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseDifference = require('../internals/baseDifference'),
    baseUniq = require('../internals/baseUniq'),
    isArguments = require('../objects/isArguments'),
    isArray = require('../objects/isArray');

/**
 * Creates an array that is the symmetric difference of the provided arrays.
 * See http://en.wikipedia.org/wiki/Symmetric_difference.
 *
 * @static
 * @memberOf _
 * @category Arrays
 * @param {...Array} [array] The arrays to inspect.
 * @returns {Array} Returns an array of values.
 * @example
 *
 * _.xor([1, 2, 3], [5, 2, 1, 4]);
 * // => [3, 5, 4]
 *
 * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]);
 * // => [1, 4, 5]
 */
function xor() {
  var index = -1,
      length = arguments.length;

  while (++index < length) {
    var array = arguments[index];
    if (isArray(array) || isArguments(array)) {
      var result = result
        ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result)))
        : array;
    }
  }
  return result || [];
}

module.exports = xor;

},{"../internals/baseDifference":94,"../internals/baseUniq":100,"../objects/isArguments":146,"../objects/isArray":147}],35:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var max = require('../collections/max'),
    pluck = require('../collections/pluck');

/**
 * Creates an array of grouped elements, the first of which contains the first
 * elements of the given arrays, the second of which contains the second
 * elements of the given arrays, and so on.
 *
 * @static
 * @memberOf _
 * @alias unzip
 * @category Arrays
 * @param {...Array} [array] Arrays to process.
 * @returns {Array} Returns a new array of grouped elements.
 * @example
 *
 * _.zip(['fred', 'barney'], [30, 40], [true, false]);
 * // => [['fred', 30, true], ['barney', 40, false]]
 */
function zip() {
  var array = arguments.length > 1 ? arguments : arguments[0],
      index = -1,
      length = array ? max(pluck(array, 'length')) : 0,
      result = Array(length < 0 ? 0 : length);

  while (++index < length) {
    result[index] = pluck(array, index);
  }
  return result;
}

module.exports = zip;

},{"../collections/max":57,"../collections/pluck":59}],36:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isArray = require('../objects/isArray');

/**
 * Creates an object composed from arrays of `keys` and `values`. Provide
 * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`
 * or two arrays, one of `keys` and one of corresponding `values`.
 *
 * @static
 * @memberOf _
 * @alias object
 * @category Arrays
 * @param {Array} keys The array of keys.
 * @param {Array} [values=[]] The array of values.
 * @returns {Object} Returns an object composed of the given keys and
 *  corresponding values.
 * @example
 *
 * _.zipObject(['fred', 'barney'], [30, 40]);
 * // => { 'fred': 30, 'barney': 40 }
 */
function zipObject(keys, values) {
  var index = -1,
      length = keys ? keys.length : 0,
      result = {};

  if (!values && length && !isArray(keys[0])) {
    values = [];
  }
  while (++index < length) {
    var key = keys[index];
    if (values) {
      result[key] = values[index];
    } else if (key) {
      result[key[0]] = key[1];
    }
  }
  return result;
}

module.exports = zipObject;

},{"../objects/isArray":147}],37:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

module.exports = {
  'chain': require('./chaining/chain'),
  'tap': require('./chaining/tap'),
  'value': require('./chaining/wrapperValueOf'),
  'wrapperChain': require('./chaining/wrapperChain'),
  'wrapperToString': require('./chaining/wrapperToString'),
  'wrapperValueOf': require('./chaining/wrapperValueOf')
};

},{"./chaining/chain":38,"./chaining/tap":39,"./chaining/wrapperChain":40,"./chaining/wrapperToString":41,"./chaining/wrapperValueOf":42}],38:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var lodashWrapper = require('../internals/lodashWrapper');

/**
 * Creates a `lodash` object that wraps the given value with explicit
 * method chaining enabled.
 *
 * @static
 * @memberOf _
 * @category Chaining
 * @param {*} value The value to wrap.
 * @returns {Object} Returns the wrapper object.
 * @example
 *
 * var characters = [
 *   { 'name': 'barney',  'age': 36 },
 *   { 'name': 'fred',    'age': 40 },
 *   { 'name': 'pebbles', 'age': 1 }
 * ];
 *
 * var youngest = _.chain(characters)
 *     .sortBy('age')
 *     .map(function(chr) { return chr.name + ' is ' + chr.age; })
 *     .first()
 *     .value();
 * // => 'pebbles is 1'
 */
function chain(value) {
  value = new lodashWrapper(value);
  value.__chain__ = true;
  return value;
}

module.exports = chain;

},{"../internals/lodashWrapper":117}],39:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Invokes `interceptor` with the `value` as the first argument and then
 * returns `value`. The purpose of this method is to "tap into" a method
 * chain in order to perform operations on intermediate results within
 * the chain.
 *
 * @static
 * @memberOf _
 * @category Chaining
 * @param {*} value The value to provide to `interceptor`.
 * @param {Function} interceptor The function to invoke.
 * @returns {*} Returns `value`.
 * @example
 *
 * _([1, 2, 3, 4])
 *  .tap(function(array) { array.pop(); })
 *  .reverse()
 *  .value();
 * // => [3, 2, 1]
 */
function tap(value, interceptor) {
  interceptor(value);
  return value;
}

module.exports = tap;

},{}],40:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Enables explicit method chaining on the wrapper object.
 *
 * @name chain
 * @memberOf _
 * @category Chaining
 * @returns {*} Returns the wrapper object.
 * @example
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36 },
 *   { 'name': 'fred',   'age': 40 }
 * ];
 *
 * // without explicit chaining
 * _(characters).first();
 * // => { 'name': 'barney', 'age': 36 }
 *
 * // with explicit chaining
 * _(characters).chain()
 *   .first()
 *   .pick('age')
 *   .value();
 * // => { 'age': 36 }
 */
function wrapperChain() {
  this.__chain__ = true;
  return this;
}

module.exports = wrapperChain;

},{}],41:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Produces the `toString` result of the wrapped value.
 *
 * @name toString
 * @memberOf _
 * @category Chaining
 * @returns {string} Returns the string result.
 * @example
 *
 * _([1, 2, 3]).toString();
 * // => '1,2,3'
 */
function wrapperToString() {
  return String(this.__wrapped__);
}

module.exports = wrapperToString;

},{}],42:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var forEach = require('../collections/forEach'),
    support = require('../support');

/**
 * Extracts the wrapped value.
 *
 * @name valueOf
 * @memberOf _
 * @alias value
 * @category Chaining
 * @returns {*} Returns the wrapped value.
 * @example
 *
 * _([1, 2, 3]).valueOf();
 * // => [1, 2, 3]
 */
function wrapperValueOf() {
  return this.__wrapped__;
}

module.exports = wrapperValueOf;

},{"../collections/forEach":51,"../support":171}],43:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

module.exports = {
  'all': require('./collections/every'),
  'any': require('./collections/some'),
  'at': require('./collections/at'),
  'collect': require('./collections/map'),
  'contains': require('./collections/contains'),
  'countBy': require('./collections/countBy'),
  'detect': require('./collections/find'),
  'each': require('./collections/forEach'),
  'eachRight': require('./collections/forEachRight'),
  'every': require('./collections/every'),
  'filter': require('./collections/filter'),
  'find': require('./collections/find'),
  'findLast': require('./collections/findLast'),
  'findWhere': require('./collections/find'),
  'foldl': require('./collections/reduce'),
  'foldr': require('./collections/reduceRight'),
  'forEach': require('./collections/forEach'),
  'forEachRight': require('./collections/forEachRight'),
  'groupBy': require('./collections/groupBy'),
  'include': require('./collections/contains'),
  'indexBy': require('./collections/indexBy'),
  'inject': require('./collections/reduce'),
  'invoke': require('./collections/invoke'),
  'map': require('./collections/map'),
  'max': require('./collections/max'),
  'min': require('./collections/min'),
  'pluck': require('./collections/pluck'),
  'reduce': require('./collections/reduce'),
  'reduceRight': require('./collections/reduceRight'),
  'reject': require('./collections/reject'),
  'sample': require('./collections/sample'),
  'select': require('./collections/filter'),
  'shuffle': require('./collections/shuffle'),
  'size': require('./collections/size'),
  'some': require('./collections/some'),
  'sortBy': require('./collections/sortBy'),
  'toArray': require('./collections/toArray'),
  'where': require('./collections/where')
};

},{"./collections/at":44,"./collections/contains":45,"./collections/countBy":46,"./collections/every":47,"./collections/filter":48,"./collections/find":49,"./collections/findLast":50,"./collections/forEach":51,"./collections/forEachRight":52,"./collections/groupBy":53,"./collections/indexBy":54,"./collections/invoke":55,"./collections/map":56,"./collections/max":57,"./collections/min":58,"./collections/pluck":59,"./collections/reduce":60,"./collections/reduceRight":61,"./collections/reject":62,"./collections/sample":63,"./collections/shuffle":64,"./collections/size":65,"./collections/some":66,"./collections/sortBy":67,"./collections/toArray":68,"./collections/where":69}],44:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseFlatten = require('../internals/baseFlatten'),
    isString = require('../objects/isString');

/**
 * Creates an array of elements from the specified indexes, or keys, of the
 * `collection`. Indexes may be specified as individual arguments or as arrays
 * of indexes.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {...(number|number[]|string|string[])} [index] The indexes of `collection`
 *   to retrieve, specified as individual indexes or arrays of indexes.
 * @returns {Array} Returns a new array of elements corresponding to the
 *  provided indexes.
 * @example
 *
 * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
 * // => ['a', 'c', 'e']
 *
 * _.at(['fred', 'barney', 'pebbles'], 0, 2);
 * // => ['fred', 'pebbles']
 */
function at(collection) {
  var args = arguments,
      index = -1,
      props = baseFlatten(args, true, false, 1),
      length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length,
      result = Array(length);

  while(++index < length) {
    result[index] = collection[props[index]];
  }
  return result;
}

module.exports = at;

},{"../internals/baseFlatten":95,"../objects/isString":161}],45:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseIndexOf = require('../internals/baseIndexOf'),
    forOwn = require('../objects/forOwn'),
    isArray = require('../objects/isArray'),
    isString = require('../objects/isString');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max;

/**
 * Checks if a given value is present in a collection using strict equality
 * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the
 * offset from the end of the collection.
 *
 * @static
 * @memberOf _
 * @alias include
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {*} target The value to check for.
 * @param {number} [fromIndex=0] The index to search from.
 * @returns {boolean} Returns `true` if the `target` element is found, else `false`.
 * @example
 *
 * _.contains([1, 2, 3], 1);
 * // => true
 *
 * _.contains([1, 2, 3], 1, 2);
 * // => false
 *
 * _.contains({ 'name': 'fred', 'age': 40 }, 'fred');
 * // => true
 *
 * _.contains('pebbles', 'eb');
 * // => true
 */
function contains(collection, target, fromIndex) {
  var index = -1,
      indexOf = baseIndexOf,
      length = collection ? collection.length : 0,
      result = false;

  fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
  if (isArray(collection)) {
    result = indexOf(collection, target, fromIndex) > -1;
  } else if (typeof length == 'number') {
    result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1;
  } else {
    forOwn(collection, function(value) {
      if (++index >= fromIndex) {
        return !(result = value === target);
      }
    });
  }
  return result;
}

module.exports = contains;

},{"../internals/baseIndexOf":96,"../objects/forOwn":141,"../objects/isArray":147,"../objects/isString":161}],46:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createAggregator = require('../internals/createAggregator');

/** Used for native method references */
var objectProto = Object.prototype;

/** Native method shortcuts */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Creates an object composed of keys generated from the results of running
 * each element of `collection` through the callback. The corresponding value
 * of each key is the number of times the key was returned by the callback.
 * The callback is bound to `thisArg` and invoked with three arguments;
 * (value, index|key, collection).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Object} Returns the composed aggregate object.
 * @example
 *
 * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
 * // => { '4': 1, '6': 2 }
 *
 * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
 * // => { '4': 1, '6': 2 }
 *
 * _.countBy(['one', 'two', 'three'], 'length');
 * // => { '3': 2, '5': 1 }
 */
var countBy = createAggregator(function(result, value, key) {
  (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
});

module.exports = countBy;

},{"../internals/createAggregator":105}],47:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forOwn = require('../objects/forOwn');

/**
 * Checks if the given callback returns truey value for **all** elements of
 * a collection. The callback is bound to `thisArg` and invoked with three
 * arguments; (value, index|key, collection).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @alias all
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {boolean} Returns `true` if all elements passed the callback check,
 *  else `false`.
 * @example
 *
 * _.every([true, 1, null, 'yes']);
 * // => false
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36 },
 *   { 'name': 'fred',   'age': 40 }
 * ];
 *
 * // using "_.pluck" callback shorthand
 * _.every(characters, 'age');
 * // => true
 *
 * // using "_.where" callback shorthand
 * _.every(characters, { 'age': 36 });
 * // => false
 */
function every(collection, callback, thisArg) {
  var result = true;
  callback = createCallback(callback, thisArg, 3);

  var index = -1,
      length = collection ? collection.length : 0;

  if (typeof length == 'number') {
    while (++index < length) {
      if (!(result = !!callback(collection[index], index, collection))) {
        break;
      }
    }
  } else {
    forOwn(collection, function(value, index, collection) {
      return (result = !!callback(value, index, collection));
    });
  }
  return result;
}

module.exports = every;

},{"../functions/createCallback":76,"../objects/forOwn":141}],48:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forOwn = require('../objects/forOwn');

/**
 * Iterates over elements of a collection, returning an array of all elements
 * the callback returns truey for. The callback is bound to `thisArg` and
 * invoked with three arguments; (value, index|key, collection).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @alias select
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array} Returns a new array of elements that passed the callback check.
 * @example
 *
 * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
 * // => [2, 4, 6]
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36, 'blocked': false },
 *   { 'name': 'fred',   'age': 40, 'blocked': true }
 * ];
 *
 * // using "_.pluck" callback shorthand
 * _.filter(characters, 'blocked');
 * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
 *
 * // using "_.where" callback shorthand
 * _.filter(characters, { 'age': 36 });
 * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
 */
function filter(collection, callback, thisArg) {
  var result = [];
  callback = createCallback(callback, thisArg, 3);

  var index = -1,
      length = collection ? collection.length : 0;

  if (typeof length == 'number') {
    while (++index < length) {
      var value = collection[index];
      if (callback(value, index, collection)) {
        result.push(value);
      }
    }
  } else {
    forOwn(collection, function(value, index, collection) {
      if (callback(value, index, collection)) {
        result.push(value);
      }
    });
  }
  return result;
}

module.exports = filter;

},{"../functions/createCallback":76,"../objects/forOwn":141}],49:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forOwn = require('../objects/forOwn');

/**
 * Iterates over elements of a collection, returning the first element that
 * the callback returns truey for. The callback is bound to `thisArg` and
 * invoked with three arguments; (value, index|key, collection).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @alias detect, findWhere
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {*} Returns the found element, else `undefined`.
 * @example
 *
 * var characters = [
 *   { 'name': 'barney',  'age': 36, 'blocked': false },
 *   { 'name': 'fred',    'age': 40, 'blocked': true },
 *   { 'name': 'pebbles', 'age': 1,  'blocked': false }
 * ];
 *
 * _.find(characters, function(chr) {
 *   return chr.age < 40;
 * });
 * // => { 'name': 'barney', 'age': 36, 'blocked': false }
 *
 * // using "_.where" callback shorthand
 * _.find(characters, { 'age': 1 });
 * // =>  { 'name': 'pebbles', 'age': 1, 'blocked': false }
 *
 * // using "_.pluck" callback shorthand
 * _.find(characters, 'blocked');
 * // => { 'name': 'fred', 'age': 40, 'blocked': true }
 */
function find(collection, callback, thisArg) {
  callback = createCallback(callback, thisArg, 3);

  var index = -1,
      length = collection ? collection.length : 0;

  if (typeof length == 'number') {
    while (++index < length) {
      var value = collection[index];
      if (callback(value, index, collection)) {
        return value;
      }
    }
  } else {
    var result;
    forOwn(collection, function(value, index, collection) {
      if (callback(value, index, collection)) {
        result = value;
        return false;
      }
    });
    return result;
  }
}

module.exports = find;

},{"../functions/createCallback":76,"../objects/forOwn":141}],50:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forEachRight = require('./forEachRight');

/**
 * This method is like `_.find` except that it iterates over elements
 * of a `collection` from right to left.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {*} Returns the found element, else `undefined`.
 * @example
 *
 * _.findLast([1, 2, 3, 4], function(num) {
 *   return num % 2 == 1;
 * });
 * // => 3
 */
function findLast(collection, callback, thisArg) {
  var result;
  callback = createCallback(callback, thisArg, 3);
  forEachRight(collection, function(value, index, collection) {
    if (callback(value, index, collection)) {
      result = value;
      return false;
    }
  });
  return result;
}

module.exports = findLast;

},{"../functions/createCallback":76,"./forEachRight":52}],51:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreateCallback = require('../internals/baseCreateCallback'),
    forOwn = require('../objects/forOwn');

/**
 * Iterates over elements of a collection, executing the callback for each
 * element. The callback is bound to `thisArg` and invoked with three arguments;
 * (value, index|key, collection). Callbacks may exit iteration early by
 * explicitly returning `false`.
 *
 * Note: As with other "Collections" methods, objects with a `length` property
 * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
 * may be used for object iteration.
 *
 * @static
 * @memberOf _
 * @alias each
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function} [callback=identity] The function called per iteration.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array|Object|string} Returns `collection`.
 * @example
 *
 * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
 * // => logs each number and returns '1,2,3'
 *
 * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
 * // => logs each number and returns the object (property order is not guaranteed across environments)
 */
function forEach(collection, callback, thisArg) {
  var index = -1,
      length = collection ? collection.length : 0;

  callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
  if (typeof length == 'number') {
    while (++index < length) {
      if (callback(collection[index], index, collection) === false) {
        break;
      }
    }
  } else {
    forOwn(collection, callback);
  }
  return collection;
}

module.exports = forEach;

},{"../internals/baseCreateCallback":92,"../objects/forOwn":141}],52:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreateCallback = require('../internals/baseCreateCallback'),
    forOwn = require('../objects/forOwn'),
    isArray = require('../objects/isArray'),
    isString = require('../objects/isString'),
    keys = require('../objects/keys');

/**
 * This method is like `_.forEach` except that it iterates over elements
 * of a `collection` from right to left.
 *
 * @static
 * @memberOf _
 * @alias eachRight
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function} [callback=identity] The function called per iteration.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array|Object|string} Returns `collection`.
 * @example
 *
 * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');
 * // => logs each number from right to left and returns '3,2,1'
 */
function forEachRight(collection, callback, thisArg) {
  var length = collection ? collection.length : 0;
  callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
  if (typeof length == 'number') {
    while (length--) {
      if (callback(collection[length], length, collection) === false) {
        break;
      }
    }
  } else {
    var props = keys(collection);
    length = props.length;
    forOwn(collection, function(value, key, collection) {
      key = props ? props[--length] : --length;
      return callback(collection[key], key, collection);
    });
  }
  return collection;
}

module.exports = forEachRight;

},{"../internals/baseCreateCallback":92,"../objects/forOwn":141,"../objects/isArray":147,"../objects/isString":161,"../objects/keys":163}],53:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createAggregator = require('../internals/createAggregator');

/** Used for native method references */
var objectProto = Object.prototype;

/** Native method shortcuts */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Creates an object composed of keys generated from the results of running
 * each element of a collection through the callback. The corresponding value
 * of each key is an array of the elements responsible for generating the key.
 * The callback is bound to `thisArg` and invoked with three arguments;
 * (value, index|key, collection).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Object} Returns the composed aggregate object.
 * @example
 *
 * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
 * // => { '4': [4.2], '6': [6.1, 6.4] }
 *
 * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
 * // => { '4': [4.2], '6': [6.1, 6.4] }
 *
 * // using "_.pluck" callback shorthand
 * _.groupBy(['one', 'two', 'three'], 'length');
 * // => { '3': ['one', 'two'], '5': ['three'] }
 */
var groupBy = createAggregator(function(result, value, key) {
  (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
});

module.exports = groupBy;

},{"../internals/createAggregator":105}],54:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createAggregator = require('../internals/createAggregator');

/**
 * Creates an object composed of keys generated from the results of running
 * each element of the collection through the given callback. The corresponding
 * value of each key is the last element responsible for generating the key.
 * The callback is bound to `thisArg` and invoked with three arguments;
 * (value, index|key, collection).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Object} Returns the composed aggregate object.
 * @example
 *
 * var keys = [
 *   { 'dir': 'left', 'code': 97 },
 *   { 'dir': 'right', 'code': 100 }
 * ];
 *
 * _.indexBy(keys, 'dir');
 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
 *
 * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
 *
 * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String);
 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
 */
var indexBy = createAggregator(function(result, value, key) {
  result[key] = value;
});

module.exports = indexBy;

},{"../internals/createAggregator":105}],55:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var forEach = require('./forEach'),
    slice = require('../internals/slice');

/**
 * Invokes the method named by `methodName` on each element in the `collection`
 * returning an array of the results of each invoked method. Additional arguments
 * will be provided to each invoked method. If `methodName` is a function it
 * will be invoked for, and `this` bound to, each element in the `collection`.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|string} methodName The name of the method to invoke or
 *  the function invoked per iteration.
 * @param {...*} [arg] Arguments to invoke the method with.
 * @returns {Array} Returns a new array of the results of each invoked method.
 * @example
 *
 * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
 * // => [[1, 5, 7], [1, 2, 3]]
 *
 * _.invoke([123, 456], String.prototype.split, '');
 * // => [['1', '2', '3'], ['4', '5', '6']]
 */
function invoke(collection, methodName) {
  var args = slice(arguments, 2),
      index = -1,
      isFunc = typeof methodName == 'function',
      length = collection ? collection.length : 0,
      result = Array(typeof length == 'number' ? length : 0);

  forEach(collection, function(value) {
    result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
  });
  return result;
}

module.exports = invoke;

},{"../internals/slice":129,"./forEach":51}],56:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forOwn = require('../objects/forOwn');

/**
 * Creates an array of values by running each element in the collection
 * through the callback. The callback is bound to `thisArg` and invoked with
 * three arguments; (value, index|key, collection).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @alias collect
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array} Returns a new array of the results of each `callback` execution.
 * @example
 *
 * _.map([1, 2, 3], function(num) { return num * 3; });
 * // => [3, 6, 9]
 *
 * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
 * // => [3, 6, 9] (property order is not guaranteed across environments)
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36 },
 *   { 'name': 'fred',   'age': 40 }
 * ];
 *
 * // using "_.pluck" callback shorthand
 * _.map(characters, 'name');
 * // => ['barney', 'fred']
 */
function map(collection, callback, thisArg) {
  var index = -1,
      length = collection ? collection.length : 0;

  callback = createCallback(callback, thisArg, 3);
  if (typeof length == 'number') {
    var result = Array(length);
    while (++index < length) {
      result[index] = callback(collection[index], index, collection);
    }
  } else {
    result = [];
    forOwn(collection, function(value, key, collection) {
      result[++index] = callback(value, key, collection);
    });
  }
  return result;
}

module.exports = map;

},{"../functions/createCallback":76,"../objects/forOwn":141}],57:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var charAtCallback = require('../internals/charAtCallback'),
    createCallback = require('../functions/createCallback'),
    forEach = require('./forEach'),
    forOwn = require('../objects/forOwn'),
    isArray = require('../objects/isArray'),
    isString = require('../objects/isString');

/**
 * Retrieves the maximum value of a collection. If the collection is empty or
 * falsey `-Infinity` is returned. If a callback is provided it will be executed
 * for each value in the collection to generate the criterion by which the value
 * is ranked. The callback is bound to `thisArg` and invoked with three
 * arguments; (value, index, collection).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {*} Returns the maximum value.
 * @example
 *
 * _.max([4, 2, 8, 6]);
 * // => 8
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36 },
 *   { 'name': 'fred',   'age': 40 }
 * ];
 *
 * _.max(characters, function(chr) { return chr.age; });
 * // => { 'name': 'fred', 'age': 40 };
 *
 * // using "_.pluck" callback shorthand
 * _.max(characters, 'age');
 * // => { 'name': 'fred', 'age': 40 };
 */
function max(collection, callback, thisArg) {
  var computed = -Infinity,
      result = computed;

  // allows working with functions like `_.map` without using
  // their `index` argument as a callback
  if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
    callback = null;
  }
  if (callback == null && isArray(collection)) {
    var index = -1,
        length = collection.length;

    while (++index < length) {
      var value = collection[index];
      if (value > result) {
        result = value;
      }
    }
  } else {
    callback = (callback == null && isString(collection))
      ? charAtCallback
      : createCallback(callback, thisArg, 3);

    forEach(collection, function(value, index, collection) {
      var current = callback(value, index, collection);
      if (current > computed) {
        computed = current;
        result = value;
      }
    });
  }
  return result;
}

module.exports = max;

},{"../functions/createCallback":76,"../internals/charAtCallback":103,"../objects/forOwn":141,"../objects/isArray":147,"../objects/isString":161,"./forEach":51}],58:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var charAtCallback = require('../internals/charAtCallback'),
    createCallback = require('../functions/createCallback'),
    forEach = require('./forEach'),
    forOwn = require('../objects/forOwn'),
    isArray = require('../objects/isArray'),
    isString = require('../objects/isString');

/**
 * Retrieves the minimum value of a collection. If the collection is empty or
 * falsey `Infinity` is returned. If a callback is provided it will be executed
 * for each value in the collection to generate the criterion by which the value
 * is ranked. The callback is bound to `thisArg` and invoked with three
 * arguments; (value, index, collection).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {*} Returns the minimum value.
 * @example
 *
 * _.min([4, 2, 8, 6]);
 * // => 2
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36 },
 *   { 'name': 'fred',   'age': 40 }
 * ];
 *
 * _.min(characters, function(chr) { return chr.age; });
 * // => { 'name': 'barney', 'age': 36 };
 *
 * // using "_.pluck" callback shorthand
 * _.min(characters, 'age');
 * // => { 'name': 'barney', 'age': 36 };
 */
function min(collection, callback, thisArg) {
  var computed = Infinity,
      result = computed;

  // allows working with functions like `_.map` without using
  // their `index` argument as a callback
  if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
    callback = null;
  }
  if (callback == null && isArray(collection)) {
    var index = -1,
        length = collection.length;

    while (++index < length) {
      var value = collection[index];
      if (value < result) {
        result = value;
      }
    }
  } else {
    callback = (callback == null && isString(collection))
      ? charAtCallback
      : createCallback(callback, thisArg, 3);

    forEach(collection, function(value, index, collection) {
      var current = callback(value, index, collection);
      if (current < computed) {
        computed = current;
        result = value;
      }
    });
  }
  return result;
}

module.exports = min;

},{"../functions/createCallback":76,"../internals/charAtCallback":103,"../objects/forOwn":141,"../objects/isArray":147,"../objects/isString":161,"./forEach":51}],59:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var map = require('./map');

/**
 * Retrieves the value of a specified property from all elements in the collection.
 *
 * @static
 * @memberOf _
 * @type Function
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {string} property The name of the property to pluck.
 * @returns {Array} Returns a new array of property values.
 * @example
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36 },
 *   { 'name': 'fred',   'age': 40 }
 * ];
 *
 * _.pluck(characters, 'name');
 * // => ['barney', 'fred']
 */
var pluck = map;

module.exports = pluck;

},{"./map":56}],60:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forOwn = require('../objects/forOwn');

/**
 * Reduces a collection to a value which is the accumulated result of running
 * each element in the collection through the callback, where each successive
 * callback execution consumes the return value of the previous execution. If
 * `accumulator` is not provided the first element of the collection will be
 * used as the initial `accumulator` value. The callback is bound to `thisArg`
 * and invoked with four arguments; (accumulator, value, index|key, collection).
 *
 * @static
 * @memberOf _
 * @alias foldl, inject
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function} [callback=identity] The function called per iteration.
 * @param {*} [accumulator] Initial value of the accumulator.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {*} Returns the accumulated value.
 * @example
 *
 * var sum = _.reduce([1, 2, 3], function(sum, num) {
 *   return sum + num;
 * });
 * // => 6
 *
 * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
 *   result[key] = num * 3;
 *   return result;
 * }, {});
 * // => { 'a': 3, 'b': 6, 'c': 9 }
 */
function reduce(collection, callback, accumulator, thisArg) {
  if (!collection) return accumulator;
  var noaccum = arguments.length < 3;
  callback = createCallback(callback, thisArg, 4);

  var index = -1,
      length = collection.length;

  if (typeof length == 'number') {
    if (noaccum) {
      accumulator = collection[++index];
    }
    while (++index < length) {
      accumulator = callback(accumulator, collection[index], index, collection);
    }
  } else {
    forOwn(collection, function(value, index, collection) {
      accumulator = noaccum
        ? (noaccum = false, value)
        : callback(accumulator, value, index, collection)
    });
  }
  return accumulator;
}

module.exports = reduce;

},{"../functions/createCallback":76,"../objects/forOwn":141}],61:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forEachRight = require('./forEachRight');

/**
 * This method is like `_.reduce` except that it iterates over elements
 * of a `collection` from right to left.
 *
 * @static
 * @memberOf _
 * @alias foldr
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function} [callback=identity] The function called per iteration.
 * @param {*} [accumulator] Initial value of the accumulator.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {*} Returns the accumulated value.
 * @example
 *
 * var list = [[0, 1], [2, 3], [4, 5]];
 * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
 * // => [4, 5, 2, 3, 0, 1]
 */
function reduceRight(collection, callback, accumulator, thisArg) {
  var noaccum = arguments.length < 3;
  callback = createCallback(callback, thisArg, 4);
  forEachRight(collection, function(value, index, collection) {
    accumulator = noaccum
      ? (noaccum = false, value)
      : callback(accumulator, value, index, collection);
  });
  return accumulator;
}

module.exports = reduceRight;

},{"../functions/createCallback":76,"./forEachRight":52}],62:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    filter = require('./filter');

/**
 * The opposite of `_.filter` this method returns the elements of a
 * collection that the callback does **not** return truey for.
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array} Returns a new array of elements that failed the callback check.
 * @example
 *
 * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
 * // => [1, 3, 5]
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36, 'blocked': false },
 *   { 'name': 'fred',   'age': 40, 'blocked': true }
 * ];
 *
 * // using "_.pluck" callback shorthand
 * _.reject(characters, 'blocked');
 * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
 *
 * // using "_.where" callback shorthand
 * _.reject(characters, { 'age': 36 });
 * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
 */
function reject(collection, callback, thisArg) {
  callback = createCallback(callback, thisArg, 3);
  return filter(collection, function(value, index, collection) {
    return !callback(value, index, collection);
  });
}

module.exports = reject;

},{"../functions/createCallback":76,"./filter":48}],63:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseRandom = require('../internals/baseRandom'),
    isString = require('../objects/isString'),
    shuffle = require('./shuffle'),
    values = require('../objects/values');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max,
    nativeMin = Math.min;

/**
 * Retrieves a random element or `n` random elements from a collection.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to sample.
 * @param {number} [n] The number of elements to sample.
 * @param- {Object} [guard] Allows working with functions like `_.map`
 *  without using their `index` arguments as `n`.
 * @returns {Array} Returns the random sample(s) of `collection`.
 * @example
 *
 * _.sample([1, 2, 3, 4]);
 * // => 2
 *
 * _.sample([1, 2, 3, 4], 2);
 * // => [3, 1]
 */
function sample(collection, n, guard) {
  if (collection && typeof collection.length != 'number') {
    collection = values(collection);
  }
  if (n == null || guard) {
    return collection ? collection[baseRandom(0, collection.length - 1)] : undefined;
  }
  var result = shuffle(collection);
  result.length = nativeMin(nativeMax(0, n), result.length);
  return result;
}

module.exports = sample;

},{"../internals/baseRandom":99,"../objects/isString":161,"../objects/values":170,"./shuffle":64}],64:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseRandom = require('../internals/baseRandom'),
    forEach = require('./forEach');

/**
 * Creates an array of shuffled values, using a version of the Fisher-Yates
 * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to shuffle.
 * @returns {Array} Returns a new shuffled collection.
 * @example
 *
 * _.shuffle([1, 2, 3, 4, 5, 6]);
 * // => [4, 1, 6, 3, 5, 2]
 */
function shuffle(collection) {
  var index = -1,
      length = collection ? collection.length : 0,
      result = Array(typeof length == 'number' ? length : 0);

  forEach(collection, function(value) {
    var rand = baseRandom(0, ++index);
    result[index] = result[rand];
    result[rand] = value;
  });
  return result;
}

module.exports = shuffle;

},{"../internals/baseRandom":99,"./forEach":51}],65:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var keys = require('../objects/keys');

/**
 * Gets the size of the `collection` by returning `collection.length` for arrays
 * and array-like objects or the number of own enumerable properties for objects.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to inspect.
 * @returns {number} Returns `collection.length` or number of own enumerable properties.
 * @example
 *
 * _.size([1, 2]);
 * // => 2
 *
 * _.size({ 'one': 1, 'two': 2, 'three': 3 });
 * // => 3
 *
 * _.size('pebbles');
 * // => 7
 */
function size(collection) {
  var length = collection ? collection.length : 0;
  return typeof length == 'number' ? length : keys(collection).length;
}

module.exports = size;

},{"../objects/keys":163}],66:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forOwn = require('../objects/forOwn'),
    isArray = require('../objects/isArray');

/**
 * Checks if the callback returns a truey value for **any** element of a
 * collection. The function returns as soon as it finds a passing value and
 * does not iterate over the entire collection. The callback is bound to
 * `thisArg` and invoked with three arguments; (value, index|key, collection).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @alias any
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {boolean} Returns `true` if any element passed the callback check,
 *  else `false`.
 * @example
 *
 * _.some([null, 0, 'yes', false], Boolean);
 * // => true
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36, 'blocked': false },
 *   { 'name': 'fred',   'age': 40, 'blocked': true }
 * ];
 *
 * // using "_.pluck" callback shorthand
 * _.some(characters, 'blocked');
 * // => true
 *
 * // using "_.where" callback shorthand
 * _.some(characters, { 'age': 1 });
 * // => false
 */
function some(collection, callback, thisArg) {
  var result;
  callback = createCallback(callback, thisArg, 3);

  var index = -1,
      length = collection ? collection.length : 0;

  if (typeof length == 'number') {
    while (++index < length) {
      if ((result = callback(collection[index], index, collection))) {
        break;
      }
    }
  } else {
    forOwn(collection, function(value, index, collection) {
      return !(result = callback(value, index, collection));
    });
  }
  return !!result;
}

module.exports = some;

},{"../functions/createCallback":76,"../objects/forOwn":141,"../objects/isArray":147}],67:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var compareAscending = require('../internals/compareAscending'),
    createCallback = require('../functions/createCallback'),
    forEach = require('./forEach'),
    getArray = require('../internals/getArray'),
    getObject = require('../internals/getObject'),
    isArray = require('../objects/isArray'),
    map = require('./map'),
    releaseArray = require('../internals/releaseArray'),
    releaseObject = require('../internals/releaseObject');

/**
 * Creates an array of elements, sorted in ascending order by the results of
 * running each element in a collection through the callback. This method
 * performs a stable sort, that is, it will preserve the original sort order
 * of equal elements. The callback is bound to `thisArg` and invoked with
 * three arguments; (value, index|key, collection).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an array of property names is provided for `callback` the collection
 * will be sorted by each property value.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Array|Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array} Returns a new array of sorted elements.
 * @example
 *
 * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
 * // => [3, 1, 2]
 *
 * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
 * // => [3, 1, 2]
 *
 * var characters = [
 *   { 'name': 'barney',  'age': 36 },
 *   { 'name': 'fred',    'age': 40 },
 *   { 'name': 'barney',  'age': 26 },
 *   { 'name': 'fred',    'age': 30 }
 * ];
 *
 * // using "_.pluck" callback shorthand
 * _.map(_.sortBy(characters, 'age'), _.values);
 * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]]
 *
 * // sorting by multiple properties
 * _.map(_.sortBy(characters, ['name', 'age']), _.values);
 * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]
 */
function sortBy(collection, callback, thisArg) {
  var index = -1,
      isArr = isArray(callback),
      length = collection ? collection.length : 0,
      result = Array(typeof length == 'number' ? length : 0);

  if (!isArr) {
    callback = createCallback(callback, thisArg, 3);
  }
  forEach(collection, function(value, key, collection) {
    var object = result[++index] = getObject();
    if (isArr) {
      object.criteria = map(callback, function(key) { return value[key]; });
    } else {
      (object.criteria = getArray())[0] = callback(value, key, collection);
    }
    object.index = index;
    object.value = value;
  });

  length = result.length;
  result.sort(compareAscending);
  while (length--) {
    var object = result[length];
    result[length] = object.value;
    if (!isArr) {
      releaseArray(object.criteria);
    }
    releaseObject(object);
  }
  return result;
}

module.exports = sortBy;

},{"../functions/createCallback":76,"../internals/compareAscending":104,"../internals/getArray":110,"../internals/getObject":111,"../internals/releaseArray":124,"../internals/releaseObject":125,"../objects/isArray":147,"./forEach":51,"./map":56}],68:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isString = require('../objects/isString'),
    slice = require('../internals/slice'),
    values = require('../objects/values');

/**
 * Converts the `collection` to an array.
 *
 * @static
 * @memberOf _
 * @category Collections
 * @param {Array|Object|string} collection The collection to convert.
 * @returns {Array} Returns the new converted array.
 * @example
 *
 * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
 * // => [2, 3, 4]
 */
function toArray(collection) {
  if (collection && typeof collection.length == 'number') {
    return slice(collection);
  }
  return values(collection);
}

module.exports = toArray;

},{"../internals/slice":129,"../objects/isString":161,"../objects/values":170}],69:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var filter = require('./filter');

/**
 * Performs a deep comparison of each element in a `collection` to the given
 * `properties` object, returning an array of all elements that have equivalent
 * property values.
 *
 * @static
 * @memberOf _
 * @type Function
 * @category Collections
 * @param {Array|Object|string} collection The collection to iterate over.
 * @param {Object} props The object of property values to filter by.
 * @returns {Array} Returns a new array of elements that have the given properties.
 * @example
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] },
 *   { 'name': 'fred',   'age': 40, 'pets': ['baby puss', 'dino'] }
 * ];
 *
 * _.where(characters, { 'age': 36 });
 * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }]
 *
 * _.where(characters, { 'pets': ['dino'] });
 * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]
 */
var where = filter;

module.exports = where;

},{"./filter":48}],70:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

module.exports = {
  'after': require('./functions/after'),
  'bind': require('./functions/bind'),
  'bindAll': require('./functions/bindAll'),
  'bindKey': require('./functions/bindKey'),
  'compose': require('./functions/compose'),
  'createCallback': require('./functions/createCallback'),
  'curry': require('./functions/curry'),
  'debounce': require('./functions/debounce'),
  'defer': require('./functions/defer'),
  'delay': require('./functions/delay'),
  'memoize': require('./functions/memoize'),
  'once': require('./functions/once'),
  'partial': require('./functions/partial'),
  'partialRight': require('./functions/partialRight'),
  'throttle': require('./functions/throttle'),
  'wrap': require('./functions/wrap')
};

},{"./functions/after":71,"./functions/bind":72,"./functions/bindAll":73,"./functions/bindKey":74,"./functions/compose":75,"./functions/createCallback":76,"./functions/curry":77,"./functions/debounce":78,"./functions/defer":79,"./functions/delay":80,"./functions/memoize":81,"./functions/once":82,"./functions/partial":83,"./functions/partialRight":84,"./functions/throttle":85,"./functions/wrap":86}],71:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isFunction = require('../objects/isFunction');

/**
 * Creates a function that executes `func`, with  the `this` binding and
 * arguments of the created function, only after being called `n` times.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {number} n The number of times the function must be called before
 *  `func` is executed.
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new restricted function.
 * @example
 *
 * var saves = ['profile', 'settings'];
 *
 * var done = _.after(saves.length, function() {
 *   console.log('Done saving!');
 * });
 *
 * _.forEach(saves, function(type) {
 *   asyncSave({ 'type': type, 'complete': done });
 * });
 * // => logs 'Done saving!', after all saves have completed
 */
function after(n, func) {
  if (!isFunction(func)) {
    throw new TypeError;
  }
  return function() {
    if (--n < 1) {
      return func.apply(this, arguments);
    }
  };
}

module.exports = after;

},{"../objects/isFunction":154}],72:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createWrapper = require('../internals/createWrapper'),
    slice = require('../internals/slice');

/**
 * Creates a function that, when called, invokes `func` with the `this`
 * binding of `thisArg` and prepends any additional `bind` arguments to those
 * provided to the bound function.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Function} func The function to bind.
 * @param {*} [thisArg] The `this` binding of `func`.
 * @param {...*} [arg] Arguments to be partially applied.
 * @returns {Function} Returns the new bound function.
 * @example
 *
 * var func = function(greeting) {
 *   return greeting + ' ' + this.name;
 * };
 *
 * func = _.bind(func, { 'name': 'fred' }, 'hi');
 * func();
 * // => 'hi fred'
 */
function bind(func, thisArg) {
  return arguments.length > 2
    ? createWrapper(func, 17, slice(arguments, 2), null, thisArg)
    : createWrapper(func, 1, null, null, thisArg);
}

module.exports = bind;

},{"../internals/createWrapper":107,"../internals/slice":129}],73:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseFlatten = require('../internals/baseFlatten'),
    createWrapper = require('../internals/createWrapper'),
    functions = require('../objects/functions');

/**
 * Binds methods of an object to the object itself, overwriting the existing
 * method. Method names may be specified as individual arguments or as arrays
 * of method names. If no method names are provided all the function properties
 * of `object` will be bound.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Object} object The object to bind and assign the bound methods to.
 * @param {...string} [methodName] The object method names to
 *  bind, specified as individual method names or arrays of method names.
 * @returns {Object} Returns `object`.
 * @example
 *
 * var view = {
 *   'label': 'docs',
 *   'onClick': function() { console.log('clicked ' + this.label); }
 * };
 *
 * _.bindAll(view);
 * jQuery('#docs').on('click', view.onClick);
 * // => logs 'clicked docs', when the button is clicked
 */
function bindAll(object) {
  var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object),
      index = -1,
      length = funcs.length;

  while (++index < length) {
    var key = funcs[index];
    object[key] = createWrapper(object[key], 1, null, null, object);
  }
  return object;
}

module.exports = bindAll;

},{"../internals/baseFlatten":95,"../internals/createWrapper":107,"../objects/functions":143}],74:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createWrapper = require('../internals/createWrapper'),
    slice = require('../internals/slice');

/**
 * Creates a function that, when called, invokes the method at `object[key]`
 * and prepends any additional `bindKey` arguments to those provided to the bound
 * function. This method differs from `_.bind` by allowing bound functions to
 * reference methods that will be redefined or don't yet exist.
 * See http://michaux.ca/articles/lazy-function-definition-pattern.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Object} object The object the method belongs to.
 * @param {string} key The key of the method.
 * @param {...*} [arg] Arguments to be partially applied.
 * @returns {Function} Returns the new bound function.
 * @example
 *
 * var object = {
 *   'name': 'fred',
 *   'greet': function(greeting) {
 *     return greeting + ' ' + this.name;
 *   }
 * };
 *
 * var func = _.bindKey(object, 'greet', 'hi');
 * func();
 * // => 'hi fred'
 *
 * object.greet = function(greeting) {
 *   return greeting + 'ya ' + this.name + '!';
 * };
 *
 * func();
 * // => 'hiya fred!'
 */
function bindKey(object, key) {
  return arguments.length > 2
    ? createWrapper(key, 19, slice(arguments, 2), null, object)
    : createWrapper(key, 3, null, null, object);
}

module.exports = bindKey;

},{"../internals/createWrapper":107,"../internals/slice":129}],75:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isFunction = require('../objects/isFunction');

/**
 * Creates a function that is the composition of the provided functions,
 * where each function consumes the return value of the function that follows.
 * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
 * Each function is executed with the `this` binding of the composed function.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {...Function} [func] Functions to compose.
 * @returns {Function} Returns the new composed function.
 * @example
 *
 * var realNameMap = {
 *   'pebbles': 'penelope'
 * };
 *
 * var format = function(name) {
 *   name = realNameMap[name.toLowerCase()] || name;
 *   return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
 * };
 *
 * var greet = function(formatted) {
 *   return 'Hiya ' + formatted + '!';
 * };
 *
 * var welcome = _.compose(greet, format);
 * welcome('pebbles');
 * // => 'Hiya Penelope!'
 */
function compose() {
  var funcs = arguments,
      length = funcs.length;

  while (length--) {
    if (!isFunction(funcs[length])) {
      throw new TypeError;
    }
  }
  return function() {
    var args = arguments,
        length = funcs.length;

    while (length--) {
      args = [funcs[length].apply(this, args)];
    }
    return args[0];
  };
}

module.exports = compose;

},{"../objects/isFunction":154}],76:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreateCallback = require('../internals/baseCreateCallback'),
    baseIsEqual = require('../internals/baseIsEqual'),
    isObject = require('../objects/isObject'),
    keys = require('../objects/keys'),
    property = require('../utilities/property');

/**
 * Produces a callback bound to an optional `thisArg`. If `func` is a property
 * name the created callback will return the property value for a given element.
 * If `func` is an object the created callback will return `true` for elements
 * that contain the equivalent object properties, otherwise it will return `false`.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {*} [func=identity] The value to convert to a callback.
 * @param {*} [thisArg] The `this` binding of the created callback.
 * @param {number} [argCount] The number of arguments the callback accepts.
 * @returns {Function} Returns a callback function.
 * @example
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36 },
 *   { 'name': 'fred',   'age': 40 }
 * ];
 *
 * // wrap to create custom callback shorthands
 * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
 *   var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
 *   return !match ? func(callback, thisArg) : function(object) {
 *     return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
 *   };
 * });
 *
 * _.filter(characters, 'age__gt38');
 * // => [{ 'name': 'fred', 'age': 40 }]
 */
function createCallback(func, thisArg, argCount) {
  var type = typeof func;
  if (func == null || type == 'function') {
    return baseCreateCallback(func, thisArg, argCount);
  }
  // handle "_.pluck" style callback shorthands
  if (type != 'object') {
    return property(func);
  }
  var props = keys(func),
      key = props[0],
      a = func[key];

  // handle "_.where" style callback shorthands
  if (props.length == 1 && a === a && !isObject(a)) {
    // fast path the common case of providing an object with a single
    // property containing a primitive value
    return function(object) {
      var b = object[key];
      return a === b && (a !== 0 || (1 / a == 1 / b));
    };
  }
  return function(object) {
    var length = props.length,
        result = false;

    while (length--) {
      if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
        break;
      }
    }
    return result;
  };
}

module.exports = createCallback;

},{"../internals/baseCreateCallback":92,"../internals/baseIsEqual":97,"../objects/isObject":158,"../objects/keys":163,"../utilities/property":181}],77:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createWrapper = require('../internals/createWrapper');

/**
 * Creates a function which accepts one or more arguments of `func` that when
 * invoked either executes `func` returning its result, if all `func` arguments
 * have been provided, or returns a function that accepts one or more of the
 * remaining `func` arguments, and so on. The arity of `func` can be specified
 * if `func.length` is not sufficient.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Function} func The function to curry.
 * @param {number} [arity=func.length] The arity of `func`.
 * @returns {Function} Returns the new curried function.
 * @example
 *
 * var curried = _.curry(function(a, b, c) {
 *   console.log(a + b + c);
 * });
 *
 * curried(1)(2)(3);
 * // => 6
 *
 * curried(1, 2)(3);
 * // => 6
 *
 * curried(1, 2, 3);
 * // => 6
 */
function curry(func, arity) {
  arity = typeof arity == 'number' ? arity : (+arity || func.length);
  return createWrapper(func, 4, null, null, null, arity);
}

module.exports = curry;

},{"../internals/createWrapper":107}],78:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isFunction = require('../objects/isFunction'),
    isObject = require('../objects/isObject'),
    now = require('../utilities/now');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max;

/**
 * Creates a function that will delay the execution of `func` until after
 * `wait` milliseconds have elapsed since the last time it was invoked.
 * Provide an options object to indicate that `func` should be invoked on
 * the leading and/or trailing edge of the `wait` timeout. Subsequent calls
 * to the debounced function will return the result of the last `func` call.
 *
 * Note: If `leading` and `trailing` options are `true` `func` will be called
 * on the trailing edge of the timeout only if the the debounced function is
 * invoked more than once during the `wait` timeout.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Function} func The function to debounce.
 * @param {number} wait The number of milliseconds to delay.
 * @param {Object} [options] The options object.
 * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout.
 * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called.
 * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
 * @returns {Function} Returns the new debounced function.
 * @example
 *
 * // avoid costly calculations while the window size is in flux
 * var lazyLayout = _.debounce(calculateLayout, 150);
 * jQuery(window).on('resize', lazyLayout);
 *
 * // execute `sendMail` when the click event is fired, debouncing subsequent calls
 * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
 *   'leading': true,
 *   'trailing': false
 * });
 *
 * // ensure `batchLog` is executed once after 1 second of debounced calls
 * var source = new EventSource('/stream');
 * source.addEventListener('message', _.debounce(batchLog, 250, {
 *   'maxWait': 1000
 * }, false);
 */
function debounce(func, wait, options) {
  var args,
      maxTimeoutId,
      result,
      stamp,
      thisArg,
      timeoutId,
      trailingCall,
      lastCalled = 0,
      maxWait = false,
      trailing = true;

  if (!isFunction(func)) {
    throw new TypeError;
  }
  wait = nativeMax(0, wait) || 0;
  if (options === true) {
    var leading = true;
    trailing = false;
  } else if (isObject(options)) {
    leading = options.leading;
    maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);
    trailing = 'trailing' in options ? options.trailing : trailing;
  }
  var delayed = function() {
    var remaining = wait - (now() - stamp);
    if (remaining <= 0) {
      if (maxTimeoutId) {
        clearTimeout(maxTimeoutId);
      }
      var isCalled = trailingCall;
      maxTimeoutId = timeoutId = trailingCall = undefined;
      if (isCalled) {
        lastCalled = now();
        result = func.apply(thisArg, args);
        if (!timeoutId && !maxTimeoutId) {
          args = thisArg = null;
        }
      }
    } else {
      timeoutId = setTimeout(delayed, remaining);
    }
  };

  var maxDelayed = function() {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    maxTimeoutId = timeoutId = trailingCall = undefined;
    if (trailing || (maxWait !== wait)) {
      lastCalled = now();
      result = func.apply(thisArg, args);
      if (!timeoutId && !maxTimeoutId) {
        args = thisArg = null;
      }
    }
  };

  return function() {
    args = arguments;
    stamp = now();
    thisArg = this;
    trailingCall = trailing && (timeoutId || !leading);

    if (maxWait === false) {
      var leadingCall = leading && !timeoutId;
    } else {
      if (!maxTimeoutId && !leading) {
        lastCalled = stamp;
      }
      var remaining = maxWait - (stamp - lastCalled),
          isCalled = remaining <= 0;

      if (isCalled) {
        if (maxTimeoutId) {
          maxTimeoutId = clearTimeout(maxTimeoutId);
        }
        lastCalled = stamp;
        result = func.apply(thisArg, args);
      }
      else if (!maxTimeoutId) {
        maxTimeoutId = setTimeout(maxDelayed, remaining);
      }
    }
    if (isCalled && timeoutId) {
      timeoutId = clearTimeout(timeoutId);
    }
    else if (!timeoutId && wait !== maxWait) {
      timeoutId = setTimeout(delayed, wait);
    }
    if (leadingCall) {
      isCalled = true;
      result = func.apply(thisArg, args);
    }
    if (isCalled && !timeoutId && !maxTimeoutId) {
      args = thisArg = null;
    }
    return result;
  };
}

module.exports = debounce;

},{"../objects/isFunction":154,"../objects/isObject":158,"../utilities/now":179}],79:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isFunction = require('../objects/isFunction'),
    slice = require('../internals/slice');

/**
 * Defers executing the `func` function until the current call stack has cleared.
 * Additional arguments will be provided to `func` when it is invoked.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Function} func The function to defer.
 * @param {...*} [arg] Arguments to invoke the function with.
 * @returns {number} Returns the timer id.
 * @example
 *
 * _.defer(function(text) { console.log(text); }, 'deferred');
 * // logs 'deferred' after one or more milliseconds
 */
function defer(func) {
  if (!isFunction(func)) {
    throw new TypeError;
  }
  var args = slice(arguments, 1);
  return setTimeout(function() { func.apply(undefined, args); }, 1);
}

module.exports = defer;

},{"../internals/slice":129,"../objects/isFunction":154}],80:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isFunction = require('../objects/isFunction'),
    slice = require('../internals/slice');

/**
 * Executes the `func` function after `wait` milliseconds. Additional arguments
 * will be provided to `func` when it is invoked.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Function} func The function to delay.
 * @param {number} wait The number of milliseconds to delay execution.
 * @param {...*} [arg] Arguments to invoke the function with.
 * @returns {number} Returns the timer id.
 * @example
 *
 * _.delay(function(text) { console.log(text); }, 1000, 'later');
 * // => logs 'later' after one second
 */
function delay(func, wait) {
  if (!isFunction(func)) {
    throw new TypeError;
  }
  var args = slice(arguments, 2);
  return setTimeout(function() { func.apply(undefined, args); }, wait);
}

module.exports = delay;

},{"../internals/slice":129,"../objects/isFunction":154}],81:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isFunction = require('../objects/isFunction'),
    keyPrefix = require('../internals/keyPrefix');

/** Used for native method references */
var objectProto = Object.prototype;

/** Native method shortcuts */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Creates a function that memoizes the result of `func`. If `resolver` is
 * provided it will be used to determine the cache key for storing the result
 * based on the arguments provided to the memoized function. By default, the
 * first argument provided to the memoized function is used as the cache key.
 * The `func` is executed with the `this` binding of the memoized function.
 * The result cache is exposed as the `cache` property on the memoized function.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Function} func The function to have its output memoized.
 * @param {Function} [resolver] A function used to resolve the cache key.
 * @returns {Function} Returns the new memoizing function.
 * @example
 *
 * var fibonacci = _.memoize(function(n) {
 *   return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
 * });
 *
 * fibonacci(9)
 * // => 34
 *
 * var data = {
 *   'fred': { 'name': 'fred', 'age': 40 },
 *   'pebbles': { 'name': 'pebbles', 'age': 1 }
 * };
 *
 * // modifying the result cache
 * var get = _.memoize(function(name) { return data[name]; }, _.identity);
 * get('pebbles');
 * // => { 'name': 'pebbles', 'age': 1 }
 *
 * get.cache.pebbles.name = 'penelope';
 * get('pebbles');
 * // => { 'name': 'penelope', 'age': 1 }
 */
function memoize(func, resolver) {
  if (!isFunction(func)) {
    throw new TypeError;
  }
  var memoized = function() {
    var cache = memoized.cache,
        key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];

    return hasOwnProperty.call(cache, key)
      ? cache[key]
      : (cache[key] = func.apply(this, arguments));
  }
  memoized.cache = {};
  return memoized;
}

module.exports = memoize;

},{"../internals/keyPrefix":115,"../objects/isFunction":154}],82:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isFunction = require('../objects/isFunction');

/**
 * Creates a function that is restricted to execute `func` once. Repeat calls to
 * the function will return the value of the first call. The `func` is executed
 * with the `this` binding of the created function.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new restricted function.
 * @example
 *
 * var initialize = _.once(createApplication);
 * initialize();
 * initialize();
 * // `initialize` executes `createApplication` once
 */
function once(func) {
  var ran,
      result;

  if (!isFunction(func)) {
    throw new TypeError;
  }
  return function() {
    if (ran) {
      return result;
    }
    ran = true;
    result = func.apply(this, arguments);

    // clear the `func` variable so the function may be garbage collected
    func = null;
    return result;
  };
}

module.exports = once;

},{"../objects/isFunction":154}],83:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createWrapper = require('../internals/createWrapper'),
    slice = require('../internals/slice');

/**
 * Creates a function that, when called, invokes `func` with any additional
 * `partial` arguments prepended to those provided to the new function. This
 * method is similar to `_.bind` except it does **not** alter the `this` binding.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Function} func The function to partially apply arguments to.
 * @param {...*} [arg] Arguments to be partially applied.
 * @returns {Function} Returns the new partially applied function.
 * @example
 *
 * var greet = function(greeting, name) { return greeting + ' ' + name; };
 * var hi = _.partial(greet, 'hi');
 * hi('fred');
 * // => 'hi fred'
 */
function partial(func) {
  return createWrapper(func, 16, slice(arguments, 1));
}

module.exports = partial;

},{"../internals/createWrapper":107,"../internals/slice":129}],84:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createWrapper = require('../internals/createWrapper'),
    slice = require('../internals/slice');

/**
 * This method is like `_.partial` except that `partial` arguments are
 * appended to those provided to the new function.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Function} func The function to partially apply arguments to.
 * @param {...*} [arg] Arguments to be partially applied.
 * @returns {Function} Returns the new partially applied function.
 * @example
 *
 * var defaultsDeep = _.partialRight(_.merge, _.defaults);
 *
 * var options = {
 *   'variable': 'data',
 *   'imports': { 'jq': $ }
 * };
 *
 * defaultsDeep(options, _.templateSettings);
 *
 * options.variable
 * // => 'data'
 *
 * options.imports
 * // => { '_': _, 'jq': $ }
 */
function partialRight(func) {
  return createWrapper(func, 32, null, slice(arguments, 1));
}

module.exports = partialRight;

},{"../internals/createWrapper":107,"../internals/slice":129}],85:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var debounce = require('./debounce'),
    isFunction = require('../objects/isFunction'),
    isObject = require('../objects/isObject');

/** Used as an internal `_.debounce` options object */
var debounceOptions = {
  'leading': false,
  'maxWait': 0,
  'trailing': false
};

/**
 * Creates a function that, when executed, will only call the `func` function
 * at most once per every `wait` milliseconds. Provide an options object to
 * indicate that `func` should be invoked on the leading and/or trailing edge
 * of the `wait` timeout. Subsequent calls to the throttled function will
 * return the result of the last `func` call.
 *
 * Note: If `leading` and `trailing` options are `true` `func` will be called
 * on the trailing edge of the timeout only if the the throttled function is
 * invoked more than once during the `wait` timeout.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {Function} func The function to throttle.
 * @param {number} wait The number of milliseconds to throttle executions to.
 * @param {Object} [options] The options object.
 * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout.
 * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
 * @returns {Function} Returns the new throttled function.
 * @example
 *
 * // avoid excessively updating the position while scrolling
 * var throttled = _.throttle(updatePosition, 100);
 * jQuery(window).on('scroll', throttled);
 *
 * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes
 * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
 *   'trailing': false
 * }));
 */
function throttle(func, wait, options) {
  var leading = true,
      trailing = true;

  if (!isFunction(func)) {
    throw new TypeError;
  }
  if (options === false) {
    leading = false;
  } else if (isObject(options)) {
    leading = 'leading' in options ? options.leading : leading;
    trailing = 'trailing' in options ? options.trailing : trailing;
  }
  debounceOptions.leading = leading;
  debounceOptions.maxWait = wait;
  debounceOptions.trailing = trailing;

  return debounce(func, wait, debounceOptions);
}

module.exports = throttle;

},{"../objects/isFunction":154,"../objects/isObject":158,"./debounce":78}],86:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createWrapper = require('../internals/createWrapper');

/**
 * Creates a function that provides `value` to the wrapper function as its
 * first argument. Additional arguments provided to the function are appended
 * to those provided to the wrapper function. The wrapper is executed with
 * the `this` binding of the created function.
 *
 * @static
 * @memberOf _
 * @category Functions
 * @param {*} value The value to wrap.
 * @param {Function} wrapper The wrapper function.
 * @returns {Function} Returns the new function.
 * @example
 *
 * var p = _.wrap(_.escape, function(func, text) {
 *   return '<p>' + func(text) + '</p>';
 * });
 *
 * p('Fred, Wilma, & Pebbles');
 * // => '<p>Fred, Wilma, &amp; Pebbles</p>'
 */
function wrap(value, wrapper) {
  return createWrapper(wrapper, 16, [value]);
}

module.exports = wrap;

},{"../internals/createWrapper":107}],87:[function(require,module,exports){
/**
 * @license
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var arrays = require('./arrays'),
    chaining = require('./chaining'),
    collections = require('./collections'),
    functions = require('./functions'),
    objects = require('./objects'),
    utilities = require('./utilities'),
    forEach = require('./collections/forEach'),
    forOwn = require('./objects/forOwn'),
    isArray = require('./objects/isArray'),
    lodashWrapper = require('./internals/lodashWrapper'),
    mixin = require('./utilities/mixin'),
    support = require('./support'),
    templateSettings = require('./utilities/templateSettings');

/**
 * Used for `Array` method references.
 *
 * Normally `Array.prototype` would suffice, however, using an array literal
 * avoids issues in Narwhal.
 */
var arrayRef = [];

/** Used for native method references */
var objectProto = Object.prototype;

/** Native method shortcuts */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Creates a `lodash` object which wraps the given value to enable intuitive
 * method chaining.
 *
 * In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
 * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
 * and `unshift`
 *
 * Chaining is supported in custom builds as long as the `value` method is
 * implicitly or explicitly included in the build.
 *
 * The chainable wrapper functions are:
 * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
 * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`,
 * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`,
 * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
 * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
 * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`,
 * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`,
 * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`,
 * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`,
 * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`,
 * and `zip`
 *
 * The non-chainable wrapper functions are:
 * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`,
 * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`,
 * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
 * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`,
 * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`,
 * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`,
 * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`,
 * `template`, `unescape`, `uniqueId`, and `value`
 *
 * The wrapper functions `first` and `last` return wrapped values when `n` is
 * provided, otherwise they return unwrapped values.
 *
 * Explicit chaining can be enabled by using the `_.chain` method.
 *
 * @name _
 * @constructor
 * @category Chaining
 * @param {*} value The value to wrap in a `lodash` instance.
 * @returns {Object} Returns a `lodash` instance.
 * @example
 *
 * var wrapped = _([1, 2, 3]);
 *
 * // returns an unwrapped value
 * wrapped.reduce(function(sum, num) {
 *   return sum + num;
 * });
 * // => 6
 *
 * // returns a wrapped value
 * var squares = wrapped.map(function(num) {
 *   return num * num;
 * });
 *
 * _.isArray(squares);
 * // => false
 *
 * _.isArray(squares.value());
 * // => true
 */
function lodash(value) {
  // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
  return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
   ? value
   : new lodashWrapper(value);
}
// ensure `new lodashWrapper` is an instance of `lodash`
lodashWrapper.prototype = lodash.prototype;

// wrap `_.mixin` so it works when provided only one argument
mixin = (function(fn) {
  var functions = objects.functions;
  return function(object, source, options) {
    if (!source || (!options && !functions(source).length)) {
      if (options == null) {
        options = source;
      }
      source = object;
      object = lodash;
    }
    return fn(object, source, options);
  };
}(mixin));

// add functions that return wrapped values when chaining
lodash.after = functions.after;
lodash.assign = objects.assign;
lodash.at = collections.at;
lodash.bind = functions.bind;
lodash.bindAll = functions.bindAll;
lodash.bindKey = functions.bindKey;
lodash.chain = chaining.chain;
lodash.compact = arrays.compact;
lodash.compose = functions.compose;
lodash.constant = utilities.constant;
lodash.countBy = collections.countBy;
lodash.create = objects.create;
lodash.createCallback = functions.createCallback;
lodash.curry = functions.curry;
lodash.debounce = functions.debounce;
lodash.defaults = objects.defaults;
lodash.defer = functions.defer;
lodash.delay = functions.delay;
lodash.difference = arrays.difference;
lodash.filter = collections.filter;
lodash.flatten = arrays.flatten;
lodash.forEach = forEach;
lodash.forEachRight = collections.forEachRight;
lodash.forIn = objects.forIn;
lodash.forInRight = objects.forInRight;
lodash.forOwn = forOwn;
lodash.forOwnRight = objects.forOwnRight;
lodash.functions = objects.functions;
lodash.groupBy = collections.groupBy;
lodash.indexBy = collections.indexBy;
lodash.initial = arrays.initial;
lodash.intersection = arrays.intersection;
lodash.invert = objects.invert;
lodash.invoke = collections.invoke;
lodash.keys = objects.keys;
lodash.map = collections.map;
lodash.mapValues = objects.mapValues;
lodash.max = collections.max;
lodash.memoize = functions.memoize;
lodash.merge = objects.merge;
lodash.min = collections.min;
lodash.omit = objects.omit;
lodash.once = functions.once;
lodash.pairs = objects.pairs;
lodash.partial = functions.partial;
lodash.partialRight = functions.partialRight;
lodash.pick = objects.pick;
lodash.pluck = collections.pluck;
lodash.property = utilities.property;
lodash.pull = arrays.pull;
lodash.range = arrays.range;
lodash.reject = collections.reject;
lodash.remove = arrays.remove;
lodash.rest = arrays.rest;
lodash.shuffle = collections.shuffle;
lodash.sortBy = collections.sortBy;
lodash.tap = chaining.tap;
lodash.throttle = functions.throttle;
lodash.times = utilities.times;
lodash.toArray = collections.toArray;
lodash.transform = objects.transform;
lodash.union = arrays.union;
lodash.uniq = arrays.uniq;
lodash.values = objects.values;
lodash.where = collections.where;
lodash.without = arrays.without;
lodash.wrap = functions.wrap;
lodash.xor = arrays.xor;
lodash.zip = arrays.zip;
lodash.zipObject = arrays.zipObject;

// add aliases
lodash.collect = collections.map;
lodash.drop = arrays.rest;
lodash.each = forEach;
lodash.eachRight = collections.forEachRight;
lodash.extend = objects.assign;
lodash.methods = objects.functions;
lodash.object = arrays.zipObject;
lodash.select = collections.filter;
lodash.tail = arrays.rest;
lodash.unique = arrays.uniq;
lodash.unzip = arrays.zip;

// add functions to `lodash.prototype`
mixin(lodash);

// add functions that return unwrapped values when chaining
lodash.clone = objects.clone;
lodash.cloneDeep = objects.cloneDeep;
lodash.contains = collections.contains;
lodash.escape = utilities.escape;
lodash.every = collections.every;
lodash.find = collections.find;
lodash.findIndex = arrays.findIndex;
lodash.findKey = objects.findKey;
lodash.findLast = collections.findLast;
lodash.findLastIndex = arrays.findLastIndex;
lodash.findLastKey = objects.findLastKey;
lodash.has = objects.has;
lodash.identity = utilities.identity;
lodash.indexOf = arrays.indexOf;
lodash.isArguments = objects.isArguments;
lodash.isArray = isArray;
lodash.isBoolean = objects.isBoolean;
lodash.isDate = objects.isDate;
lodash.isElement = objects.isElement;
lodash.isEmpty = objects.isEmpty;
lodash.isEqual = objects.isEqual;
lodash.isFinite = objects.isFinite;
lodash.isFunction = objects.isFunction;
lodash.isNaN = objects.isNaN;
lodash.isNull = objects.isNull;
lodash.isNumber = objects.isNumber;
lodash.isObject = objects.isObject;
lodash.isPlainObject = objects.isPlainObject;
lodash.isRegExp = objects.isRegExp;
lodash.isString = objects.isString;
lodash.isUndefined = objects.isUndefined;
lodash.lastIndexOf = arrays.lastIndexOf;
lodash.mixin = mixin;
lodash.noConflict = utilities.noConflict;
lodash.noop = utilities.noop;
lodash.now = utilities.now;
lodash.parseInt = utilities.parseInt;
lodash.random = utilities.random;
lodash.reduce = collections.reduce;
lodash.reduceRight = collections.reduceRight;
lodash.result = utilities.result;
lodash.size = collections.size;
lodash.some = collections.some;
lodash.sortedIndex = arrays.sortedIndex;
lodash.template = utilities.template;
lodash.unescape = utilities.unescape;
lodash.uniqueId = utilities.uniqueId;

// add aliases
lodash.all = collections.every;
lodash.any = collections.some;
lodash.detect = collections.find;
lodash.findWhere = collections.find;
lodash.foldl = collections.reduce;
lodash.foldr = collections.reduceRight;
lodash.include = collections.contains;
lodash.inject = collections.reduce;

mixin(function() {
  var source = {}
  forOwn(lodash, function(func, methodName) {
    if (!lodash.prototype[methodName]) {
      source[methodName] = func;
    }
  });
  return source;
}(), false);

// add functions capable of returning wrapped and unwrapped values when chaining
lodash.first = arrays.first;
lodash.last = arrays.last;
lodash.sample = collections.sample;

// add aliases
lodash.take = arrays.first;
lodash.head = arrays.first;

forOwn(lodash, function(func, methodName) {
  var callbackable = methodName !== 'sample';
  if (!lodash.prototype[methodName]) {
    lodash.prototype[methodName]= function(n, guard) {
      var chainAll = this.__chain__,
          result = func(this.__wrapped__, n, guard);

      return !chainAll && (n == null || (guard && !(callbackable && typeof n == 'function')))
        ? result
        : new lodashWrapper(result, chainAll);
    };
  }
});

/**
 * The semantic version number.
 *
 * @static
 * @memberOf _
 * @type string
 */
lodash.VERSION = '2.4.1';

// add "Chaining" functions to the wrapper
lodash.prototype.chain = chaining.wrapperChain;
lodash.prototype.toString = chaining.wrapperToString;
lodash.prototype.value = chaining.wrapperValueOf;
lodash.prototype.valueOf = chaining.wrapperValueOf;

// add `Array` functions that return unwrapped values
forEach(['join', 'pop', 'shift'], function(methodName) {
  var func = arrayRef[methodName];
  lodash.prototype[methodName] = function() {
    var chainAll = this.__chain__,
        result = func.apply(this.__wrapped__, arguments);

    return chainAll
      ? new lodashWrapper(result, chainAll)
      : result;
  };
});

// add `Array` functions that return the existing wrapped value
forEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) {
  var func = arrayRef[methodName];
  lodash.prototype[methodName] = function() {
    func.apply(this.__wrapped__, arguments);
    return this;
  };
});

// add `Array` functions that return new wrapped values
forEach(['concat', 'slice', 'splice'], function(methodName) {
  var func = arrayRef[methodName];
  lodash.prototype[methodName] = function() {
    return new lodashWrapper(func.apply(this.__wrapped__, arguments), this.__chain__);
  };
});

lodash.support = support;
(lodash.templateSettings = utilities.templateSettings).imports._ = lodash;
module.exports = lodash;

},{"./arrays":14,"./chaining":37,"./collections":43,"./collections/forEach":51,"./functions":70,"./internals/lodashWrapper":117,"./objects":131,"./objects/forOwn":141,"./objects/isArray":147,"./support":171,"./utilities":172,"./utilities/mixin":176,"./utilities/templateSettings":185}],88:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used to pool arrays and objects used internally */
var arrayPool = [];

module.exports = arrayPool;

},{}],89:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreate = require('./baseCreate'),
    isObject = require('../objects/isObject'),
    setBindData = require('./setBindData'),
    slice = require('./slice');

/**
 * Used for `Array` method references.
 *
 * Normally `Array.prototype` would suffice, however, using an array literal
 * avoids issues in Narwhal.
 */
var arrayRef = [];

/** Native method shortcuts */
var push = arrayRef.push;

/**
 * The base implementation of `_.bind` that creates the bound function and
 * sets its meta data.
 *
 * @private
 * @param {Array} bindData The bind data array.
 * @returns {Function} Returns the new bound function.
 */
function baseBind(bindData) {
  var func = bindData[0],
      partialArgs = bindData[2],
      thisArg = bindData[4];

  function bound() {
    // `Function#bind` spec
    // http://es5.github.io/#x15.3.4.5
    if (partialArgs) {
      // avoid `arguments` object deoptimizations by using `slice` instead
      // of `Array.prototype.slice.call` and not assigning `arguments` to a
      // variable as a ternary expression
      var args = slice(partialArgs);
      push.apply(args, arguments);
    }
    // mimic the constructor's `return` behavior
    // http://es5.github.io/#x13.2.2
    if (this instanceof bound) {
      // ensure `new bound` is an instance of `func`
      var thisBinding = baseCreate(func.prototype),
          result = func.apply(thisBinding, args || arguments);
      return isObject(result) ? result : thisBinding;
    }
    return func.apply(thisArg, args || arguments);
  }
  setBindData(bound, bindData);
  return bound;
}

module.exports = baseBind;

},{"../objects/isObject":158,"./baseCreate":91,"./setBindData":126,"./slice":129}],90:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var assign = require('../objects/assign'),
    forEach = require('../collections/forEach'),
    forOwn = require('../objects/forOwn'),
    getArray = require('./getArray'),
    isArray = require('../objects/isArray'),
    isObject = require('../objects/isObject'),
    releaseArray = require('./releaseArray'),
    slice = require('./slice');

/** Used to match regexp flags from their coerced string values */
var reFlags = /\w*$/;

/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
    arrayClass = '[object Array]',
    boolClass = '[object Boolean]',
    dateClass = '[object Date]',
    funcClass = '[object Function]',
    numberClass = '[object Number]',
    objectClass = '[object Object]',
    regexpClass = '[object RegExp]',
    stringClass = '[object String]';

/** Used to identify object classifications that `_.clone` supports */
var cloneableClasses = {};
cloneableClasses[funcClass] = false;
cloneableClasses[argsClass] = cloneableClasses[arrayClass] =
cloneableClasses[boolClass] = cloneableClasses[dateClass] =
cloneableClasses[numberClass] = cloneableClasses[objectClass] =
cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true;

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/** Native method shortcuts */
var hasOwnProperty = objectProto.hasOwnProperty;

/** Used to lookup a built-in constructor by [[Class]] */
var ctorByClass = {};
ctorByClass[arrayClass] = Array;
ctorByClass[boolClass] = Boolean;
ctorByClass[dateClass] = Date;
ctorByClass[funcClass] = Function;
ctorByClass[objectClass] = Object;
ctorByClass[numberClass] = Number;
ctorByClass[regexpClass] = RegExp;
ctorByClass[stringClass] = String;

/**
 * The base implementation of `_.clone` without argument juggling or support
 * for `thisArg` binding.
 *
 * @private
 * @param {*} value The value to clone.
 * @param {boolean} [isDeep=false] Specify a deep clone.
 * @param {Function} [callback] The function to customize cloning values.
 * @param {Array} [stackA=[]] Tracks traversed source objects.
 * @param {Array} [stackB=[]] Associates clones with source counterparts.
 * @returns {*} Returns the cloned value.
 */
function baseClone(value, isDeep, callback, stackA, stackB) {
  if (callback) {
    var result = callback(value);
    if (typeof result != 'undefined') {
      return result;
    }
  }
  // inspect [[Class]]
  var isObj = isObject(value);
  if (isObj) {
    var className = toString.call(value);
    if (!cloneableClasses[className]) {
      return value;
    }
    var ctor = ctorByClass[className];
    switch (className) {
      case boolClass:
      case dateClass:
        return new ctor(+value);

      case numberClass:
      case stringClass:
        return new ctor(value);

      case regexpClass:
        result = ctor(value.source, reFlags.exec(value));
        result.lastIndex = value.lastIndex;
        return result;
    }
  } else {
    return value;
  }
  var isArr = isArray(value);
  if (isDeep) {
    // check for circular references and return corresponding clone
    var initedStack = !stackA;
    stackA || (stackA = getArray());
    stackB || (stackB = getArray());

    var length = stackA.length;
    while (length--) {
      if (stackA[length] == value) {
        return stackB[length];
      }
    }
    result = isArr ? ctor(value.length) : {};
  }
  else {
    result = isArr ? slice(value) : assign({}, value);
  }
  // add array properties assigned by `RegExp#exec`
  if (isArr) {
    if (hasOwnProperty.call(value, 'index')) {
      result.index = value.index;
    }
    if (hasOwnProperty.call(value, 'input')) {
      result.input = value.input;
    }
  }
  // exit for shallow clone
  if (!isDeep) {
    return result;
  }
  // add the source value to the stack of traversed objects
  // and associate it with its clone
  stackA.push(value);
  stackB.push(result);

  // recursively populate clone (susceptible to call stack limits)
  (isArr ? forEach : forOwn)(value, function(objValue, key) {
    result[key] = baseClone(objValue, isDeep, callback, stackA, stackB);
  });

  if (initedStack) {
    releaseArray(stackA);
    releaseArray(stackB);
  }
  return result;
}

module.exports = baseClone;

},{"../collections/forEach":51,"../objects/assign":132,"../objects/forOwn":141,"../objects/isArray":147,"../objects/isObject":158,"./getArray":110,"./releaseArray":124,"./slice":129}],91:[function(require,module,exports){
var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isNative = require('./isNative'),
    isObject = require('../objects/isObject'),
    noop = require('../utilities/noop');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate;

/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} prototype The object to inherit from.
 * @returns {Object} Returns the new object.
 */
function baseCreate(prototype, properties) {
  return isObject(prototype) ? nativeCreate(prototype) : {};
}
// fallback for browsers without `Object.create`
if (!nativeCreate) {
  baseCreate = (function() {
    function Object() {}
    return function(prototype) {
      if (isObject(prototype)) {
        Object.prototype = prototype;
        var result = new Object;
        Object.prototype = null;
      }
      return result || global.Object();
    };
  }());
}

module.exports = baseCreate;

},{"../objects/isObject":158,"../utilities/noop":178,"./isNative":114}],92:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var bind = require('../functions/bind'),
    identity = require('../utilities/identity'),
    setBindData = require('./setBindData'),
    support = require('../support');

/** Used to detected named functions */
var reFuncName = /^\s*function[ \n\r\t]+\w/;

/** Used to detect functions containing a `this` reference */
var reThis = /\bthis\b/;

/** Native method shortcuts */
var fnToString = Function.prototype.toString;

/**
 * The base implementation of `_.createCallback` without support for creating
 * "_.pluck" or "_.where" style callbacks.
 *
 * @private
 * @param {*} [func=identity] The value to convert to a callback.
 * @param {*} [thisArg] The `this` binding of the created callback.
 * @param {number} [argCount] The number of arguments the callback accepts.
 * @returns {Function} Returns a callback function.
 */
function baseCreateCallback(func, thisArg, argCount) {
  if (typeof func != 'function') {
    return identity;
  }
  // exit early for no `thisArg` or already bound by `Function#bind`
  if (typeof thisArg == 'undefined' || !('prototype' in func)) {
    return func;
  }
  var bindData = func.__bindData__;
  if (typeof bindData == 'undefined') {
    if (support.funcNames) {
      bindData = !func.name;
    }
    bindData = bindData || !support.funcDecomp;
    if (!bindData) {
      var source = fnToString.call(func);
      if (!support.funcNames) {
        bindData = !reFuncName.test(source);
      }
      if (!bindData) {
        // checks if `func` references the `this` keyword and stores the result
        bindData = reThis.test(source);
        setBindData(func, bindData);
      }
    }
  }
  // exit early if there are no `this` references or `func` is bound
  if (bindData === false || (bindData !== true && bindData[1] & 1)) {
    return func;
  }
  switch (argCount) {
    case 1: return function(value) {
      return func.call(thisArg, value);
    };
    case 2: return function(a, b) {
      return func.call(thisArg, a, b);
    };
    case 3: return function(value, index, collection) {
      return func.call(thisArg, value, index, collection);
    };
    case 4: return function(accumulator, value, index, collection) {
      return func.call(thisArg, accumulator, value, index, collection);
    };
  }
  return bind(func, thisArg);
}

module.exports = baseCreateCallback;

},{"../functions/bind":72,"../support":171,"../utilities/identity":175,"./setBindData":126}],93:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreate = require('./baseCreate'),
    isObject = require('../objects/isObject'),
    setBindData = require('./setBindData'),
    slice = require('./slice');

/**
 * Used for `Array` method references.
 *
 * Normally `Array.prototype` would suffice, however, using an array literal
 * avoids issues in Narwhal.
 */
var arrayRef = [];

/** Native method shortcuts */
var push = arrayRef.push;

/**
 * The base implementation of `createWrapper` that creates the wrapper and
 * sets its meta data.
 *
 * @private
 * @param {Array} bindData The bind data array.
 * @returns {Function} Returns the new function.
 */
function baseCreateWrapper(bindData) {
  var func = bindData[0],
      bitmask = bindData[1],
      partialArgs = bindData[2],
      partialRightArgs = bindData[3],
      thisArg = bindData[4],
      arity = bindData[5];

  var isBind = bitmask & 1,
      isBindKey = bitmask & 2,
      isCurry = bitmask & 4,
      isCurryBound = bitmask & 8,
      key = func;

  function bound() {
    var thisBinding = isBind ? thisArg : this;
    if (partialArgs) {
      var args = slice(partialArgs);
      push.apply(args, arguments);
    }
    if (partialRightArgs || isCurry) {
      args || (args = slice(arguments));
      if (partialRightArgs) {
        push.apply(args, partialRightArgs);
      }
      if (isCurry && args.length < arity) {
        bitmask |= 16 & ~32;
        return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]);
      }
    }
    args || (args = arguments);
    if (isBindKey) {
      func = thisBinding[key];
    }
    if (this instanceof bound) {
      thisBinding = baseCreate(func.prototype);
      var result = func.apply(thisBinding, args);
      return isObject(result) ? result : thisBinding;
    }
    return func.apply(thisBinding, args);
  }
  setBindData(bound, bindData);
  return bound;
}

module.exports = baseCreateWrapper;

},{"../objects/isObject":158,"./baseCreate":91,"./setBindData":126,"./slice":129}],94:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseIndexOf = require('./baseIndexOf'),
    cacheIndexOf = require('./cacheIndexOf'),
    createCache = require('./createCache'),
    largeArraySize = require('./largeArraySize'),
    releaseObject = require('./releaseObject');

/**
 * The base implementation of `_.difference` that accepts a single array
 * of values to exclude.
 *
 * @private
 * @param {Array} array The array to process.
 * @param {Array} [values] The array of values to exclude.
 * @returns {Array} Returns a new array of filtered values.
 */
function baseDifference(array, values) {
  var index = -1,
      indexOf = baseIndexOf,
      length = array ? array.length : 0,
      isLarge = length >= largeArraySize,
      result = [];

  if (isLarge) {
    var cache = createCache(values);
    if (cache) {
      indexOf = cacheIndexOf;
      values = cache;
    } else {
      isLarge = false;
    }
  }
  while (++index < length) {
    var value = array[index];
    if (indexOf(values, value) < 0) {
      result.push(value);
    }
  }
  if (isLarge) {
    releaseObject(values);
  }
  return result;
}

module.exports = baseDifference;

},{"./baseIndexOf":96,"./cacheIndexOf":101,"./createCache":106,"./largeArraySize":116,"./releaseObject":125}],95:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isArguments = require('../objects/isArguments'),
    isArray = require('../objects/isArray');

/**
 * The base implementation of `_.flatten` without support for callback
 * shorthands or `thisArg` binding.
 *
 * @private
 * @param {Array} array The array to flatten.
 * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
 * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects.
 * @param {number} [fromIndex=0] The index to start from.
 * @returns {Array} Returns a new flattened array.
 */
function baseFlatten(array, isShallow, isStrict, fromIndex) {
  var index = (fromIndex || 0) - 1,
      length = array ? array.length : 0,
      result = [];

  while (++index < length) {
    var value = array[index];

    if (value && typeof value == 'object' && typeof value.length == 'number'
        && (isArray(value) || isArguments(value))) {
      // recursively flatten arrays (susceptible to call stack limits)
      if (!isShallow) {
        value = baseFlatten(value, isShallow, isStrict);
      }
      var valIndex = -1,
          valLength = value.length,
          resIndex = result.length;

      result.length += valLength;
      while (++valIndex < valLength) {
        result[resIndex++] = value[valIndex];
      }
    } else if (!isStrict) {
      result.push(value);
    }
  }
  return result;
}

module.exports = baseFlatten;

},{"../objects/isArguments":146,"../objects/isArray":147}],96:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * The base implementation of `_.indexOf` without support for binary searches
 * or `fromIndex` constraints.
 *
 * @private
 * @param {Array} array The array to search.
 * @param {*} value The value to search for.
 * @param {number} [fromIndex=0] The index to search from.
 * @returns {number} Returns the index of the matched value or `-1`.
 */
function baseIndexOf(array, value, fromIndex) {
  var index = (fromIndex || 0) - 1,
      length = array ? array.length : 0;

  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }
  return -1;
}

module.exports = baseIndexOf;

},{}],97:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var forIn = require('../objects/forIn'),
    getArray = require('./getArray'),
    isFunction = require('../objects/isFunction'),
    objectTypes = require('./objectTypes'),
    releaseArray = require('./releaseArray');

/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
    arrayClass = '[object Array]',
    boolClass = '[object Boolean]',
    dateClass = '[object Date]',
    numberClass = '[object Number]',
    objectClass = '[object Object]',
    regexpClass = '[object RegExp]',
    stringClass = '[object String]';

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/** Native method shortcuts */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * The base implementation of `_.isEqual`, without support for `thisArg` binding,
 * that allows partial "_.where" style comparisons.
 *
 * @private
 * @param {*} a The value to compare.
 * @param {*} b The other value to compare.
 * @param {Function} [callback] The function to customize comparing values.
 * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
 * @param {Array} [stackA=[]] Tracks traversed `a` objects.
 * @param {Array} [stackB=[]] Tracks traversed `b` objects.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 */
function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
  // used to indicate that when comparing objects, `a` has at least the properties of `b`
  if (callback) {
    var result = callback(a, b);
    if (typeof result != 'undefined') {
      return !!result;
    }
  }
  // exit early for identical values
  if (a === b) {
    // treat `+0` vs. `-0` as not equal
    return a !== 0 || (1 / a == 1 / b);
  }
  var type = typeof a,
      otherType = typeof b;

  // exit early for unlike primitive values
  if (a === a &&
      !(a && objectTypes[type]) &&
      !(b && objectTypes[otherType])) {
    return false;
  }
  // exit early for `null` and `undefined` avoiding ES3's Function#call behavior
  // http://es5.github.io/#x15.3.4.4
  if (a == null || b == null) {
    return a === b;
  }
  // compare [[Class]] names
  var className = toString.call(a),
      otherClass = toString.call(b);

  if (className == argsClass) {
    className = objectClass;
  }
  if (otherClass == argsClass) {
    otherClass = objectClass;
  }
  if (className != otherClass) {
    return false;
  }
  switch (className) {
    case boolClass:
    case dateClass:
      // coerce dates and booleans to numbers, dates to milliseconds and booleans
      // to `1` or `0` treating invalid dates coerced to `NaN` as not equal
      return +a == +b;

    case numberClass:
      // treat `NaN` vs. `NaN` as equal
      return (a != +a)
        ? b != +b
        // but treat `+0` vs. `-0` as not equal
        : (a == 0 ? (1 / a == 1 / b) : a == +b);

    case regexpClass:
    case stringClass:
      // coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
      // treat string primitives and their corresponding object instances as equal
      return a == String(b);
  }
  var isArr = className == arrayClass;
  if (!isArr) {
    // unwrap any `lodash` wrapped values
    var aWrapped = hasOwnProperty.call(a, '__wrapped__'),
        bWrapped = hasOwnProperty.call(b, '__wrapped__');

    if (aWrapped || bWrapped) {
      return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB);
    }
    // exit for functions and DOM nodes
    if (className != objectClass) {
      return false;
    }
    // in older versions of Opera, `arguments` objects have `Array` constructors
    var ctorA = a.constructor,
        ctorB = b.constructor;

    // non `Object` object instances with different constructors are not equal
    if (ctorA != ctorB &&
          !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
          ('constructor' in a && 'constructor' in b)
        ) {
      return false;
    }
  }
  // assume cyclic structures are equal
  // the algorithm for detecting cyclic structures is adapted from ES 5.1
  // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
  var initedStack = !stackA;
  stackA || (stackA = getArray());
  stackB || (stackB = getArray());

  var length = stackA.length;
  while (length--) {
    if (stackA[length] == a) {
      return stackB[length] == b;
    }
  }
  var size = 0;
  result = true;

  // add `a` and `b` to the stack of traversed objects
  stackA.push(a);
  stackB.push(b);

  // recursively compare objects and arrays (susceptible to call stack limits)
  if (isArr) {
    // compare lengths to determine if a deep comparison is necessary
    length = a.length;
    size = b.length;
    result = size == length;

    if (result || isWhere) {
      // deep compare the contents, ignoring non-numeric properties
      while (size--) {
        var index = length,
            value = b[size];

        if (isWhere) {
          while (index--) {
            if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
              break;
            }
          }
        } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
          break;
        }
      }
    }
  }
  else {
    // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
    // which, in this case, is more costly
    forIn(b, function(value, key, b) {
      if (hasOwnProperty.call(b, key)) {
        // count the number of properties.
        size++;
        // deep compare each property value.
        return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
      }
    });

    if (result && !isWhere) {
      // ensure both objects have the same number of properties
      forIn(a, function(value, key, a) {
        if (hasOwnProperty.call(a, key)) {
          // `size` will be `-1` if `a` has more properties than `b`
          return (result = --size > -1);
        }
      });
    }
  }
  stackA.pop();
  stackB.pop();

  if (initedStack) {
    releaseArray(stackA);
    releaseArray(stackB);
  }
  return result;
}

module.exports = baseIsEqual;

},{"../objects/forIn":139,"../objects/isFunction":154,"./getArray":110,"./objectTypes":120,"./releaseArray":124}],98:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var forEach = require('../collections/forEach'),
    forOwn = require('../objects/forOwn'),
    isArray = require('../objects/isArray'),
    isPlainObject = require('../objects/isPlainObject');

/**
 * The base implementation of `_.merge` without argument juggling or support
 * for `thisArg` binding.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @param {Function} [callback] The function to customize merging properties.
 * @param {Array} [stackA=[]] Tracks traversed source objects.
 * @param {Array} [stackB=[]] Associates values with source counterparts.
 */
function baseMerge(object, source, callback, stackA, stackB) {
  (isArray(source) ? forEach : forOwn)(source, function(source, key) {
    var found,
        isArr,
        result = source,
        value = object[key];

    if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
      // avoid merging previously merged cyclic sources
      var stackLength = stackA.length;
      while (stackLength--) {
        if ((found = stackA[stackLength] == source)) {
          value = stackB[stackLength];
          break;
        }
      }
      if (!found) {
        var isShallow;
        if (callback) {
          result = callback(value, source);
          if ((isShallow = typeof result != 'undefined')) {
            value = result;
          }
        }
        if (!isShallow) {
          value = isArr
            ? (isArray(value) ? value : [])
            : (isPlainObject(value) ? value : {});
        }
        // add `source` and associated `value` to the stack of traversed objects
        stackA.push(source);
        stackB.push(value);

        // recursively merge objects and arrays (susceptible to call stack limits)
        if (!isShallow) {
          baseMerge(value, source, callback, stackA, stackB);
        }
      }
    }
    else {
      if (callback) {
        result = callback(value, source);
        if (typeof result == 'undefined') {
          result = source;
        }
      }
      if (typeof result != 'undefined') {
        value = result;
      }
    }
    object[key] = value;
  });
}

module.exports = baseMerge;

},{"../collections/forEach":51,"../objects/forOwn":141,"../objects/isArray":147,"../objects/isPlainObject":159}],99:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Native method shortcuts */
var floor = Math.floor;

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeRandom = Math.random;

/**
 * The base implementation of `_.random` without argument juggling or support
 * for returning floating-point numbers.
 *
 * @private
 * @param {number} min The minimum possible value.
 * @param {number} max The maximum possible value.
 * @returns {number} Returns a random number.
 */
function baseRandom(min, max) {
  return min + floor(nativeRandom() * (max - min + 1));
}

module.exports = baseRandom;

},{}],100:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseIndexOf = require('./baseIndexOf'),
    cacheIndexOf = require('./cacheIndexOf'),
    createCache = require('./createCache'),
    getArray = require('./getArray'),
    largeArraySize = require('./largeArraySize'),
    releaseArray = require('./releaseArray'),
    releaseObject = require('./releaseObject');

/**
 * The base implementation of `_.uniq` without support for callback shorthands
 * or `thisArg` binding.
 *
 * @private
 * @param {Array} array The array to process.
 * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
 * @param {Function} [callback] The function called per iteration.
 * @returns {Array} Returns a duplicate-value-free array.
 */
function baseUniq(array, isSorted, callback) {
  var index = -1,
      indexOf = baseIndexOf,
      length = array ? array.length : 0,
      result = [];

  var isLarge = !isSorted && length >= largeArraySize,
      seen = (callback || isLarge) ? getArray() : result;

  if (isLarge) {
    var cache = createCache(seen);
    indexOf = cacheIndexOf;
    seen = cache;
  }
  while (++index < length) {
    var value = array[index],
        computed = callback ? callback(value, index, array) : value;

    if (isSorted
          ? !index || seen[seen.length - 1] !== computed
          : indexOf(seen, computed) < 0
        ) {
      if (callback || isLarge) {
        seen.push(computed);
      }
      result.push(value);
    }
  }
  if (isLarge) {
    releaseArray(seen.array);
    releaseObject(seen);
  } else if (callback) {
    releaseArray(seen);
  }
  return result;
}

module.exports = baseUniq;

},{"./baseIndexOf":96,"./cacheIndexOf":101,"./createCache":106,"./getArray":110,"./largeArraySize":116,"./releaseArray":124,"./releaseObject":125}],101:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseIndexOf = require('./baseIndexOf'),
    keyPrefix = require('./keyPrefix');

/**
 * An implementation of `_.contains` for cache objects that mimics the return
 * signature of `_.indexOf` by returning `0` if the value is found, else `-1`.
 *
 * @private
 * @param {Object} cache The cache object to inspect.
 * @param {*} value The value to search for.
 * @returns {number} Returns `0` if `value` is found, else `-1`.
 */
function cacheIndexOf(cache, value) {
  var type = typeof value;
  cache = cache.cache;

  if (type == 'boolean' || value == null) {
    return cache[value] ? 0 : -1;
  }
  if (type != 'number' && type != 'string') {
    type = 'object';
  }
  var key = type == 'number' ? value : keyPrefix + value;
  cache = (cache = cache[type]) && cache[key];

  return type == 'object'
    ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1)
    : (cache ? 0 : -1);
}

module.exports = cacheIndexOf;

},{"./baseIndexOf":96,"./keyPrefix":115}],102:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var keyPrefix = require('./keyPrefix');

/**
 * Adds a given value to the corresponding cache object.
 *
 * @private
 * @param {*} value The value to add to the cache.
 */
function cachePush(value) {
  var cache = this.cache,
      type = typeof value;

  if (type == 'boolean' || value == null) {
    cache[value] = true;
  } else {
    if (type != 'number' && type != 'string') {
      type = 'object';
    }
    var key = type == 'number' ? value : keyPrefix + value,
        typeCache = cache[type] || (cache[type] = {});

    if (type == 'object') {
      (typeCache[key] || (typeCache[key] = [])).push(value);
    } else {
      typeCache[key] = true;
    }
  }
}

module.exports = cachePush;

},{"./keyPrefix":115}],103:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Used by `_.max` and `_.min` as the default callback when a given
 * collection is a string value.
 *
 * @private
 * @param {string} value The character to inspect.
 * @returns {number} Returns the code unit of given character.
 */
function charAtCallback(value) {
  return value.charCodeAt(0);
}

module.exports = charAtCallback;

},{}],104:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Used by `sortBy` to compare transformed `collection` elements, stable sorting
 * them in ascending order.
 *
 * @private
 * @param {Object} a The object to compare to `b`.
 * @param {Object} b The object to compare to `a`.
 * @returns {number} Returns the sort order indicator of `1` or `-1`.
 */
function compareAscending(a, b) {
  var ac = a.criteria,
      bc = b.criteria,
      index = -1,
      length = ac.length;

  while (++index < length) {
    var value = ac[index],
        other = bc[index];

    if (value !== other) {
      if (value > other || typeof value == 'undefined') {
        return 1;
      }
      if (value < other || typeof other == 'undefined') {
        return -1;
      }
    }
  }
  // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
  // that causes it, under certain circumstances, to return the same value for
  // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247
  //
  // This also ensures a stable sort in V8 and other engines.
  // See http://code.google.com/p/v8/issues/detail?id=90
  return a.index - b.index;
}

module.exports = compareAscending;

},{}],105:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forOwn = require('../objects/forOwn'),
    isArray = require('../objects/isArray');

/**
 * Creates a function that aggregates a collection, creating an object composed
 * of keys generated from the results of running each element of the collection
 * through a callback. The given `setter` function sets the keys and values
 * of the composed object.
 *
 * @private
 * @param {Function} setter The setter function.
 * @returns {Function} Returns the new aggregator function.
 */
function createAggregator(setter) {
  return function(collection, callback, thisArg) {
    var result = {};
    callback = createCallback(callback, thisArg, 3);

    var index = -1,
        length = collection ? collection.length : 0;

    if (typeof length == 'number') {
      while (++index < length) {
        var value = collection[index];
        setter(result, value, callback(value, index, collection), collection);
      }
    } else {
      forOwn(collection, function(value, key, collection) {
        setter(result, value, callback(value, key, collection), collection);
      });
    }
    return result;
  };
}

module.exports = createAggregator;

},{"../functions/createCallback":76,"../objects/forOwn":141,"../objects/isArray":147}],106:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var cachePush = require('./cachePush'),
    getObject = require('./getObject'),
    releaseObject = require('./releaseObject');

/**
 * Creates a cache object to optimize linear searches of large arrays.
 *
 * @private
 * @param {Array} [array=[]] The array to search.
 * @returns {null|Object} Returns the cache object or `null` if caching should not be used.
 */
function createCache(array) {
  var index = -1,
      length = array.length,
      first = array[0],
      mid = array[(length / 2) | 0],
      last = array[length - 1];

  if (first && typeof first == 'object' &&
      mid && typeof mid == 'object' && last && typeof last == 'object') {
    return false;
  }
  var cache = getObject();
  cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;

  var result = getObject();
  result.array = array;
  result.cache = cache;
  result.push = cachePush;

  while (++index < length) {
    result.push(array[index]);
  }
  return result;
}

module.exports = createCache;

},{"./cachePush":102,"./getObject":111,"./releaseObject":125}],107:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseBind = require('./baseBind'),
    baseCreateWrapper = require('./baseCreateWrapper'),
    isFunction = require('../objects/isFunction'),
    slice = require('./slice');

/**
 * Used for `Array` method references.
 *
 * Normally `Array.prototype` would suffice, however, using an array literal
 * avoids issues in Narwhal.
 */
var arrayRef = [];

/** Native method shortcuts */
var push = arrayRef.push,
    unshift = arrayRef.unshift;

/**
 * Creates a function that, when called, either curries or invokes `func`
 * with an optional `this` binding and partially applied arguments.
 *
 * @private
 * @param {Function|string} func The function or method name to reference.
 * @param {number} bitmask The bitmask of method flags to compose.
 *  The bitmask may be composed of the following flags:
 *  1 - `_.bind`
 *  2 - `_.bindKey`
 *  4 - `_.curry`
 *  8 - `_.curry` (bound)
 *  16 - `_.partial`
 *  32 - `_.partialRight`
 * @param {Array} [partialArgs] An array of arguments to prepend to those
 *  provided to the new function.
 * @param {Array} [partialRightArgs] An array of arguments to append to those
 *  provided to the new function.
 * @param {*} [thisArg] The `this` binding of `func`.
 * @param {number} [arity] The arity of `func`.
 * @returns {Function} Returns the new function.
 */
function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
  var isBind = bitmask & 1,
      isBindKey = bitmask & 2,
      isCurry = bitmask & 4,
      isCurryBound = bitmask & 8,
      isPartial = bitmask & 16,
      isPartialRight = bitmask & 32;

  if (!isBindKey && !isFunction(func)) {
    throw new TypeError;
  }
  if (isPartial && !partialArgs.length) {
    bitmask &= ~16;
    isPartial = partialArgs = false;
  }
  if (isPartialRight && !partialRightArgs.length) {
    bitmask &= ~32;
    isPartialRight = partialRightArgs = false;
  }
  var bindData = func && func.__bindData__;
  if (bindData && bindData !== true) {
    // clone `bindData`
    bindData = slice(bindData);
    if (bindData[2]) {
      bindData[2] = slice(bindData[2]);
    }
    if (bindData[3]) {
      bindData[3] = slice(bindData[3]);
    }
    // set `thisBinding` is not previously bound
    if (isBind && !(bindData[1] & 1)) {
      bindData[4] = thisArg;
    }
    // set if previously bound but not currently (subsequent curried functions)
    if (!isBind && bindData[1] & 1) {
      bitmask |= 8;
    }
    // set curried arity if not yet set
    if (isCurry && !(bindData[1] & 4)) {
      bindData[5] = arity;
    }
    // append partial left arguments
    if (isPartial) {
      push.apply(bindData[2] || (bindData[2] = []), partialArgs);
    }
    // append partial right arguments
    if (isPartialRight) {
      unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
    }
    // merge flags
    bindData[1] |= bitmask;
    return createWrapper.apply(null, bindData);
  }
  // fast path for `_.bind`
  var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper;
  return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]);
}

module.exports = createWrapper;

},{"../objects/isFunction":154,"./baseBind":89,"./baseCreateWrapper":93,"./slice":129}],108:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var htmlEscapes = require('./htmlEscapes');

/**
 * Used by `escape` to convert characters to HTML entities.
 *
 * @private
 * @param {string} match The matched character to escape.
 * @returns {string} Returns the escaped character.
 */
function escapeHtmlChar(match) {
  return htmlEscapes[match];
}

module.exports = escapeHtmlChar;

},{"./htmlEscapes":112}],109:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used to escape characters for inclusion in compiled string literals */
var stringEscapes = {
  '\\': '\\',
  "'": "'",
  '\n': 'n',
  '\r': 'r',
  '\t': 't',
  '\u2028': 'u2028',
  '\u2029': 'u2029'
};

/**
 * Used by `template` to escape characters for inclusion in compiled
 * string literals.
 *
 * @private
 * @param {string} match The matched character to escape.
 * @returns {string} Returns the escaped character.
 */
function escapeStringChar(match) {
  return '\\' + stringEscapes[match];
}

module.exports = escapeStringChar;

},{}],110:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var arrayPool = require('./arrayPool');

/**
 * Gets an array from the array pool or creates a new one if the pool is empty.
 *
 * @private
 * @returns {Array} The array from the pool.
 */
function getArray() {
  return arrayPool.pop() || [];
}

module.exports = getArray;

},{"./arrayPool":88}],111:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var objectPool = require('./objectPool');

/**
 * Gets an object from the object pool or creates a new one if the pool is empty.
 *
 * @private
 * @returns {Object} The object from the pool.
 */
function getObject() {
  return objectPool.pop() || {
    'array': null,
    'cache': null,
    'criteria': null,
    'false': false,
    'index': 0,
    'null': false,
    'number': null,
    'object': null,
    'push': null,
    'string': null,
    'true': false,
    'undefined': false,
    'value': null
  };
}

module.exports = getObject;

},{"./objectPool":119}],112:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Used to convert characters to HTML entities:
 *
 * Though the `>` character is escaped for symmetry, characters like `>` and `/`
 * don't require escaping in HTML and have no special meaning unless they're part
 * of a tag or an unquoted attribute value.
 * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
 */
var htmlEscapes = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;'
};

module.exports = htmlEscapes;

},{}],113:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var htmlEscapes = require('./htmlEscapes'),
    invert = require('../objects/invert');

/** Used to convert HTML entities to characters */
var htmlUnescapes = invert(htmlEscapes);

module.exports = htmlUnescapes;

},{"../objects/invert":145,"./htmlEscapes":112}],114:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/** Used to detect if a method is native */
var reNative = RegExp('^' +
  String(toString)
    .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    .replace(/toString| for [^\]]+/g, '.*?') + '$'
);

/**
 * Checks if `value` is a native function.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is a native function, else `false`.
 */
function isNative(value) {
  return typeof value == 'function' && reNative.test(value);
}

module.exports = isNative;

},{}],115:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
var keyPrefix = +new Date + '';

module.exports = keyPrefix;

},{}],116:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used as the size when optimizations are enabled for large arrays */
var largeArraySize = 75;

module.exports = largeArraySize;

},{}],117:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * A fast path for creating `lodash` wrapper objects.
 *
 * @private
 * @param {*} value The value to wrap in a `lodash` instance.
 * @param {boolean} chainAll A flag to enable chaining for all methods
 * @returns {Object} Returns a `lodash` instance.
 */
function lodashWrapper(value, chainAll) {
  this.__chain__ = !!chainAll;
  this.__wrapped__ = value;
}

module.exports = lodashWrapper;

},{}],118:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used as the max size of the `arrayPool` and `objectPool` */
var maxPoolSize = 40;

module.exports = maxPoolSize;

},{}],119:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used to pool arrays and objects used internally */
var objectPool = [];

module.exports = objectPool;

},{}],120:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used to determine if values are of the language type Object */
var objectTypes = {
  'boolean': false,
  'function': true,
  'object': true,
  'number': false,
  'string': false,
  'undefined': false
};

module.exports = objectTypes;

},{}],121:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var htmlUnescapes = require('./htmlUnescapes'),
    keys = require('../objects/keys');

/** Used to match HTML entities and HTML characters */
var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g');

module.exports = reEscapedHtml;

},{"../objects/keys":163,"./htmlUnescapes":113}],122:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used to match "interpolate" template delimiters */
var reInterpolate = /<%=([\s\S]+?)%>/g;

module.exports = reInterpolate;

},{}],123:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var htmlEscapes = require('./htmlEscapes'),
    keys = require('../objects/keys');

/** Used to match HTML entities and HTML characters */
var reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g');

module.exports = reUnescapedHtml;

},{"../objects/keys":163,"./htmlEscapes":112}],124:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var arrayPool = require('./arrayPool'),
    maxPoolSize = require('./maxPoolSize');

/**
 * Releases the given array back to the array pool.
 *
 * @private
 * @param {Array} [array] The array to release.
 */
function releaseArray(array) {
  array.length = 0;
  if (arrayPool.length < maxPoolSize) {
    arrayPool.push(array);
  }
}

module.exports = releaseArray;

},{"./arrayPool":88,"./maxPoolSize":118}],125:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var maxPoolSize = require('./maxPoolSize'),
    objectPool = require('./objectPool');

/**
 * Releases the given object back to the object pool.
 *
 * @private
 * @param {Object} [object] The object to release.
 */
function releaseObject(object) {
  var cache = object.cache;
  if (cache) {
    releaseObject(cache);
  }
  object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
  if (objectPool.length < maxPoolSize) {
    objectPool.push(object);
  }
}

module.exports = releaseObject;

},{"./maxPoolSize":118,"./objectPool":119}],126:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isNative = require('./isNative'),
    noop = require('../utilities/noop');

/** Used as the property descriptor for `__bindData__` */
var descriptor = {
  'configurable': false,
  'enumerable': false,
  'value': null,
  'writable': false
};

/** Used to set meta data on functions */
var defineProperty = (function() {
  // IE 8 only accepts DOM elements
  try {
    var o = {},
        func = isNative(func = Object.defineProperty) && func,
        result = func(o, o, o) && func;
  } catch(e) { }
  return result;
}());

/**
 * Sets `this` binding data on a given function.
 *
 * @private
 * @param {Function} func The function to set data on.
 * @param {Array} value The data array to set.
 */
var setBindData = !defineProperty ? noop : function(func, value) {
  descriptor.value = value;
  defineProperty(func, '__bindData__', descriptor);
};

module.exports = setBindData;

},{"../utilities/noop":178,"./isNative":114}],127:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var forIn = require('../objects/forIn'),
    isFunction = require('../objects/isFunction');

/** `Object#toString` result shortcuts */
var objectClass = '[object Object]';

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/** Native method shortcuts */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * A fallback implementation of `isPlainObject` which checks if a given value
 * is an object created by the `Object` constructor, assuming objects created
 * by the `Object` constructor have no inherited enumerable properties and that
 * there are no `Object.prototype` extensions.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
 */
function shimIsPlainObject(value) {
  var ctor,
      result;

  // avoid non Object objects, `arguments` objects, and DOM elements
  if (!(value && toString.call(value) == objectClass) ||
      (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) {
    return false;
  }
  // In most environments an object's own properties are iterated before
  // its inherited properties. If the last iterated property is an object's
  // own property then there are no inherited enumerable properties.
  forIn(value, function(value, key) {
    result = key;
  });
  return typeof result == 'undefined' || hasOwnProperty.call(value, result);
}

module.exports = shimIsPlainObject;

},{"../objects/forIn":139,"../objects/isFunction":154}],128:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var objectTypes = require('./objectTypes');

/** Used for native method references */
var objectProto = Object.prototype;

/** Native method shortcuts */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * A fallback implementation of `Object.keys` which produces an array of the
 * given object's own enumerable property names.
 *
 * @private
 * @type Function
 * @param {Object} object The object to inspect.
 * @returns {Array} Returns an array of property names.
 */
var shimKeys = function(object) {
  var index, iterable = object, result = [];
  if (!iterable) return result;
  if (!(objectTypes[typeof object])) return result;
    for (index in iterable) {
      if (hasOwnProperty.call(iterable, index)) {
        result.push(index);
      }
    }
  return result
};

module.exports = shimKeys;

},{"./objectTypes":120}],129:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Slices the `collection` from the `start` index up to, but not including,
 * the `end` index.
 *
 * Note: This function is used instead of `Array#slice` to support node lists
 * in IE < 9 and to ensure dense arrays are returned.
 *
 * @private
 * @param {Array|Object|string} collection The collection to slice.
 * @param {number} start The start index.
 * @param {number} end The end index.
 * @returns {Array} Returns the new array.
 */
function slice(array, start, end) {
  start || (start = 0);
  if (typeof end == 'undefined') {
    end = array ? array.length : 0;
  }
  var index = -1,
      length = end - start || 0,
      result = Array(length < 0 ? 0 : length);

  while (++index < length) {
    result[index] = array[start + index];
  }
  return result;
}

module.exports = slice;

},{}],130:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var htmlUnescapes = require('./htmlUnescapes');

/**
 * Used by `unescape` to convert HTML entities to characters.
 *
 * @private
 * @param {string} match The matched character to unescape.
 * @returns {string} Returns the unescaped character.
 */
function unescapeHtmlChar(match) {
  return htmlUnescapes[match];
}

module.exports = unescapeHtmlChar;

},{"./htmlUnescapes":113}],131:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

module.exports = {
  'assign': require('./objects/assign'),
  'clone': require('./objects/clone'),
  'cloneDeep': require('./objects/cloneDeep'),
  'create': require('./objects/create'),
  'defaults': require('./objects/defaults'),
  'extend': require('./objects/assign'),
  'findKey': require('./objects/findKey'),
  'findLastKey': require('./objects/findLastKey'),
  'forIn': require('./objects/forIn'),
  'forInRight': require('./objects/forInRight'),
  'forOwn': require('./objects/forOwn'),
  'forOwnRight': require('./objects/forOwnRight'),
  'functions': require('./objects/functions'),
  'has': require('./objects/has'),
  'invert': require('./objects/invert'),
  'isArguments': require('./objects/isArguments'),
  'isArray': require('./objects/isArray'),
  'isBoolean': require('./objects/isBoolean'),
  'isDate': require('./objects/isDate'),
  'isElement': require('./objects/isElement'),
  'isEmpty': require('./objects/isEmpty'),
  'isEqual': require('./objects/isEqual'),
  'isFinite': require('./objects/isFinite'),
  'isFunction': require('./objects/isFunction'),
  'isNaN': require('./objects/isNaN'),
  'isNull': require('./objects/isNull'),
  'isNumber': require('./objects/isNumber'),
  'isObject': require('./objects/isObject'),
  'isPlainObject': require('./objects/isPlainObject'),
  'isRegExp': require('./objects/isRegExp'),
  'isString': require('./objects/isString'),
  'isUndefined': require('./objects/isUndefined'),
  'keys': require('./objects/keys'),
  'mapValues': require('./objects/mapValues'),
  'merge': require('./objects/merge'),
  'methods': require('./objects/functions'),
  'omit': require('./objects/omit'),
  'pairs': require('./objects/pairs'),
  'pick': require('./objects/pick'),
  'transform': require('./objects/transform'),
  'values': require('./objects/values')
};

},{"./objects/assign":132,"./objects/clone":133,"./objects/cloneDeep":134,"./objects/create":135,"./objects/defaults":136,"./objects/findKey":137,"./objects/findLastKey":138,"./objects/forIn":139,"./objects/forInRight":140,"./objects/forOwn":141,"./objects/forOwnRight":142,"./objects/functions":143,"./objects/has":144,"./objects/invert":145,"./objects/isArguments":146,"./objects/isArray":147,"./objects/isBoolean":148,"./objects/isDate":149,"./objects/isElement":150,"./objects/isEmpty":151,"./objects/isEqual":152,"./objects/isFinite":153,"./objects/isFunction":154,"./objects/isNaN":155,"./objects/isNull":156,"./objects/isNumber":157,"./objects/isObject":158,"./objects/isPlainObject":159,"./objects/isRegExp":160,"./objects/isString":161,"./objects/isUndefined":162,"./objects/keys":163,"./objects/mapValues":164,"./objects/merge":165,"./objects/omit":166,"./objects/pairs":167,"./objects/pick":168,"./objects/transform":169,"./objects/values":170}],132:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreateCallback = require('../internals/baseCreateCallback'),
    keys = require('./keys'),
    objectTypes = require('../internals/objectTypes');

/**
 * Assigns own enumerable properties of source object(s) to the destination
 * object. Subsequent sources will overwrite property assignments of previous
 * sources. If a callback is provided it will be executed to produce the
 * assigned values. The callback is bound to `thisArg` and invoked with two
 * arguments; (objectValue, sourceValue).
 *
 * @static
 * @memberOf _
 * @type Function
 * @alias extend
 * @category Objects
 * @param {Object} object The destination object.
 * @param {...Object} [source] The source objects.
 * @param {Function} [callback] The function to customize assigning values.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Object} Returns the destination object.
 * @example
 *
 * _.assign({ 'name': 'fred' }, { 'employer': 'slate' });
 * // => { 'name': 'fred', 'employer': 'slate' }
 *
 * var defaults = _.partialRight(_.assign, function(a, b) {
 *   return typeof a == 'undefined' ? b : a;
 * });
 *
 * var object = { 'name': 'barney' };
 * defaults(object, { 'name': 'fred', 'employer': 'slate' });
 * // => { 'name': 'barney', 'employer': 'slate' }
 */
var assign = function(object, source, guard) {
  var index, iterable = object, result = iterable;
  if (!iterable) return result;
  var args = arguments,
      argsIndex = 0,
      argsLength = typeof guard == 'number' ? 2 : args.length;
  if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {
    var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);
  } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {
    callback = args[--argsLength];
  }
  while (++argsIndex < argsLength) {
    iterable = args[argsIndex];
    if (iterable && objectTypes[typeof iterable]) {
    var ownIndex = -1,
        ownProps = objectTypes[typeof iterable] && keys(iterable),
        length = ownProps ? ownProps.length : 0;

    while (++ownIndex < length) {
      index = ownProps[ownIndex];
      result[index] = callback ? callback(result[index], iterable[index]) : iterable[index];
    }
    }
  }
  return result
};

module.exports = assign;

},{"../internals/baseCreateCallback":92,"../internals/objectTypes":120,"./keys":163}],133:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseClone = require('../internals/baseClone'),
    baseCreateCallback = require('../internals/baseCreateCallback');

/**
 * Creates a clone of `value`. If `isDeep` is `true` nested objects will also
 * be cloned, otherwise they will be assigned by reference. If a callback
 * is provided it will be executed to produce the cloned values. If the
 * callback returns `undefined` cloning will be handled by the method instead.
 * The callback is bound to `thisArg` and invoked with one argument; (value).
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to clone.
 * @param {boolean} [isDeep=false] Specify a deep clone.
 * @param {Function} [callback] The function to customize cloning values.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {*} Returns the cloned value.
 * @example
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36 },
 *   { 'name': 'fred',   'age': 40 }
 * ];
 *
 * var shallow = _.clone(characters);
 * shallow[0] === characters[0];
 * // => true
 *
 * var deep = _.clone(characters, true);
 * deep[0] === characters[0];
 * // => false
 *
 * _.mixin({
 *   'clone': _.partialRight(_.clone, function(value) {
 *     return _.isElement(value) ? value.cloneNode(false) : undefined;
 *   })
 * });
 *
 * var clone = _.clone(document.body);
 * clone.childNodes.length;
 * // => 0
 */
function clone(value, isDeep, callback, thisArg) {
  // allows working with "Collections" methods without using their `index`
  // and `collection` arguments for `isDeep` and `callback`
  if (typeof isDeep != 'boolean' && isDeep != null) {
    thisArg = callback;
    callback = isDeep;
    isDeep = false;
  }
  return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
}

module.exports = clone;

},{"../internals/baseClone":90,"../internals/baseCreateCallback":92}],134:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseClone = require('../internals/baseClone'),
    baseCreateCallback = require('../internals/baseCreateCallback');

/**
 * Creates a deep clone of `value`. If a callback is provided it will be
 * executed to produce the cloned values. If the callback returns `undefined`
 * cloning will be handled by the method instead. The callback is bound to
 * `thisArg` and invoked with one argument; (value).
 *
 * Note: This method is loosely based on the structured clone algorithm. Functions
 * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and
 * objects created by constructors other than `Object` are cloned to plain `Object` objects.
 * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to deep clone.
 * @param {Function} [callback] The function to customize cloning values.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {*} Returns the deep cloned value.
 * @example
 *
 * var characters = [
 *   { 'name': 'barney', 'age': 36 },
 *   { 'name': 'fred',   'age': 40 }
 * ];
 *
 * var deep = _.cloneDeep(characters);
 * deep[0] === characters[0];
 * // => false
 *
 * var view = {
 *   'label': 'docs',
 *   'node': element
 * };
 *
 * var clone = _.cloneDeep(view, function(value) {
 *   return _.isElement(value) ? value.cloneNode(true) : undefined;
 * });
 *
 * clone.node == view.node;
 * // => false
 */
function cloneDeep(value, callback, thisArg) {
  return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
}

module.exports = cloneDeep;

},{"../internals/baseClone":90,"../internals/baseCreateCallback":92}],135:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var assign = require('./assign'),
    baseCreate = require('../internals/baseCreate');

/**
 * Creates an object that inherits from the given `prototype` object. If a
 * `properties` object is provided its own enumerable properties are assigned
 * to the created object.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} prototype The object to inherit from.
 * @param {Object} [properties] The properties to assign to the object.
 * @returns {Object} Returns the new object.
 * @example
 *
 * function Shape() {
 *   this.x = 0;
 *   this.y = 0;
 * }
 *
 * function Circle() {
 *   Shape.call(this);
 * }
 *
 * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle });
 *
 * var circle = new Circle;
 * circle instanceof Circle;
 * // => true
 *
 * circle instanceof Shape;
 * // => true
 */
function create(prototype, properties) {
  var result = baseCreate(prototype);
  return properties ? assign(result, properties) : result;
}

module.exports = create;

},{"../internals/baseCreate":91,"./assign":132}],136:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var keys = require('./keys'),
    objectTypes = require('../internals/objectTypes');

/**
 * Assigns own enumerable properties of source object(s) to the destination
 * object for all destination properties that resolve to `undefined`. Once a
 * property is set, additional defaults of the same property will be ignored.
 *
 * @static
 * @memberOf _
 * @type Function
 * @category Objects
 * @param {Object} object The destination object.
 * @param {...Object} [source] The source objects.
 * @param- {Object} [guard] Allows working with `_.reduce` without using its
 *  `key` and `object` arguments as sources.
 * @returns {Object} Returns the destination object.
 * @example
 *
 * var object = { 'name': 'barney' };
 * _.defaults(object, { 'name': 'fred', 'employer': 'slate' });
 * // => { 'name': 'barney', 'employer': 'slate' }
 */
var defaults = function(object, source, guard) {
  var index, iterable = object, result = iterable;
  if (!iterable) return result;
  var args = arguments,
      argsIndex = 0,
      argsLength = typeof guard == 'number' ? 2 : args.length;
  while (++argsIndex < argsLength) {
    iterable = args[argsIndex];
    if (iterable && objectTypes[typeof iterable]) {
    var ownIndex = -1,
        ownProps = objectTypes[typeof iterable] && keys(iterable),
        length = ownProps ? ownProps.length : 0;

    while (++ownIndex < length) {
      index = ownProps[ownIndex];
      if (typeof result[index] == 'undefined') result[index] = iterable[index];
    }
    }
  }
  return result
};

module.exports = defaults;

},{"../internals/objectTypes":120,"./keys":163}],137:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forOwn = require('./forOwn');

/**
 * This method is like `_.findIndex` except that it returns the key of the
 * first element that passes the callback check, instead of the element itself.
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The object to search.
 * @param {Function|Object|string} [callback=identity] The function called per
 *  iteration. If a property name or object is provided it will be used to
 *  create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {string|undefined} Returns the key of the found element, else `undefined`.
 * @example
 *
 * var characters = {
 *   'barney': {  'age': 36, 'blocked': false },
 *   'fred': {    'age': 40, 'blocked': true },
 *   'pebbles': { 'age': 1,  'blocked': false }
 * };
 *
 * _.findKey(characters, function(chr) {
 *   return chr.age < 40;
 * });
 * // => 'barney' (property order is not guaranteed across environments)
 *
 * // using "_.where" callback shorthand
 * _.findKey(characters, { 'age': 1 });
 * // => 'pebbles'
 *
 * // using "_.pluck" callback shorthand
 * _.findKey(characters, 'blocked');
 * // => 'fred'
 */
function findKey(object, callback, thisArg) {
  var result;
  callback = createCallback(callback, thisArg, 3);
  forOwn(object, function(value, key, object) {
    if (callback(value, key, object)) {
      result = key;
      return false;
    }
  });
  return result;
}

module.exports = findKey;

},{"../functions/createCallback":76,"./forOwn":141}],138:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forOwnRight = require('./forOwnRight');

/**
 * This method is like `_.findKey` except that it iterates over elements
 * of a `collection` in the opposite order.
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The object to search.
 * @param {Function|Object|string} [callback=identity] The function called per
 *  iteration. If a property name or object is provided it will be used to
 *  create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {string|undefined} Returns the key of the found element, else `undefined`.
 * @example
 *
 * var characters = {
 *   'barney': {  'age': 36, 'blocked': true },
 *   'fred': {    'age': 40, 'blocked': false },
 *   'pebbles': { 'age': 1,  'blocked': true }
 * };
 *
 * _.findLastKey(characters, function(chr) {
 *   return chr.age < 40;
 * });
 * // => returns `pebbles`, assuming `_.findKey` returns `barney`
 *
 * // using "_.where" callback shorthand
 * _.findLastKey(characters, { 'age': 40 });
 * // => 'fred'
 *
 * // using "_.pluck" callback shorthand
 * _.findLastKey(characters, 'blocked');
 * // => 'pebbles'
 */
function findLastKey(object, callback, thisArg) {
  var result;
  callback = createCallback(callback, thisArg, 3);
  forOwnRight(object, function(value, key, object) {
    if (callback(value, key, object)) {
      result = key;
      return false;
    }
  });
  return result;
}

module.exports = findLastKey;

},{"../functions/createCallback":76,"./forOwnRight":142}],139:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreateCallback = require('../internals/baseCreateCallback'),
    objectTypes = require('../internals/objectTypes');

/**
 * Iterates over own and inherited enumerable properties of an object,
 * executing the callback for each property. The callback is bound to `thisArg`
 * and invoked with three arguments; (value, key, object). Callbacks may exit
 * iteration early by explicitly returning `false`.
 *
 * @static
 * @memberOf _
 * @type Function
 * @category Objects
 * @param {Object} object The object to iterate over.
 * @param {Function} [callback=identity] The function called per iteration.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Object} Returns `object`.
 * @example
 *
 * function Shape() {
 *   this.x = 0;
 *   this.y = 0;
 * }
 *
 * Shape.prototype.move = function(x, y) {
 *   this.x += x;
 *   this.y += y;
 * };
 *
 * _.forIn(new Shape, function(value, key) {
 *   console.log(key);
 * });
 * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments)
 */
var forIn = function(collection, callback, thisArg) {
  var index, iterable = collection, result = iterable;
  if (!iterable) return result;
  if (!objectTypes[typeof iterable]) return result;
  callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
    for (index in iterable) {
      if (callback(iterable[index], index, collection) === false) return result;
    }
  return result
};

module.exports = forIn;

},{"../internals/baseCreateCallback":92,"../internals/objectTypes":120}],140:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreateCallback = require('../internals/baseCreateCallback'),
    forIn = require('./forIn');

/**
 * This method is like `_.forIn` except that it iterates over elements
 * of a `collection` in the opposite order.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The object to iterate over.
 * @param {Function} [callback=identity] The function called per iteration.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Object} Returns `object`.
 * @example
 *
 * function Shape() {
 *   this.x = 0;
 *   this.y = 0;
 * }
 *
 * Shape.prototype.move = function(x, y) {
 *   this.x += x;
 *   this.y += y;
 * };
 *
 * _.forInRight(new Shape, function(value, key) {
 *   console.log(key);
 * });
 * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move'
 */
function forInRight(object, callback, thisArg) {
  var pairs = [];

  forIn(object, function(value, key) {
    pairs.push(key, value);
  });

  var length = pairs.length;
  callback = baseCreateCallback(callback, thisArg, 3);
  while (length--) {
    if (callback(pairs[length--], pairs[length], object) === false) {
      break;
    }
  }
  return object;
}

module.exports = forInRight;

},{"../internals/baseCreateCallback":92,"./forIn":139}],141:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreateCallback = require('../internals/baseCreateCallback'),
    keys = require('./keys'),
    objectTypes = require('../internals/objectTypes');

/**
 * Iterates over own enumerable properties of an object, executing the callback
 * for each property. The callback is bound to `thisArg` and invoked with three
 * arguments; (value, key, object). Callbacks may exit iteration early by
 * explicitly returning `false`.
 *
 * @static
 * @memberOf _
 * @type Function
 * @category Objects
 * @param {Object} object The object to iterate over.
 * @param {Function} [callback=identity] The function called per iteration.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Object} Returns `object`.
 * @example
 *
 * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
 *   console.log(key);
 * });
 * // => logs '0', '1', and 'length' (property order is not guaranteed across environments)
 */
var forOwn = function(collection, callback, thisArg) {
  var index, iterable = collection, result = iterable;
  if (!iterable) return result;
  if (!objectTypes[typeof iterable]) return result;
  callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
    var ownIndex = -1,
        ownProps = objectTypes[typeof iterable] && keys(iterable),
        length = ownProps ? ownProps.length : 0;

    while (++ownIndex < length) {
      index = ownProps[ownIndex];
      if (callback(iterable[index], index, collection) === false) return result;
    }
  return result
};

module.exports = forOwn;

},{"../internals/baseCreateCallback":92,"../internals/objectTypes":120,"./keys":163}],142:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreateCallback = require('../internals/baseCreateCallback'),
    keys = require('./keys');

/**
 * This method is like `_.forOwn` except that it iterates over elements
 * of a `collection` in the opposite order.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The object to iterate over.
 * @param {Function} [callback=identity] The function called per iteration.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Object} Returns `object`.
 * @example
 *
 * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
 *   console.log(key);
 * });
 * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
 */
function forOwnRight(object, callback, thisArg) {
  var props = keys(object),
      length = props.length;

  callback = baseCreateCallback(callback, thisArg, 3);
  while (length--) {
    var key = props[length];
    if (callback(object[key], key, object) === false) {
      break;
    }
  }
  return object;
}

module.exports = forOwnRight;

},{"../internals/baseCreateCallback":92,"./keys":163}],143:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var forIn = require('./forIn'),
    isFunction = require('./isFunction');

/**
 * Creates a sorted array of property names of all enumerable properties,
 * own and inherited, of `object` that have function values.
 *
 * @static
 * @memberOf _
 * @alias methods
 * @category Objects
 * @param {Object} object The object to inspect.
 * @returns {Array} Returns an array of property names that have function values.
 * @example
 *
 * _.functions(_);
 * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
 */
function functions(object) {
  var result = [];
  forIn(object, function(value, key) {
    if (isFunction(value)) {
      result.push(key);
    }
  });
  return result.sort();
}

module.exports = functions;

},{"./forIn":139,"./isFunction":154}],144:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used for native method references */
var objectProto = Object.prototype;

/** Native method shortcuts */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Checks if the specified property name exists as a direct property of `object`,
 * instead of an inherited property.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The object to inspect.
 * @param {string} key The name of the property to check.
 * @returns {boolean} Returns `true` if key is a direct property, else `false`.
 * @example
 *
 * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
 * // => true
 */
function has(object, key) {
  return object ? hasOwnProperty.call(object, key) : false;
}

module.exports = has;

},{}],145:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var keys = require('./keys');

/**
 * Creates an object composed of the inverted keys and values of the given object.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The object to invert.
 * @returns {Object} Returns the created inverted object.
 * @example
 *
 * _.invert({ 'first': 'fred', 'second': 'barney' });
 * // => { 'fred': 'first', 'barney': 'second' }
 */
function invert(object) {
  var index = -1,
      props = keys(object),
      length = props.length,
      result = {};

  while (++index < length) {
    var key = props[index];
    result[object[key]] = key;
  }
  return result;
}

module.exports = invert;

},{"./keys":163}],146:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]';

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/**
 * Checks if `value` is an `arguments` object.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
 * @example
 *
 * (function() { return _.isArguments(arguments); })(1, 2, 3);
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
function isArguments(value) {
  return value && typeof value == 'object' && typeof value.length == 'number' &&
    toString.call(value) == argsClass || false;
}

module.exports = isArguments;

},{}],147:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isNative = require('../internals/isNative');

/** `Object#toString` result shortcuts */
var arrayClass = '[object Array]';

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray;

/**
 * Checks if `value` is an array.
 *
 * @static
 * @memberOf _
 * @type Function
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is an array, else `false`.
 * @example
 *
 * (function() { return _.isArray(arguments); })();
 * // => false
 *
 * _.isArray([1, 2, 3]);
 * // => true
 */
var isArray = nativeIsArray || function(value) {
  return value && typeof value == 'object' && typeof value.length == 'number' &&
    toString.call(value) == arrayClass || false;
};

module.exports = isArray;

},{"../internals/isNative":114}],148:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** `Object#toString` result shortcuts */
var boolClass = '[object Boolean]';

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/**
 * Checks if `value` is a boolean value.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`.
 * @example
 *
 * _.isBoolean(null);
 * // => false
 */
function isBoolean(value) {
  return value === true || value === false ||
    value && typeof value == 'object' && toString.call(value) == boolClass || false;
}

module.exports = isBoolean;

},{}],149:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** `Object#toString` result shortcuts */
var dateClass = '[object Date]';

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/**
 * Checks if `value` is a date.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is a date, else `false`.
 * @example
 *
 * _.isDate(new Date);
 * // => true
 */
function isDate(value) {
  return value && typeof value == 'object' && toString.call(value) == dateClass || false;
}

module.exports = isDate;

},{}],150:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Checks if `value` is a DOM element.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`.
 * @example
 *
 * _.isElement(document.body);
 * // => true
 */
function isElement(value) {
  return value && value.nodeType === 1 || false;
}

module.exports = isElement;

},{}],151:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var forOwn = require('./forOwn'),
    isFunction = require('./isFunction');

/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
    arrayClass = '[object Array]',
    objectClass = '[object Object]',
    stringClass = '[object String]';

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/**
 * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
 * length of `0` and objects with no own enumerable properties are considered
 * "empty".
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Array|Object|string} value The value to inspect.
 * @returns {boolean} Returns `true` if the `value` is empty, else `false`.
 * @example
 *
 * _.isEmpty([1, 2, 3]);
 * // => false
 *
 * _.isEmpty({});
 * // => true
 *
 * _.isEmpty('');
 * // => true
 */
function isEmpty(value) {
  var result = true;
  if (!value) {
    return result;
  }
  var className = toString.call(value),
      length = value.length;

  if ((className == arrayClass || className == stringClass || className == argsClass ) ||
      (className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
    return !length;
  }
  forOwn(value, function() {
    return (result = false);
  });
  return result;
}

module.exports = isEmpty;

},{"./forOwn":141,"./isFunction":154}],152:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreateCallback = require('../internals/baseCreateCallback'),
    baseIsEqual = require('../internals/baseIsEqual');

/**
 * Performs a deep comparison between two values to determine if they are
 * equivalent to each other. If a callback is provided it will be executed
 * to compare values. If the callback returns `undefined` comparisons will
 * be handled by the method instead. The callback is bound to `thisArg` and
 * invoked with two arguments; (a, b).
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} a The value to compare.
 * @param {*} b The other value to compare.
 * @param {Function} [callback] The function to customize comparing values.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'name': 'fred' };
 * var copy = { 'name': 'fred' };
 *
 * object == copy;
 * // => false
 *
 * _.isEqual(object, copy);
 * // => true
 *
 * var words = ['hello', 'goodbye'];
 * var otherWords = ['hi', 'goodbye'];
 *
 * _.isEqual(words, otherWords, function(a, b) {
 *   var reGreet = /^(?:hello|hi)$/i,
 *       aGreet = _.isString(a) && reGreet.test(a),
 *       bGreet = _.isString(b) && reGreet.test(b);
 *
 *   return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
 * });
 * // => true
 */
function isEqual(a, b, callback, thisArg) {
  return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2));
}

module.exports = isEqual;

},{"../internals/baseCreateCallback":92,"../internals/baseIsEqual":97}],153:[function(require,module,exports){
var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeIsFinite = global.isFinite,
    nativeIsNaN = global.isNaN;

/**
 * Checks if `value` is, or can be coerced to, a finite number.
 *
 * Note: This is not the same as native `isFinite` which will return true for
 * booleans and empty strings. See http://es5.github.io/#x15.1.2.5.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is finite, else `false`.
 * @example
 *
 * _.isFinite(-101);
 * // => true
 *
 * _.isFinite('10');
 * // => true
 *
 * _.isFinite(true);
 * // => false
 *
 * _.isFinite('');
 * // => false
 *
 * _.isFinite(Infinity);
 * // => false
 */
function isFinite(value) {
  return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
}

module.exports = isFinite;

},{}],154:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Checks if `value` is a function.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 */
function isFunction(value) {
  return typeof value == 'function';
}

module.exports = isFunction;

},{}],155:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isNumber = require('./isNumber');

/**
 * Checks if `value` is `NaN`.
 *
 * Note: This is not the same as native `isNaN` which will return `true` for
 * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`.
 * @example
 *
 * _.isNaN(NaN);
 * // => true
 *
 * _.isNaN(new Number(NaN));
 * // => true
 *
 * isNaN(undefined);
 * // => true
 *
 * _.isNaN(undefined);
 * // => false
 */
function isNaN(value) {
  // `NaN` as a primitive is the only value that is not equal to itself
  // (perform the [[Class]] check first to avoid errors with some host objects in IE)
  return isNumber(value) && value != +value;
}

module.exports = isNaN;

},{"./isNumber":157}],156:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Checks if `value` is `null`.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is `null`, else `false`.
 * @example
 *
 * _.isNull(null);
 * // => true
 *
 * _.isNull(undefined);
 * // => false
 */
function isNull(value) {
  return value === null;
}

module.exports = isNull;

},{}],157:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** `Object#toString` result shortcuts */
var numberClass = '[object Number]';

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/**
 * Checks if `value` is a number.
 *
 * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is a number, else `false`.
 * @example
 *
 * _.isNumber(8.4 * 5);
 * // => true
 */
function isNumber(value) {
  return typeof value == 'number' ||
    value && typeof value == 'object' && toString.call(value) == numberClass || false;
}

module.exports = isNumber;

},{}],158:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var objectTypes = require('../internals/objectTypes');

/**
 * Checks if `value` is the language type of Object.
 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(1);
 * // => false
 */
function isObject(value) {
  // check if the value is the ECMAScript language type of Object
  // http://es5.github.io/#x8
  // and avoid a V8 bug
  // http://code.google.com/p/v8/issues/detail?id=2291
  return !!(value && objectTypes[typeof value]);
}

module.exports = isObject;

},{"../internals/objectTypes":120}],159:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isNative = require('../internals/isNative'),
    shimIsPlainObject = require('../internals/shimIsPlainObject');

/** `Object#toString` result shortcuts */
var objectClass = '[object Object]';

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/** Native method shortcuts */
var getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf;

/**
 * Checks if `value` is an object created by the `Object` constructor.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
 * @example
 *
 * function Shape() {
 *   this.x = 0;
 *   this.y = 0;
 * }
 *
 * _.isPlainObject(new Shape);
 * // => false
 *
 * _.isPlainObject([1, 2, 3]);
 * // => false
 *
 * _.isPlainObject({ 'x': 0, 'y': 0 });
 * // => true
 */
var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
  if (!(value && toString.call(value) == objectClass)) {
    return false;
  }
  var valueOf = value.valueOf,
      objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);

  return objProto
    ? (value == objProto || getPrototypeOf(value) == objProto)
    : shimIsPlainObject(value);
};

module.exports = isPlainObject;

},{"../internals/isNative":114,"../internals/shimIsPlainObject":127}],160:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** `Object#toString` result shortcuts */
var regexpClass = '[object RegExp]';

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/**
 * Checks if `value` is a regular expression.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`.
 * @example
 *
 * _.isRegExp(/fred/);
 * // => true
 */
function isRegExp(value) {
  return value && typeof value == 'object' && toString.call(value) == regexpClass || false;
}

module.exports = isRegExp;

},{}],161:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** `Object#toString` result shortcuts */
var stringClass = '[object String]';

/** Used for native method references */
var objectProto = Object.prototype;

/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;

/**
 * Checks if `value` is a string.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is a string, else `false`.
 * @example
 *
 * _.isString('fred');
 * // => true
 */
function isString(value) {
  return typeof value == 'string' ||
    value && typeof value == 'object' && toString.call(value) == stringClass || false;
}

module.exports = isString;

},{}],162:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Checks if `value` is `undefined`.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`.
 * @example
 *
 * _.isUndefined(void 0);
 * // => true
 */
function isUndefined(value) {
  return typeof value == 'undefined';
}

module.exports = isUndefined;

},{}],163:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isNative = require('../internals/isNative'),
    isObject = require('./isObject'),
    shimKeys = require('../internals/shimKeys');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys;

/**
 * Creates an array composed of the own enumerable property names of an object.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The object to inspect.
 * @returns {Array} Returns an array of property names.
 * @example
 *
 * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
 * // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
 */
var keys = !nativeKeys ? shimKeys : function(object) {
  if (!isObject(object)) {
    return [];
  }
  return nativeKeys(object);
};

module.exports = keys;

},{"../internals/isNative":114,"../internals/shimKeys":128,"./isObject":158}],164:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var createCallback = require('../functions/createCallback'),
    forOwn = require('./forOwn');

/**
 * Creates an object with the same keys as `object` and values generated by
 * running each own enumerable property of `object` through the callback.
 * The callback is bound to `thisArg` and invoked with three arguments;
 * (value, key, object).
 *
 * If a property name is provided for `callback` the created "_.pluck" style
 * callback will return the property value of the given element.
 *
 * If an object is provided for `callback` the created "_.where" style callback
 * will return `true` for elements that have the properties of the given object,
 * else `false`.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The object to iterate over.
 * @param {Function|Object|string} [callback=identity] The function called
 *  per iteration. If a property name or object is provided it will be used
 *  to create a "_.pluck" or "_.where" style callback, respectively.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array} Returns a new object with values of the results of each `callback` execution.
 * @example
 *
 * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
 * // => { 'a': 3, 'b': 6, 'c': 9 }
 *
 * var characters = {
 *   'fred': { 'name': 'fred', 'age': 40 },
 *   'pebbles': { 'name': 'pebbles', 'age': 1 }
 * };
 *
 * // using "_.pluck" callback shorthand
 * _.mapValues(characters, 'age');
 * // => { 'fred': 40, 'pebbles': 1 }
 */
function mapValues(object, callback, thisArg) {
  var result = {};
  callback = createCallback(callback, thisArg, 3);

  forOwn(object, function(value, key, object) {
    result[key] = callback(value, key, object);
  });
  return result;
}

module.exports = mapValues;

},{"../functions/createCallback":76,"./forOwn":141}],165:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreateCallback = require('../internals/baseCreateCallback'),
    baseMerge = require('../internals/baseMerge'),
    getArray = require('../internals/getArray'),
    isObject = require('./isObject'),
    releaseArray = require('../internals/releaseArray'),
    slice = require('../internals/slice');

/**
 * Recursively merges own enumerable properties of the source object(s), that
 * don't resolve to `undefined` into the destination object. Subsequent sources
 * will overwrite property assignments of previous sources. If a callback is
 * provided it will be executed to produce the merged values of the destination
 * and source properties. If the callback returns `undefined` merging will
 * be handled by the method instead. The callback is bound to `thisArg` and
 * invoked with two arguments; (objectValue, sourceValue).
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The destination object.
 * @param {...Object} [source] The source objects.
 * @param {Function} [callback] The function to customize merging properties.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Object} Returns the destination object.
 * @example
 *
 * var names = {
 *   'characters': [
 *     { 'name': 'barney' },
 *     { 'name': 'fred' }
 *   ]
 * };
 *
 * var ages = {
 *   'characters': [
 *     { 'age': 36 },
 *     { 'age': 40 }
 *   ]
 * };
 *
 * _.merge(names, ages);
 * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }
 *
 * var food = {
 *   'fruits': ['apple'],
 *   'vegetables': ['beet']
 * };
 *
 * var otherFood = {
 *   'fruits': ['banana'],
 *   'vegetables': ['carrot']
 * };
 *
 * _.merge(food, otherFood, function(a, b) {
 *   return _.isArray(a) ? a.concat(b) : undefined;
 * });
 * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
 */
function merge(object) {
  var args = arguments,
      length = 2;

  if (!isObject(object)) {
    return object;
  }
  // allows working with `_.reduce` and `_.reduceRight` without using
  // their `index` and `collection` arguments
  if (typeof args[2] != 'number') {
    length = args.length;
  }
  if (length > 3 && typeof args[length - 2] == 'function') {
    var callback = baseCreateCallback(args[--length - 1], args[length--], 2);
  } else if (length > 2 && typeof args[length - 1] == 'function') {
    callback = args[--length];
  }
  var sources = slice(arguments, 1, length),
      index = -1,
      stackA = getArray(),
      stackB = getArray();

  while (++index < length) {
    baseMerge(object, sources[index], callback, stackA, stackB);
  }
  releaseArray(stackA);
  releaseArray(stackB);
  return object;
}

module.exports = merge;

},{"../internals/baseCreateCallback":92,"../internals/baseMerge":98,"../internals/getArray":110,"../internals/releaseArray":124,"../internals/slice":129,"./isObject":158}],166:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseDifference = require('../internals/baseDifference'),
    baseFlatten = require('../internals/baseFlatten'),
    createCallback = require('../functions/createCallback'),
    forIn = require('./forIn');

/**
 * Creates a shallow clone of `object` excluding the specified properties.
 * Property names may be specified as individual arguments or as arrays of
 * property names. If a callback is provided it will be executed for each
 * property of `object` omitting the properties the callback returns truey
 * for. The callback is bound to `thisArg` and invoked with three arguments;
 * (value, key, object).
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The source object.
 * @param {Function|...string|string[]} [callback] The properties to omit or the
 *  function called per iteration.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Object} Returns an object without the omitted properties.
 * @example
 *
 * _.omit({ 'name': 'fred', 'age': 40 }, 'age');
 * // => { 'name': 'fred' }
 *
 * _.omit({ 'name': 'fred', 'age': 40 }, function(value) {
 *   return typeof value == 'number';
 * });
 * // => { 'name': 'fred' }
 */
function omit(object, callback, thisArg) {
  var result = {};
  if (typeof callback != 'function') {
    var props = [];
    forIn(object, function(value, key) {
      props.push(key);
    });
    props = baseDifference(props, baseFlatten(arguments, true, false, 1));

    var index = -1,
        length = props.length;

    while (++index < length) {
      var key = props[index];
      result[key] = object[key];
    }
  } else {
    callback = createCallback(callback, thisArg, 3);
    forIn(object, function(value, key, object) {
      if (!callback(value, key, object)) {
        result[key] = value;
      }
    });
  }
  return result;
}

module.exports = omit;

},{"../functions/createCallback":76,"../internals/baseDifference":94,"../internals/baseFlatten":95,"./forIn":139}],167:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var keys = require('./keys');

/**
 * Creates a two dimensional array of an object's key-value pairs,
 * i.e. `[[key1, value1], [key2, value2]]`.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The object to inspect.
 * @returns {Array} Returns new array of key-value pairs.
 * @example
 *
 * _.pairs({ 'barney': 36, 'fred': 40 });
 * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments)
 */
function pairs(object) {
  var index = -1,
      props = keys(object),
      length = props.length,
      result = Array(length);

  while (++index < length) {
    var key = props[index];
    result[index] = [key, object[key]];
  }
  return result;
}

module.exports = pairs;

},{"./keys":163}],168:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseFlatten = require('../internals/baseFlatten'),
    createCallback = require('../functions/createCallback'),
    forIn = require('./forIn'),
    isObject = require('./isObject');

/**
 * Creates a shallow clone of `object` composed of the specified properties.
 * Property names may be specified as individual arguments or as arrays of
 * property names. If a callback is provided it will be executed for each
 * property of `object` picking the properties the callback returns truey
 * for. The callback is bound to `thisArg` and invoked with three arguments;
 * (value, key, object).
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The source object.
 * @param {Function|...string|string[]} [callback] The function called per
 *  iteration or property names to pick, specified as individual property
 *  names or arrays of property names.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Object} Returns an object composed of the picked properties.
 * @example
 *
 * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name');
 * // => { 'name': 'fred' }
 *
 * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) {
 *   return key.charAt(0) != '_';
 * });
 * // => { 'name': 'fred' }
 */
function pick(object, callback, thisArg) {
  var result = {};
  if (typeof callback != 'function') {
    var index = -1,
        props = baseFlatten(arguments, true, false, 1),
        length = isObject(object) ? props.length : 0;

    while (++index < length) {
      var key = props[index];
      if (key in object) {
        result[key] = object[key];
      }
    }
  } else {
    callback = createCallback(callback, thisArg, 3);
    forIn(object, function(value, key, object) {
      if (callback(value, key, object)) {
        result[key] = value;
      }
    });
  }
  return result;
}

module.exports = pick;

},{"../functions/createCallback":76,"../internals/baseFlatten":95,"./forIn":139,"./isObject":158}],169:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreate = require('../internals/baseCreate'),
    createCallback = require('../functions/createCallback'),
    forEach = require('../collections/forEach'),
    forOwn = require('./forOwn'),
    isArray = require('./isArray');

/**
 * An alternative to `_.reduce` this method transforms `object` to a new
 * `accumulator` object which is the result of running each of its own
 * enumerable properties through a callback, with each callback execution
 * potentially mutating the `accumulator` object. The callback is bound to
 * `thisArg` and invoked with four arguments; (accumulator, value, key, object).
 * Callbacks may exit iteration early by explicitly returning `false`.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Array|Object} object The object to iterate over.
 * @param {Function} [callback=identity] The function called per iteration.
 * @param {*} [accumulator] The custom accumulator value.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {*} Returns the accumulated value.
 * @example
 *
 * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) {
 *   num *= num;
 *   if (num % 2) {
 *     return result.push(num) < 3;
 *   }
 * });
 * // => [1, 9, 25]
 *
 * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
 *   result[key] = num * 3;
 * });
 * // => { 'a': 3, 'b': 6, 'c': 9 }
 */
function transform(object, callback, accumulator, thisArg) {
  var isArr = isArray(object);
  if (accumulator == null) {
    if (isArr) {
      accumulator = [];
    } else {
      var ctor = object && object.constructor,
          proto = ctor && ctor.prototype;

      accumulator = baseCreate(proto);
    }
  }
  if (callback) {
    callback = createCallback(callback, thisArg, 4);
    (isArr ? forEach : forOwn)(object, function(value, index, object) {
      return callback(accumulator, value, index, object);
    });
  }
  return accumulator;
}

module.exports = transform;

},{"../collections/forEach":51,"../functions/createCallback":76,"../internals/baseCreate":91,"./forOwn":141,"./isArray":147}],170:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var keys = require('./keys');

/**
 * Creates an array composed of the own enumerable property values of `object`.
 *
 * @static
 * @memberOf _
 * @category Objects
 * @param {Object} object The object to inspect.
 * @returns {Array} Returns an array of property values.
 * @example
 *
 * _.values({ 'one': 1, 'two': 2, 'three': 3 });
 * // => [1, 2, 3] (property order is not guaranteed across environments)
 */
function values(object) {
  var index = -1,
      props = keys(object),
      length = props.length,
      result = Array(length);

  while (++index < length) {
    result[index] = object[props[index]];
  }
  return result;
}

module.exports = values;

},{"./keys":163}],171:[function(require,module,exports){
var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isNative = require('./internals/isNative');

/** Used to detect functions containing a `this` reference */
var reThis = /\bthis\b/;

/**
 * An object used to flag environments features.
 *
 * @static
 * @memberOf _
 * @type Object
 */
var support = {};

/**
 * Detect if functions can be decompiled by `Function#toString`
 * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
 *
 * @memberOf _.support
 * @type boolean
 */
support.funcDecomp = !isNative(global.WinRTError) && reThis.test(function() { return this; });

/**
 * Detect if `Function#name` is supported (all but IE).
 *
 * @memberOf _.support
 * @type boolean
 */
support.funcNames = typeof Function.name == 'string';

module.exports = support;

},{"./internals/isNative":114}],172:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

module.exports = {
  'constant': require('./utilities/constant'),
  'createCallback': require('./functions/createCallback'),
  'escape': require('./utilities/escape'),
  'identity': require('./utilities/identity'),
  'mixin': require('./utilities/mixin'),
  'noConflict': require('./utilities/noConflict'),
  'noop': require('./utilities/noop'),
  'now': require('./utilities/now'),
  'parseInt': require('./utilities/parseInt'),
  'property': require('./utilities/property'),
  'random': require('./utilities/random'),
  'result': require('./utilities/result'),
  'template': require('./utilities/template'),
  'templateSettings': require('./utilities/templateSettings'),
  'times': require('./utilities/times'),
  'unescape': require('./utilities/unescape'),
  'uniqueId': require('./utilities/uniqueId')
};

},{"./functions/createCallback":76,"./utilities/constant":173,"./utilities/escape":174,"./utilities/identity":175,"./utilities/mixin":176,"./utilities/noConflict":177,"./utilities/noop":178,"./utilities/now":179,"./utilities/parseInt":180,"./utilities/property":181,"./utilities/random":182,"./utilities/result":183,"./utilities/template":184,"./utilities/templateSettings":185,"./utilities/times":186,"./utilities/unescape":187,"./utilities/uniqueId":188}],173:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Creates a function that returns `value`.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {*} value The value to return from the new function.
 * @returns {Function} Returns the new function.
 * @example
 *
 * var object = { 'name': 'fred' };
 * var getter = _.constant(object);
 * getter() === object;
 * // => true
 */
function constant(value) {
  return function() {
    return value;
  };
}

module.exports = constant;

},{}],174:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var escapeHtmlChar = require('../internals/escapeHtmlChar'),
    keys = require('../objects/keys'),
    reUnescapedHtml = require('../internals/reUnescapedHtml');

/**
 * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
 * corresponding HTML entities.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {string} string The string to escape.
 * @returns {string} Returns the escaped string.
 * @example
 *
 * _.escape('Fred, Wilma, & Pebbles');
 * // => 'Fred, Wilma, &amp; Pebbles'
 */
function escape(string) {
  return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar);
}

module.exports = escape;

},{"../internals/escapeHtmlChar":108,"../internals/reUnescapedHtml":123,"../objects/keys":163}],175:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * This method returns the first argument provided to it.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {*} value Any value.
 * @returns {*} Returns `value`.
 * @example
 *
 * var object = { 'name': 'fred' };
 * _.identity(object) === object;
 * // => true
 */
function identity(value) {
  return value;
}

module.exports = identity;

},{}],176:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var forEach = require('../collections/forEach'),
    functions = require('../objects/functions'),
    isFunction = require('../objects/isFunction'),
    isObject = require('../objects/isObject');

/**
 * Used for `Array` method references.
 *
 * Normally `Array.prototype` would suffice, however, using an array literal
 * avoids issues in Narwhal.
 */
var arrayRef = [];

/** Native method shortcuts */
var push = arrayRef.push;

/**
 * Adds function properties of a source object to the destination object.
 * If `object` is a function methods will be added to its prototype as well.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {Function|Object} [object=lodash] object The destination object.
 * @param {Object} source The object of functions to add.
 * @param {Object} [options] The options object.
 * @param {boolean} [options.chain=true] Specify whether the functions added are chainable.
 * @example
 *
 * function capitalize(string) {
 *   return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
 * }
 *
 * _.mixin({ 'capitalize': capitalize });
 * _.capitalize('fred');
 * // => 'Fred'
 *
 * _('fred').capitalize().value();
 * // => 'Fred'
 *
 * _.mixin({ 'capitalize': capitalize }, { 'chain': false });
 * _('fred').capitalize();
 * // => 'Fred'
 */
function mixin(object, source, options) {
  var chain = true,
      methodNames = source && functions(source);

  if (options === false) {
    chain = false;
  } else if (isObject(options) && 'chain' in options) {
    chain = options.chain;
  }
  var ctor = object,
      isFunc = isFunction(ctor);

  forEach(methodNames, function(methodName) {
    var func = object[methodName] = source[methodName];
    if (isFunc) {
      ctor.prototype[methodName] = function() {
        var chainAll = this.__chain__,
            value = this.__wrapped__,
            args = [value];

        push.apply(args, arguments);
        var result = func.apply(object, args);
        if (chain || chainAll) {
          if (value === result && isObject(result)) {
            return this;
          }
          result = new ctor(result);
          result.__chain__ = chainAll;
        }
        return result;
      };
    }
  });
}

module.exports = mixin;

},{"../collections/forEach":51,"../objects/functions":143,"../objects/isFunction":154,"../objects/isObject":158}],177:[function(require,module,exports){
var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used to restore the original `_` reference in `noConflict` */
var oldDash = global._;

/**
 * Reverts the '_' variable to its previous value and returns a reference to
 * the `lodash` function.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @returns {Function} Returns the `lodash` function.
 * @example
 *
 * var lodash = _.noConflict();
 */
function noConflict() {
  global._ = oldDash;
  return this;
}

module.exports = noConflict;

},{}],178:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * A no-operation function.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @example
 *
 * var object = { 'name': 'fred' };
 * _.noop(object) === undefined;
 * // => true
 */
function noop() {
  // no operation performed
}

module.exports = noop;

},{}],179:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isNative = require('../internals/isNative');

/**
 * Gets the number of milliseconds that have elapsed since the Unix epoch
 * (1 January 1970 00:00:00 UTC).
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @example
 *
 * var stamp = _.now();
 * _.defer(function() { console.log(_.now() - stamp); });
 * // => logs the number of milliseconds it took for the deferred function to be called
 */
var now = isNative(now = Date.now) && now || function() {
  return new Date().getTime();
};

module.exports = now;

},{"../internals/isNative":114}],180:[function(require,module,exports){
var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isString = require('../objects/isString');

/** Used to detect and test whitespace */
var whitespace = (
  // whitespace
  ' \t\x0B\f\xA0\ufeff' +

  // line terminators
  '\n\r\u2028\u2029' +

  // unicode category "Zs" space separators
  '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
);

/** Used to match leading whitespace and zeros to be removed */
var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeParseInt = global.parseInt;

/**
 * Converts the given value into an integer of the specified radix.
 * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the
 * `value` is a hexadecimal, in which case a `radix` of `16` is used.
 *
 * Note: This method avoids differences in native ES3 and ES5 `parseInt`
 * implementations. See http://es5.github.io/#E.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {string} value The value to parse.
 * @param {number} [radix] The radix used to interpret the value to parse.
 * @returns {number} Returns the new integer value.
 * @example
 *
 * _.parseInt('08');
 * // => 8
 */
var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) {
  // Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt`
  return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0);
};

module.exports = parseInt;

},{"../objects/isString":161}],181:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/**
 * Creates a "_.pluck" style function, which returns the `key` value of a
 * given object.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {string} key The name of the property to retrieve.
 * @returns {Function} Returns the new function.
 * @example
 *
 * var characters = [
 *   { 'name': 'fred',   'age': 40 },
 *   { 'name': 'barney', 'age': 36 }
 * ];
 *
 * var getName = _.property('name');
 *
 * _.map(characters, getName);
 * // => ['barney', 'fred']
 *
 * _.sortBy(characters, getName);
 * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred',   'age': 40 }]
 */
function property(key) {
  return function(object) {
    return object[key];
  };
}

module.exports = property;

},{}],182:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseRandom = require('../internals/baseRandom');

/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMin = Math.min,
    nativeRandom = Math.random;

/**
 * Produces a random number between `min` and `max` (inclusive). If only one
 * argument is provided a number between `0` and the given number will be
 * returned. If `floating` is truey or either `min` or `max` are floats a
 * floating-point number will be returned instead of an integer.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {number} [min=0] The minimum possible value.
 * @param {number} [max=1] The maximum possible value.
 * @param {boolean} [floating=false] Specify returning a floating-point number.
 * @returns {number} Returns a random number.
 * @example
 *
 * _.random(0, 5);
 * // => an integer between 0 and 5
 *
 * _.random(5);
 * // => also an integer between 0 and 5
 *
 * _.random(5, true);
 * // => a floating-point number between 0 and 5
 *
 * _.random(1.2, 5.2);
 * // => a floating-point number between 1.2 and 5.2
 */
function random(min, max, floating) {
  var noMin = min == null,
      noMax = max == null;

  if (floating == null) {
    if (typeof min == 'boolean' && noMax) {
      floating = min;
      min = 1;
    }
    else if (!noMax && typeof max == 'boolean') {
      floating = max;
      noMax = true;
    }
  }
  if (noMin && noMax) {
    max = 1;
  }
  min = +min || 0;
  if (noMax) {
    max = min;
    min = 0;
  } else {
    max = +max || 0;
  }
  if (floating || min % 1 || max % 1) {
    var rand = nativeRandom();
    return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max);
  }
  return baseRandom(min, max);
}

module.exports = random;

},{"../internals/baseRandom":99}],183:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var isFunction = require('../objects/isFunction');

/**
 * Resolves the value of property `key` on `object`. If `key` is a function
 * it will be invoked with the `this` binding of `object` and its result returned,
 * else the property value is returned. If `object` is falsey then `undefined`
 * is returned.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {Object} object The object to inspect.
 * @param {string} key The name of the property to resolve.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = {
 *   'cheese': 'crumpets',
 *   'stuff': function() {
 *     return 'nonsense';
 *   }
 * };
 *
 * _.result(object, 'cheese');
 * // => 'crumpets'
 *
 * _.result(object, 'stuff');
 * // => 'nonsense'
 */
function result(object, key) {
  if (object) {
    var value = object[key];
    return isFunction(value) ? object[key]() : value;
  }
}

module.exports = result;

},{"../objects/isFunction":154}],184:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var defaults = require('../objects/defaults'),
    escape = require('./escape'),
    escapeStringChar = require('../internals/escapeStringChar'),
    keys = require('../objects/keys'),
    reInterpolate = require('../internals/reInterpolate'),
    templateSettings = require('./templateSettings'),
    values = require('../objects/values');

/** Used to match empty string literals in compiled template source */
var reEmptyStringLeading = /\b__p \+= '';/g,
    reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
    reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;

/**
 * Used to match ES6 template delimiters
 * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals
 */
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;

/** Used to ensure capturing order of template delimiters */
var reNoMatch = /($^)/;

/** Used to match unescaped characters in compiled string literals */
var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;

/**
 * A micro-templating method that handles arbitrary delimiters, preserves
 * whitespace, and correctly escapes quotes within interpolated code.
 *
 * Note: In the development build, `_.template` utilizes sourceURLs for easier
 * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
 *
 * For more information on precompiling templates see:
 * http://lodash.com/custom-builds
 *
 * For more information on Chrome extension sandboxes see:
 * http://developer.chrome.com/stable/extensions/sandboxingEval.html
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {string} text The template text.
 * @param {Object} data The data object used to populate the text.
 * @param {Object} [options] The options object.
 * @param {RegExp} [options.escape] The "escape" delimiter.
 * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
 * @param {Object} [options.imports] An object to import into the template as local variables.
 * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
 * @param {string} [sourceURL] The sourceURL of the template's compiled source.
 * @param {string} [variable] The data object variable name.
 * @returns {Function|string} Returns a compiled function when no `data` object
 *  is given, else it returns the interpolated text.
 * @example
 *
 * // using the "interpolate" delimiter to create a compiled template
 * var compiled = _.template('hello <%= name %>');
 * compiled({ 'name': 'fred' });
 * // => 'hello fred'
 *
 * // using the "escape" delimiter to escape HTML in data property values
 * _.template('<b><%- value %></b>', { 'value': '<script>' });
 * // => '<b>&lt;script&gt;</b>'
 *
 * // using the "evaluate" delimiter to generate HTML
 * var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
 * _.template(list, { 'people': ['fred', 'barney'] });
 * // => '<li>fred</li><li>barney</li>'
 *
 * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
 * _.template('hello ${ name }', { 'name': 'pebbles' });
 * // => 'hello pebbles'
 *
 * // using the internal `print` function in "evaluate" delimiters
 * _.template('<% print("hello " + name); %>!', { 'name': 'barney' });
 * // => 'hello barney!'
 *
 * // using a custom template delimiters
 * _.templateSettings = {
 *   'interpolate': /{{([\s\S]+?)}}/g
 * };
 *
 * _.template('hello {{ name }}!', { 'name': 'mustache' });
 * // => 'hello mustache!'
 *
 * // using the `imports` option to import jQuery
 * var list = '<% jq.each(people, function(name) { %><li><%- name %></li><% }); %>';
 * _.template(list, { 'people': ['fred', 'barney'] }, { 'imports': { 'jq': jQuery } });
 * // => '<li>fred</li><li>barney</li>'
 *
 * // using the `sourceURL` option to specify a custom sourceURL for the template
 * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
 * compiled(data);
 * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
 *
 * // using the `variable` option to ensure a with-statement isn't used in the compiled template
 * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });
 * compiled.source;
 * // => function(data) {
 *   var __t, __p = '', __e = _.escape;
 *   __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
 *   return __p;
 * }
 *
 * // using the `source` property to inline compiled templates for meaningful
 * // line numbers in error messages and a stack trace
 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
 *   var JST = {\
 *     "main": ' + _.template(mainText).source + '\
 *   };\
 * ');
 */
function template(text, data, options) {
  // based on John Resig's `tmpl` implementation
  // http://ejohn.org/blog/javascript-micro-templating/
  // and Laura Doktorova's doT.js
  // https://github.com/olado/doT
  var settings = templateSettings.imports._.templateSettings || templateSettings;
  text = String(text || '');

  // avoid missing dependencies when `iteratorTemplate` is not defined
  options = defaults({}, options, settings);

  var imports = defaults({}, options.imports, settings.imports),
      importsKeys = keys(imports),
      importsValues = values(imports);

  var isEvaluating,
      index = 0,
      interpolate = options.interpolate || reNoMatch,
      source = "__p += '";

  // compile the regexp to match each delimiter
  var reDelimiters = RegExp(
    (options.escape || reNoMatch).source + '|' +
    interpolate.source + '|' +
    (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
    (options.evaluate || reNoMatch).source + '|$'
  , 'g');

  text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
    interpolateValue || (interpolateValue = esTemplateValue);

    // escape characters that cannot be included in string literals
    source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);

    // replace delimiters with snippets
    if (escapeValue) {
      source += "' +\n__e(" + escapeValue + ") +\n'";
    }
    if (evaluateValue) {
      isEvaluating = true;
      source += "';\n" + evaluateValue + ";\n__p += '";
    }
    if (interpolateValue) {
      source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
    }
    index = offset + match.length;

    // the JS engine embedded in Adobe products requires returning the `match`
    // string in order to produce the correct `offset` value
    return match;
  });

  source += "';\n";

  // if `variable` is not specified, wrap a with-statement around the generated
  // code to add the data object to the top of the scope chain
  var variable = options.variable,
      hasVariable = variable;

  if (!hasVariable) {
    variable = 'obj';
    source = 'with (' + variable + ') {\n' + source + '\n}\n';
  }
  // cleanup code by stripping empty strings
  source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
    .replace(reEmptyStringMiddle, '$1')
    .replace(reEmptyStringTrailing, '$1;');

  // frame code as the function body
  source = 'function(' + variable + ') {\n' +
    (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
    "var __t, __p = '', __e = _.escape" +
    (isEvaluating
      ? ', __j = Array.prototype.join;\n' +
        "function print() { __p += __j.call(arguments, '') }\n"
      : ';\n'
    ) +
    source +
    'return __p\n}';

  try {
    var result = Function(importsKeys, 'return ' + source ).apply(undefined, importsValues);
  } catch(e) {
    e.source = source;
    throw e;
  }
  if (data) {
    return result(data);
  }
  // provide the compiled function's source by its `toString` method, in
  // supported environments, or the `source` property as a convenience for
  // inlining compiled templates during the build process
  result.source = source;
  return result;
}

module.exports = template;

},{"../internals/escapeStringChar":109,"../internals/reInterpolate":122,"../objects/defaults":136,"../objects/keys":163,"../objects/values":170,"./escape":174,"./templateSettings":185}],185:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var escape = require('./escape'),
    reInterpolate = require('../internals/reInterpolate');

/**
 * By default, the template delimiters used by Lo-Dash are similar to those in
 * embedded Ruby (ERB). Change the following template settings to use alternative
 * delimiters.
 *
 * @static
 * @memberOf _
 * @type Object
 */
var templateSettings = {

  /**
   * Used to detect `data` property values to be HTML-escaped.
   *
   * @memberOf _.templateSettings
   * @type RegExp
   */
  'escape': /<%-([\s\S]+?)%>/g,

  /**
   * Used to detect code to be evaluated.
   *
   * @memberOf _.templateSettings
   * @type RegExp
   */
  'evaluate': /<%([\s\S]+?)%>/g,

  /**
   * Used to detect `data` property values to inject.
   *
   * @memberOf _.templateSettings
   * @type RegExp
   */
  'interpolate': reInterpolate,

  /**
   * Used to reference the data object in the template text.
   *
   * @memberOf _.templateSettings
   * @type string
   */
  'variable': '',

  /**
   * Used to import variables into the compiled template.
   *
   * @memberOf _.templateSettings
   * @type Object
   */
  'imports': {

    /**
     * A reference to the `lodash` function.
     *
     * @memberOf _.templateSettings.imports
     * @type Function
     */
    '_': { 'escape': escape }
  }
};

module.exports = templateSettings;

},{"../internals/reInterpolate":122,"./escape":174}],186:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var baseCreateCallback = require('../internals/baseCreateCallback');

/**
 * Executes the callback `n` times, returning an array of the results
 * of each callback execution. The callback is bound to `thisArg` and invoked
 * with one argument; (index).
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {number} n The number of times to execute the callback.
 * @param {Function} callback The function called per iteration.
 * @param {*} [thisArg] The `this` binding of `callback`.
 * @returns {Array} Returns an array of the results of each `callback` execution.
 * @example
 *
 * var diceRolls = _.times(3, _.partial(_.random, 1, 6));
 * // => [3, 6, 4]
 *
 * _.times(3, function(n) { mage.castSpell(n); });
 * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
 *
 * _.times(3, function(n) { this.cast(n); }, mage);
 * // => also calls `mage.castSpell(n)` three times
 */
function times(n, callback, thisArg) {
  n = (n = +n) > -1 ? n : 0;
  var index = -1,
      result = Array(n);

  callback = baseCreateCallback(callback, thisArg, 1);
  while (++index < n) {
    result[index] = callback(index);
  }
  return result;
}

module.exports = times;

},{"../internals/baseCreateCallback":92}],187:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */
var keys = require('../objects/keys'),
    reEscapedHtml = require('../internals/reEscapedHtml'),
    unescapeHtmlChar = require('../internals/unescapeHtmlChar');

/**
 * The inverse of `_.escape` this method converts the HTML entities
 * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their
 * corresponding characters.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {string} string The string to unescape.
 * @returns {string} Returns the unescaped string.
 * @example
 *
 * _.unescape('Fred, Barney &amp; Pebbles');
 * // => 'Fred, Barney & Pebbles'
 */
function unescape(string) {
  return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar);
}

module.exports = unescape;

},{"../internals/reEscapedHtml":121,"../internals/unescapeHtmlChar":130,"../objects/keys":163}],188:[function(require,module,exports){
/**
 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
 * Build: `lodash modularize modern exports="node" -o ./modern/`
 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <http://lodash.com/license>
 */

/** Used to generate unique IDs */
var idCounter = 0;

/**
 * Generates a unique ID. If `prefix` is provided the ID will be appended to it.
 *
 * @static
 * @memberOf _
 * @category Utilities
 * @param {string} [prefix] The value to prefix the ID with.
 * @returns {string} Returns the unique ID.
 * @example
 *
 * _.uniqueId('contact_');
 * // => 'contact_104'
 *
 * _.uniqueId();
 * // => '105'
 */
function uniqueId(prefix) {
  var id = ++idCounter;
  return String(prefix == null ? '' : prefix) + id;
}

module.exports = uniqueId;

},{}],189:[function(require,module,exports){
var process=require("__browserify_process");/**
 * Wrapper for the elasticsearch.js client, which will register the client constructor
 * as a factory within angular that can be easily injected with Angular's awesome DI.
 *
 * It will also instruct the client to use Angular's $http service for it's ajax requests
 */
var AngularConnector = require('./lib/connectors/angular');
var Client = require('./lib/client');

process.angular_build = true;

/* global angular */
angular.module('elasticsearch', [])
  .factory('esFactory', ['$http', '$q', function ($http, $q) {

    var factory = function (config) {
      config = config || {};
      config.connectionClass = AngularConnector;
      config.$http = $http;
      config.defer = function () {
        return $q.defer();
      };
      return new Client(config);
    };

    factory.errors = require('./lib/errors');
    factory.ConnectionPool = require('./lib/connection_pool');
    factory.Transport = require('./lib/transport');

    return factory;
  }]);

},{"./lib/client":194,"./lib/connection_pool":197,"./lib/connectors/angular":198,"./lib/errors":200,"./lib/transport":211,"__browserify_process":13}],190:[function(require,module,exports){
/* jshint maxlen: false */

var ca = require('../client_action');
var api = module.exports = {};

api._namespaces = ['cluster', 'indices'];

/**
 * Perform a [bulk](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/docs-bulk.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Explicitely set the replication type
 * @param {String} params.type - Default document type for items which don't provide one
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {String} params.index - Default index for items which don't provide one
 */
api.bulk = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    type: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_bulk',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_bulk',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_bulk'
    }
  ],
  needBody: true,
  bulkBody: true,
  method: 'POST'
});

/**
 * Perform a [clearScroll](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/search-request-scroll.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.scrollId - A comma-separated list of scroll IDs to clear
 */
api.clearScroll = ca({
  url: {
    fmt: '/_search/scroll/<%=scrollId%>',
    req: {
      scrollId: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

api.cluster = function ClusterNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [cluster.getSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/cluster-update-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 */
api.cluster.prototype.getSettings = ca({
  url: {
    fmt: '/_cluster/settings'
  }
});

/**
 * Perform a [cluster.health](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/cluster-health.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.level=cluster] - Specify the level of detail for returned information
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Number} params.waitForActiveShards - Wait until the specified number of shards is active
 * @param {String} params.waitForNodes - Wait until the specified number of nodes is available
 * @param {Number} params.waitForRelocatingShards - Wait until the specified number of relocating shards is finished
 * @param {String} params.waitForStatus - Wait until cluster is in a specific state
 * @param {String} params.index - Limit the information returned to a specific index
 */
api.cluster.prototype.health = ca({
  params: {
    level: {
      type: 'enum',
      'default': 'cluster',
      options: [
        'cluster',
        'indices',
        'shards'
      ]
    },
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    timeout: {
      type: 'time'
    },
    waitForActiveShards: {
      type: 'number',
      name: 'wait_for_active_shards'
    },
    waitForNodes: {
      type: 'string',
      name: 'wait_for_nodes'
    },
    waitForRelocatingShards: {
      type: 'number',
      name: 'wait_for_relocating_shards'
    },
    waitForStatus: {
      type: 'enum',
      'default': null,
      options: [
        'green',
        'yellow',
        'red'
      ],
      name: 'wait_for_status'
    }
  },
  urls: [
    {
      fmt: '/_cluster/health/<%=index%>',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_cluster/health'
    }
  ]
});

/**
 * Perform a [cluster.nodeHotThreads](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/cluster-nodes-hot-threads.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.interval - The interval for the second sampling of threads
 * @param {Number} params.snapshots - Number of samples of thread stacktrace (default: 10)
 * @param {Number} params.threads - Specify the number of threads to provide information for (default: 3)
 * @param {String} params.type - The type to sample (default: cpu)
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
 */
api.cluster.prototype.nodeHotThreads = ca({
  params: {
    interval: {
      type: 'time'
    },
    snapshots: {
      type: 'number'
    },
    threads: {
      type: 'number'
    },
    type: {
      type: 'enum',
      options: [
        'cpu',
        'wait',
        'block'
      ]
    }
  },
  urls: [
    {
      fmt: '/_nodes/<%=nodeId%>/hotthreads',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_nodes/hotthreads'
    }
  ]
});

/**
 * Perform a [cluster.nodeInfo](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/cluster-nodes-info.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.all - Return all available information
 * @param {Boolean} params.clear - Reset the default settings
 * @param {Boolean} params.http - Return information about HTTP
 * @param {Boolean} params.jvm - Return information about the JVM
 * @param {Boolean} params.network - Return information about network
 * @param {Boolean} params.os - Return information about the operating system
 * @param {Boolean} params.plugin - Return information about plugins
 * @param {Boolean} params.process - Return information about the Elasticsearch process
 * @param {Boolean} params.settings - Return information about node settings
 * @param {Boolean} params.threadPool - Return information about the thread pool
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Boolean} params.transport - Return information about transport
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
 */
api.cluster.prototype.nodeInfo = ca({
  params: {
    all: {
      type: 'boolean'
    },
    clear: {
      type: 'boolean'
    },
    http: {
      type: 'boolean'
    },
    jvm: {
      type: 'boolean'
    },
    network: {
      type: 'boolean'
    },
    os: {
      type: 'boolean'
    },
    plugin: {
      type: 'boolean'
    },
    process: {
      type: 'boolean'
    },
    settings: {
      type: 'boolean'
    },
    threadPool: {
      type: 'boolean',
      name: 'thread_pool'
    },
    timeout: {
      type: 'time'
    },
    transport: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/_nodes/<%=nodeId%>',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_nodes'
    }
  ]
});

/**
 * Perform a [cluster.nodeShutdown](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/cluster-nodes-shutdown.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.delay - Set the delay for the operation (default: 1s)
 * @param {Boolean} params.exit - Exit the JVM as well (default: true)
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to perform the operation on; use `_local` to perform the operation on the node you're connected to, leave empty to perform the operation on all nodes
 */
api.cluster.prototype.nodeShutdown = ca({
  params: {
    delay: {
      type: 'time'
    },
    exit: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/_cluster/nodes/<%=nodeId%>/_shutdown',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_shutdown'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [cluster.nodeStats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/cluster-nodes-stats.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.all - Return all available information
 * @param {Boolean} params.clear - Reset the default level of detail
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return detailed information for, when returning the `indices` metric family (supports wildcards)
 * @param {Boolean} params.fs - Return information about the filesystem
 * @param {Boolean} params.http - Return information about HTTP
 * @param {Boolean} params.indices - Return information about indices
 * @param {Boolean} params.jvm - Return information about the JVM
 * @param {Boolean} params.network - Return information about network
 * @param {Boolean} params.os - Return information about the operating system
 * @param {Boolean} params.process - Return information about the Elasticsearch process
 * @param {Boolean} params.threadPool - Return information about the thread pool
 * @param {Boolean} params.transport - Return information about transport
 * @param {String} params.metricFamily - Limit the information returned to a certain metric family
 * @param {String} params.metric - Limit the information returned for `indices` family to a specific metric
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
 */
api.cluster.prototype.nodeStats = ca({
  params: {
    all: {
      type: 'boolean'
    },
    clear: {
      type: 'boolean'
    },
    fields: {
      type: 'list'
    },
    fs: {
      type: 'boolean'
    },
    http: {
      type: 'boolean'
    },
    indices: {
      type: 'boolean'
    },
    jvm: {
      type: 'boolean'
    },
    network: {
      type: 'boolean'
    },
    os: {
      type: 'boolean'
    },
    process: {
      type: 'boolean'
    },
    threadPool: {
      type: 'boolean',
      name: 'thread_pool'
    },
    transport: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/_nodes/<%=nodeId%>/stats',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_nodes/stats'
    }
  ]
});

/**
 * Perform a [cluster.pendingTasks](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/cluster-pending.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 */
api.cluster.prototype.pendingTasks = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_cluster/pending_tasks'
  }
});

/**
 * Perform a [cluster.putSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/cluster-update-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 */
api.cluster.prototype.putSettings = ca({
  url: {
    fmt: '/_cluster/settings'
  },
  method: 'PUT'
});

/**
 * Perform a [cluster.reroute](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/cluster-reroute.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.dryRun - Simulate the operation only and return the resulting state
 * @param {Boolean} params.filterMetadata - Don't return cluster state metadata (default: false)
 */
api.cluster.prototype.reroute = ca({
  params: {
    dryRun: {
      type: 'boolean',
      name: 'dry_run'
    },
    filterMetadata: {
      type: 'boolean',
      name: 'filter_metadata'
    }
  },
  url: {
    fmt: '/_cluster/reroute'
  },
  method: 'POST'
});

/**
 * Perform a [cluster.state](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/cluster-state.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.filterBlocks - Do not return information about blocks
 * @param {Boolean} params.filterIndexTemplates - Do not return information about index templates
 * @param {String, String[], Boolean} params.filterIndices - Limit returned metadata information to specific indices
 * @param {Boolean} params.filterMetadata - Do not return information about indices metadata
 * @param {Boolean} params.filterNodes - Do not return information about nodes
 * @param {Boolean} params.filterRoutingTable - Do not return information about shard allocation (`routing_table` and `routing_nodes`)
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 */
api.cluster.prototype.state = ca({
  params: {
    filterBlocks: {
      type: 'boolean',
      name: 'filter_blocks'
    },
    filterIndexTemplates: {
      type: 'boolean',
      name: 'filter_index_templates'
    },
    filterIndices: {
      type: 'list',
      name: 'filter_indices'
    },
    filterMetadata: {
      type: 'boolean',
      name: 'filter_metadata'
    },
    filterNodes: {
      type: 'boolean',
      name: 'filter_nodes'
    },
    filterRoutingTable: {
      type: 'boolean',
      name: 'filter_routing_table'
    },
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_cluster/state'
  }
});

/**
 * Perform a [count](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/search-count.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {Number} params.minScore - Include only documents with a specific `_score` value in the result
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the results
 * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the results
 */
api.count = ca({
  params: {
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    minScore: {
      type: 'number',
      name: 'min_score'
    },
    preference: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_count',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_count',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_count'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/docs-delete.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Specific write consistency setting for the operation
 * @param {String} params.parent - ID of parent document
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.routing - Specific routing value
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api['delete'] = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    parent: {
      type: 'string'
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    routing: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external'
      ],
      name: 'version_type'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [deleteByQuery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/docs-delete-by-query.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.analyzer - The analyzer to use for the query string
 * @param {String} params.consistency - Specific write consistency setting for the operation
 * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR)
 * @param {String} params.df - The field to use as default where no field prefix is given in the query string
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the operation; use `_all` to perform the operation on all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the operation
 */
api.deleteByQuery = ca({
  params: {
    analyzer: {
      type: 'string'
    },
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    defaultOperator: {
      type: 'enum',
      'default': 'OR',
      options: [
        'AND',
        'OR'
      ],
      name: 'default_operator'
    },
    df: {
      type: 'string'
    },
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    q: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_query',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_query',
      req: {
        index: {
          type: 'list'
        }
      }
    }
  ],
  method: 'DELETE'
});

/**
 * Perform a [exists](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/docs-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String} params.routing - Specific routing value
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types)
 */
api.exists = ca({
  params: {
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    routing: {
      type: 'string'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'HEAD'
});

/**
 * Perform a [explain](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/search-explain.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.analyzeWildcard - Specify whether wildcards and prefix queries in the query string query should be analyzed (default: false)
 * @param {String} params.analyzer - The analyzer for the query string query
 * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR)
 * @param {String} params.df - The default field for query string query (default: _all)
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
 * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.explain = ca({
  params: {
    analyzeWildcard: {
      type: 'boolean',
      name: 'analyze_wildcard'
    },
    analyzer: {
      type: 'string'
    },
    defaultOperator: {
      type: 'enum',
      'default': 'OR',
      options: [
        'AND',
        'OR'
      ],
      name: 'default_operator'
    },
    df: {
      type: 'string'
    },
    fields: {
      type: 'list'
    },
    lenient: {
      type: 'boolean'
    },
    lowercaseExpandedTerms: {
      type: 'boolean',
      name: 'lowercase_expanded_terms'
    },
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    q: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_explain',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [get](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/docs-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String} params.routing - Specific routing value
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types)
 */
api.get = ca({
  params: {
    fields: {
      type: 'list'
    },
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    routing: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  }
});

/**
 * Perform a [getSource](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/docs-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String} params.routing - Specific routing value
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document; use `_all` to fetch the first document matching the ID across all types
 */
api.getSource = ca({
  params: {
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    routing: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external'
      ],
      name: 'version_type'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_source',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  }
});

/**
 * Perform a [index](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/docs-index_.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {String} params.parent - ID of the parent document
 * @param {String} params.percolate - Percolator queries to execute while indexing the document
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.routing - Specific routing value
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.timestamp - Explicit timestamp for the document
 * @param {Duration} params.ttl - Expiration time for the document
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - Document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.index = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    opType: {
      type: 'enum',
      'default': 'index',
      options: [
        'index',
        'create'
      ],
      name: 'op_type'
    },
    parent: {
      type: 'string'
    },
    percolate: {
      type: 'string'
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    routing: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    },
    timestamp: {
      type: 'time'
    },
    ttl: {
      type: 'duration'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external'
      ],
      name: 'version_type'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/<%=id%>',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        },
        id: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/<%=type%>',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    }
  ],
  needBody: true,
  method: 'POST'
});

api.indices = function IndicesNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [indices.analyze](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-analyze.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.analyzer - The name of the analyzer to use
 * @param {String} params.field - Use the analyzer configured for this field (instead of passing the analyzer name)
 * @param {String, String[], Boolean} params.filters - A comma-separated list of filters to use for the analysis
 * @param {String} params.index - The name of the index to scope the operation
 * @param {Boolean} params.preferLocal - With `true`, specify that a local shard should be used if available, with `false`, use a random shard (default: true)
 * @param {String} params.text - The text on which the analysis should be performed (when request body is not used)
 * @param {String} params.tokenizer - The name of the tokenizer to use for the analysis
 * @param {String} [params.format=detailed] - Format of the output
 */
api.indices.prototype.analyze = ca({
  params: {
    analyzer: {
      type: 'string'
    },
    field: {
      type: 'string'
    },
    filters: {
      type: 'list'
    },
    index: {
      type: 'string'
    },
    preferLocal: {
      type: 'boolean',
      name: 'prefer_local'
    },
    text: {
      type: 'string'
    },
    tokenizer: {
      type: 'string'
    },
    format: {
      type: 'enum',
      'default': 'detailed',
      options: [
        'detailed',
        'text'
      ]
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_analyze',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_analyze'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.clearCache](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-clearcache.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.fieldData - Clear field data
 * @param {Boolean} params.fielddata - Clear field data
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to clear when using the `field_data` parameter (default: all)
 * @param {Boolean} params.filter - Clear filter caches
 * @param {Boolean} params.filterCache - Clear filter caches
 * @param {Boolean} params.filterKeys - A comma-separated list of keys to clear when using the `filter_cache` parameter (default: all)
 * @param {Boolean} params.id - Clear ID caches for parent/child
 * @param {Boolean} params.idCache - Clear ID caches for parent/child
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {String, String[], Boolean} params.index - A comma-separated list of index name to limit the operation
 * @param {Boolean} params.recycler - Clear the recycler cache
 */
api.indices.prototype.clearCache = ca({
  params: {
    fieldData: {
      type: 'boolean',
      name: 'field_data'
    },
    fielddata: {
      type: 'boolean'
    },
    fields: {
      type: 'list'
    },
    filter: {
      type: 'boolean'
    },
    filterCache: {
      type: 'boolean',
      name: 'filter_cache'
    },
    filterKeys: {
      type: 'boolean',
      name: 'filter_keys'
    },
    id: {
      type: 'boolean'
    },
    idCache: {
      type: 'boolean',
      name: 'id_cache'
    },
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    index: {
      type: 'list'
    },
    recycler: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_cache/clear',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cache/clear'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.close](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-open-close.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String} params.index - The name of the index
 */
api.indices.prototype.close = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>/_close',
    req: {
      index: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [indices.create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-create-index.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String} params.index - The name of the index
 */
api.indices.prototype.create = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>',
    req: {
      index: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [indices.delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-delete-index.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to delete; use `_all` or empty string to delete all indices
 */
api.indices.prototype['delete'] = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/'
    }
  ],
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit timestamp for the document
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String} params.index - The name of the index with an alias
 * @param {String} params.name - The name of the alias to be deleted
 */
api.indices.prototype.deleteAlias = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>/_alias/<%=name%>',
    req: {
      index: {
        type: 'string'
      },
      name: {
        type: 'string'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-delete-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` for all indices
 * @param {String} params.type - The name of the document type to delete
 */
api.indices.prototype.deleteMapping = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>',
    req: {
      index: {
        type: 'list'
      },
      type: {
        type: 'string'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-templates.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String} params.name - The name of the template
 */
api.indices.prototype.deleteTemplate = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_template/<%=name%>',
    req: {
      name: {
        type: 'string'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-warmers.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to register warmer for; use `_all` or empty string to perform the operation on all indices
 * @param {String} params.name - The name of the warmer (supports wildcards); leave empty to delete all warmers
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to register warmer for; use `_all` or empty string to perform the operation on all types
 */
api.indices.prototype.deleteWarmer = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_warmer',
      req: {
        index: {
          type: 'list'
        }
      }
    }
  ],
  method: 'DELETE'
});

/**
 * Perform a [indices.exists](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-get-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to check
 */
api.indices.prototype.exists = ca({
  url: {
    fmt: '/<%=index%>',
    req: {
      index: {
        type: 'list'
      }
    }
  },
  method: 'HEAD'
});

/**
 * Perform a [indices.existsAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases
 * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return
 */
api.indices.prototype.existsAlias = ca({
  params: {
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_alias/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_alias/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    }
  ],
  method: 'HEAD'
});

/**
 * Perform a [indices.existsType](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-types-exists.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` to check the types across all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to check
 */
api.indices.prototype.existsType = ca({
  params: {
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>',
    req: {
      index: {
        type: 'list'
      },
      type: {
        type: 'list'
      }
    }
  },
  method: 'HEAD'
});

/**
 * Perform a [indices.flush](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-flush.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.force - Whether a flush should be forced even if it is not necessarily needed ie. if no changes will be committed to the index. This is useful if transaction log IDs should be incremented even if no uncommitted changes are present. (This setting can be considered as internal)
 * @param {Boolean} params.full - If set to true a new index writer is created and settings that have been changed related to the index writer will be refreshed. Note: if a full flush is required for a setting to take effect this will be part of the settings update process and it not required to be executed by the user. (This setting can be considered as internal)
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string for all indices
 */
api.indices.prototype.flush = ca({
  params: {
    force: {
      type: 'boolean'
    },
    full: {
      type: 'boolean'
    },
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    refresh: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_flush',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_flush'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.getAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases
 * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return
 */
api.indices.prototype.getAlias = ca({
  params: {
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_alias/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_alias/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    }
  ]
});

/**
 * Perform a [indices.getAliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases
 */
api.indices.prototype.getAliases = ca({
  params: {
    timeout: {
      type: 'time'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_aliases',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_aliases'
    }
  ]
});

/**
 * Perform a [indices.getFieldMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-get-field-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.includeDefaults - Whether the default mapping values should be returned as well
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types
 * @param {String, String[], Boolean} params.field - A comma-separated list of fields
 */
api.indices.prototype.getFieldMapping = ca({
  params: {
    includeDefaults: {
      type: 'boolean',
      name: 'include_defaults'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_mapping/field/<%=field%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        },
        field: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mapping/field/<%=field%>',
      req: {
        index: {
          type: 'list'
        },
        field: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_mapping/field/<%=field%>',
      req: {
        field: {
          type: 'list'
        }
      }
    }
  ]
});

/**
 * Perform a [indices.getMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-get-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types
 */
api.indices.prototype.getMapping = ca({
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_mapping',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mapping',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_mapping'
    }
  ]
});

/**
 * Perform a [indices.getSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-get-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.getSettings = ca({
  urls: [
    {
      fmt: '/<%=index%>/_settings',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_settings'
    }
  ]
});

/**
 * Perform a [indices.getTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-templates.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.name - The name of the template
 */
api.indices.prototype.getTemplate = ca({
  urls: [
    {
      fmt: '/_template/<%=name%>',
      req: {
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_template'
    }
  ]
});

/**
 * Perform a [indices.getWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-warmers.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` to perform the operation on all indices
 * @param {String} params.name - The name of the warmer (supports wildcards); leave empty to get all warmers
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types
 */
api.indices.prototype.getWarmer = ca({
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_warmer',
      req: {
        index: {
          type: 'list'
        }
      }
    }
  ]
});

/**
 * Perform a [indices.open](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-open-close.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String} params.index - The name of the index
 */
api.indices.prototype.open = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>/_open',
    req: {
      index: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [indices.optimize](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-optimize.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flush - Specify whether the index should be flushed after performing the operation (default: true)
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {Number} params.maxNumSegments - The number of segments the index should be merged into (default: dynamic)
 * @param {Boolean} params.onlyExpungeDeletes - Specify whether the operation should only expunge deleted documents
 * @param {Anything} params.operationThreading - : ?
 * @param {Boolean} params.refresh - Specify whether the index should be refreshed after performing the operation (default: true)
 * @param {Boolean} params.waitForMerge - Specify whether the request should block until the merge process is finished (default: true)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.optimize = ca({
  params: {
    flush: {
      type: 'boolean'
    },
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    maxNumSegments: {
      type: 'number',
      name: 'max_num_segments'
    },
    onlyExpungeDeletes: {
      type: 'boolean',
      name: 'only_expunge_deletes'
    },
    operationThreading: {
      name: 'operation_threading'
    },
    refresh: {
      type: 'boolean'
    },
    waitForMerge: {
      type: 'boolean',
      name: 'wait_for_merge'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_optimize',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_optimize'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.putAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit timestamp for the document
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String} params.index - The name of the index with an alias
 * @param {String} params.name - The name of the alias to be created or updated
 */
api.indices.prototype.putAlias = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_alias/<%=name%>',
      req: {
        index: {
          type: 'string'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_alias/<%=name%>',
      req: {
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_alias',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_alias'
    }
  ],
  method: 'PUT'
});

/**
 * Perform a [indices.putMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-put-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreConflicts - Specify whether to ignore conflicts while updating the mapping (default: false)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` to perform the operation on all indices
 * @param {String} params.type - The name of the document type
 */
api.indices.prototype.putMapping = ca({
  params: {
    ignoreConflicts: {
      type: 'boolean',
      name: 'ignore_conflicts'
    },
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/_mapping',
    req: {
      index: {
        type: 'list'
      },
      type: {
        type: 'string'
      }
    }
  },
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.putSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-update-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.putSettings = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_settings',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_settings'
    }
  ],
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.putTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-templates.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Number} params.order - The order for this template when merging multiple matching ones (higher numbers are merged later, overriding the lower numbers)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String} params.name - The name of the template
 */
api.indices.prototype.putTemplate = ca({
  params: {
    order: {
      type: 'number'
    },
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_template/<%=name%>',
    req: {
      name: {
        type: 'string'
      }
    }
  },
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.putWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-warmers.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to register the warmer for; use `_all` or empty string to perform the operation on all indices
 * @param {String} params.name - The name of the warmer
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to register the warmer for; leave empty to perform the operation on all types
 */
api.indices.prototype.putWarmer = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    }
  ],
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.refresh](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-refresh.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {Anything} params.operationThreading - : ?
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.refresh = ca({
  params: {
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    operationThreading: {
      name: 'operation_threading'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_refresh',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_refresh'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.segments](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-segments.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {Anything} params.operationThreading - : ?
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.segments = ca({
  params: {
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    operationThreading: {
      name: 'operation_threading'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_segments',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_segments'
    }
  ]
});

/**
 * Perform a [indices.snapshotIndex](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-gateway-snapshot.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string for all indices
 */
api.indices.prototype.snapshotIndex = ca({
  params: {
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_gateway/snapshot',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_gateway/snapshot'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-stats.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.all - Return all available information
 * @param {Boolean} params.clear - Reset the default level of detail
 * @param {Boolean} params.completion - Return information about completion suggester stats
 * @param {String, String[], Boolean} params.completionFields - A comma-separated list of fields for `completion` metric (supports wildcards)
 * @param {Boolean} params.docs - Return information about indexed and deleted documents
 * @param {Boolean} params.fielddata - Return information about field data
 * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields for `fielddata` metric (supports wildcards)
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return detailed information for, when returning the `search` statistics
 * @param {Boolean} params.filterCache - Return information about filter cache
 * @param {Boolean} params.flush - Return information about flush operations
 * @param {Boolean} params.get - Return information about get operations
 * @param {Boolean} params.groups - A comma-separated list of search groups for `search` statistics
 * @param {Boolean} params.idCache - Return information about ID cache
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {Boolean} params.indexing - Return information about indexing operations
 * @param {Boolean} params.merge - Return information about merge operations
 * @param {Boolean} params.refresh - Return information about refresh operations
 * @param {Boolean} params.search - Return information about search operations; use the `groups` parameter to include information for specific search groups
 * @param {Boolean} params.store - Return information about the size of the index
 * @param {Boolean} params.warmer - Return information about warmers
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.indexingTypes - A comma-separated list of document types to include in the `indexing` statistics
 * @param {String} params.metricFamily - Limit the information returned to a specific metric
 * @param {String, String[], Boolean} params.searchGroups - A comma-separated list of search groups to include in the `search` statistics
 */
api.indices.prototype.stats = ca({
  params: {
    all: {
      type: 'boolean'
    },
    clear: {
      type: 'boolean'
    },
    completion: {
      type: 'boolean'
    },
    completionFields: {
      type: 'list',
      name: 'completion_fields'
    },
    docs: {
      type: 'boolean'
    },
    fielddata: {
      type: 'boolean'
    },
    fielddataFields: {
      type: 'list',
      name: 'fielddata_fields'
    },
    fields: {
      type: 'list'
    },
    filterCache: {
      type: 'boolean',
      name: 'filter_cache'
    },
    flush: {
      type: 'boolean'
    },
    get: {
      type: 'boolean'
    },
    groups: {
      type: 'boolean'
    },
    idCache: {
      type: 'boolean',
      name: 'id_cache'
    },
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    indexing: {
      type: 'boolean'
    },
    merge: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    search: {
      type: 'boolean'
    },
    store: {
      type: 'boolean'
    },
    warmer: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_stats',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_stats'
    }
  ]
});

/**
 * Perform a [indices.status](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-status.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {Anything} params.operationThreading - : ?
 * @param {Boolean} params.recovery - Return information about shard recovery
 * @param {Boolean} params.snapshot - : ?
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.status = ca({
  params: {
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    operationThreading: {
      name: 'operation_threading'
    },
    recovery: {
      type: 'boolean'
    },
    snapshot: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_status',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_status'
    }
  ]
});

/**
 * Perform a [indices.updateAliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Request timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases
 */
api.indices.prototype.updateAliases = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_aliases'
  },
  needBody: true,
  method: 'POST'
});

/**
 * Perform a [indices.validateQuery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/search-validate.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.explain - Return detailed information about the error
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {Anything} params.operationThreading - : ?
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types
 */
api.indices.prototype.validateQuery = ca({
  params: {
    explain: {
      type: 'boolean'
    },
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    operationThreading: {
      name: 'operation_threading'
    },
    source: {
      type: 'string'
    },
    q: {
      type: 'string'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_validate/query',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_validate/query',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_validate/query'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [info](http://www.elasticsearch.org/guide/) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 */
api.info = ca({
  url: {
    fmt: '/'
  }
});

/**
 * Perform a [mget](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/docs-multi-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.mget = ca({
  params: {
    fields: {
      type: 'list'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_mget',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mget',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_mget'
    }
  ],
  needBody: true,
  method: 'POST'
});

/**
 * Perform a [mlt](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/search-more-like-this.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Number} params.boostTerms - The boost factor
 * @param {Number} params.maxDocFreq - The word occurrence frequency as count: words with higher occurrence in the corpus will be ignored
 * @param {Number} params.maxQueryTerms - The maximum query terms to be included in the generated query
 * @param {Number} params.maxWordLen - The minimum length of the word: longer words will be ignored
 * @param {Number} params.minDocFreq - The word occurrence frequency as count: words with lower occurrence in the corpus will be ignored
 * @param {Number} params.minTermFreq - The term frequency as percent: terms with lower occurence in the source document will be ignored
 * @param {Number} params.minWordLen - The minimum length of the word: shorter words will be ignored
 * @param {String, String[], Boolean} params.mltFields - Specific fields to perform the query against
 * @param {Number} params.percentTermsToMatch - How many terms have to match in order to consider the document a match (default: 0.3)
 * @param {String} params.routing - Specific routing value
 * @param {Number} params.searchFrom - The offset from which to return results
 * @param {String, String[], Boolean} params.searchIndices - A comma-separated list of indices to perform the query against (default: the index containing the document)
 * @param {String} params.searchQueryHint - The search query hint
 * @param {String} params.searchScroll - A scroll search request definition
 * @param {Number} params.searchSize - The number of documents to return (default: 10)
 * @param {String} params.searchSource - A specific search request definition (instead of using the request body)
 * @param {String} params.searchType - Specific search type (eg. `dfs_then_fetch`, `count`, etc)
 * @param {String, String[], Boolean} params.searchTypes - A comma-separated list of types to perform the query against (default: the same type as the document)
 * @param {String, String[], Boolean} params.stopWords - A list of stop words to be ignored
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types)
 */
api.mlt = ca({
  params: {
    boostTerms: {
      type: 'number',
      name: 'boost_terms'
    },
    maxDocFreq: {
      type: 'number',
      name: 'max_doc_freq'
    },
    maxQueryTerms: {
      type: 'number',
      name: 'max_query_terms'
    },
    maxWordLen: {
      type: 'number',
      name: 'max_word_len'
    },
    minDocFreq: {
      type: 'number',
      name: 'min_doc_freq'
    },
    minTermFreq: {
      type: 'number',
      name: 'min_term_freq'
    },
    minWordLen: {
      type: 'number',
      name: 'min_word_len'
    },
    mltFields: {
      type: 'list',
      name: 'mlt_fields'
    },
    percentTermsToMatch: {
      type: 'number',
      name: 'percent_terms_to_match'
    },
    routing: {
      type: 'string'
    },
    searchFrom: {
      type: 'number',
      name: 'search_from'
    },
    searchIndices: {
      type: 'list',
      name: 'search_indices'
    },
    searchQueryHint: {
      type: 'string',
      name: 'search_query_hint'
    },
    searchScroll: {
      type: 'string',
      name: 'search_scroll'
    },
    searchSize: {
      type: 'number',
      name: 'search_size'
    },
    searchSource: {
      type: 'string',
      name: 'search_source'
    },
    searchType: {
      type: 'string',
      name: 'search_type'
    },
    searchTypes: {
      type: 'list',
      name: 'search_types'
    },
    stopWords: {
      type: 'list',
      name: 'stop_words'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_mlt',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [msearch](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/search-multi-search.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.searchType - Search operation type
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to use as default
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to use as default
 */
api.msearch = ca({
  params: {
    searchType: {
      type: 'enum',
      options: [
        'query_then_fetch',
        'query_and_fetch',
        'dfs_query_then_fetch',
        'dfs_query_and_fetch',
        'count',
        'scan'
      ],
      name: 'search_type'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_msearch',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_msearch',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_msearch'
    }
  ],
  needBody: true,
  bulkBody: true,
  method: 'POST'
});

/**
 * Perform a [percolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/search-percolate.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.preferLocal - With `true`, specify that a local shard should be used if available, with `false`, use a random shard (default: true)
 * @param {String} params.index - The name of the index with a registered percolator query
 * @param {String} params.type - The document type
 */
api.percolate = ca({
  params: {
    preferLocal: {
      type: 'boolean',
      name: 'prefer_local'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/_percolate',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      }
    }
  },
  needBody: true,
  method: 'POST'
});

/**
 * Perform a [ping](http://www.elasticsearch.org/guide/) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 */
api.ping = ca({
  url: {
    fmt: '/'
  },
  requestTimeout: 100,
  method: 'HEAD'
});

/**
 * Perform a [scroll](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/search-request-scroll.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search
 * @param {String} params.scrollId - The scroll ID
 */
api.scroll = ca({
  params: {
    scroll: {
      type: 'duration'
    },
    scrollId: {
      type: 'string',
      name: 'scroll_id'
    }
  },
  urls: [
    {
      fmt: '/_search/scroll/<%=scrollId%>',
      req: {
        scrollId: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_search/scroll'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [search](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/search-search.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.analyzer - The analyzer to use for the query string
 * @param {Boolean} params.analyzeWildcard - Specify whether wildcard and prefix queries should be analyzed (default: false)
 * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR)
 * @param {String} params.df - The field to use as default where no field prefix is given in the query string
 * @param {Boolean} params.explain - Specify whether to return detailed information about score computation as part of a hit
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return as part of a hit
 * @param {Number} params.from - Starting offset (default: 0)
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {String, String[], Boolean} params.indicesBoost - Comma-separated list of index boosts
 * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
 * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values
 * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search
 * @param {String} params.searchType - Search operation type
 * @param {Number} params.size - Number of hits to return (default: 10)
 * @param {String, String[], Boolean} params.sort - A comma-separated list of <field>:<direction> pairs
 * @param {String} params.source - The URL-encoded request definition using the Query DSL (instead of using request body)
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {String, String[], Boolean} params.stats - Specific 'tag' of the request for logging and statistical purposes
 * @param {String} params.suggestField - Specify which field to use for suggestions
 * @param {String} [params.suggestMode=missing] - Specify suggest mode
 * @param {Number} params.suggestSize - How many suggestions to return in response
 * @param {Text} params.suggestText - The source text for which the suggestions should be returned
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Boolean} params.version - Specify whether to return document version as part of a hit
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to search; leave empty to perform the operation on all types
 */
api.search = ca({
  params: {
    analyzer: {
      type: 'string'
    },
    analyzeWildcard: {
      type: 'boolean',
      name: 'analyze_wildcard'
    },
    defaultOperator: {
      type: 'enum',
      'default': 'OR',
      options: [
        'AND',
        'OR'
      ],
      name: 'default_operator'
    },
    df: {
      type: 'string'
    },
    explain: {
      type: 'boolean'
    },
    fields: {
      type: 'list'
    },
    from: {
      type: 'number'
    },
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    indicesBoost: {
      type: 'list',
      name: 'indices_boost'
    },
    lenient: {
      type: 'boolean'
    },
    lowercaseExpandedTerms: {
      type: 'boolean',
      name: 'lowercase_expanded_terms'
    },
    preference: {
      type: 'string'
    },
    q: {
      type: 'string'
    },
    routing: {
      type: 'list'
    },
    scroll: {
      type: 'duration'
    },
    searchType: {
      type: 'enum',
      options: [
        'query_then_fetch',
        'query_and_fetch',
        'dfs_query_then_fetch',
        'dfs_query_and_fetch',
        'count',
        'scan'
      ],
      name: 'search_type'
    },
    size: {
      type: 'number'
    },
    sort: {
      type: 'list'
    },
    source: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    },
    stats: {
      type: 'list'
    },
    suggestField: {
      type: 'string',
      name: 'suggest_field'
    },
    suggestMode: {
      type: 'enum',
      'default': 'missing',
      options: [
        'missing',
        'popular',
        'always'
      ],
      name: 'suggest_mode'
    },
    suggestSize: {
      type: 'number',
      name: 'suggest_size'
    },
    suggestText: {
      type: 'text',
      name: 'suggest_text'
    },
    timeout: {
      type: 'time'
    },
    version: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_search',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_search',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_search'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [suggest](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/search-search.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.ignoreIndices=none] - When performed on multiple indices, allows to ignore `missing` ones
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded request definition (instead of using request body)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices
 */
api.suggest = ca({
  params: {
    ignoreIndices: {
      type: 'enum',
      'default': 'none',
      options: [
        'none',
        'missing'
      ],
      name: 'ignore_indices'
    },
    preference: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_suggest',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_suggest'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [update](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/docs-update.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {String} params.lang - The script language (default: mvel)
 * @param {String} params.parent - ID of the parent document
 * @param {String} params.percolate - Perform percolation during the operation; use specific registered query name, attribute, or wildcard
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {Number} params.retryOnConflict - Specify how many times should the operation be retried when a conflict occurs (default: 0)
 * @param {String} params.routing - Specific routing value
 * @param {Anything} params.script - The URL-encoded script definition (instead of using request body)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.timestamp - Explicit timestamp for the document
 * @param {Duration} params.ttl - Expiration time for the document
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - Document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.update = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    fields: {
      type: 'list'
    },
    lang: {
      type: 'string'
    },
    parent: {
      type: 'string'
    },
    percolate: {
      type: 'string'
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    retryOnConflict: {
      type: 'number',
      name: 'retry_on_conflict'
    },
    routing: {
      type: 'string'
    },
    script: {},
    timeout: {
      type: 'time'
    },
    timestamp: {
      type: 'time'
    },
    ttl: {
      type: 'duration'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external'
      ],
      name: 'version_type'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_update',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/docs-index_.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {String} params.parent - ID of the parent document
 * @param {String} params.percolate - Percolator queries to execute while indexing the document
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.routing - Specific routing value
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.timestamp - Explicit timestamp for the document
 * @param {Duration} params.ttl - Expiration time for the document
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - Document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.create = ca.proxy(api.index, {
  transform: function (params) {
    params.op_type = 'create';
  }
});
},{"../client_action":195}],191:[function(require,module,exports){
/* jshint maxlen: false */

var ca = require('../client_action');
var api = module.exports = {};

api._namespaces = ['cat', 'cluster', 'indices', 'nodes', 'snapshot'];

/**
 * Perform a [bulk](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-bulk.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Explicitely set the replication type
 * @param {String} params.routing - Specific routing value
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {String} params.type - Default document type for items which don't provide one
 * @param {String} params.index - Default index for items which don't provide one
 */
api.bulk = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    routing: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    },
    type: {
      type: 'string'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_bulk',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_bulk',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_bulk'
    }
  ],
  needBody: true,
  bulkBody: true,
  method: 'POST'
});

api.cat = function CatNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [cat.aliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return
 */
api.cat.prototype.aliases = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/aliases/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/aliases'
    }
  ]
});

/**
 * Perform a [cat.allocation](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-allocation.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.bytes - The unit in which to display byte values
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information
 */
api.cat.prototype.allocation = ca({
  params: {
    bytes: {
      type: 'enum',
      options: [
        'b',
        'k',
        'm',
        'g'
      ]
    },
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/allocation/<%=nodeId%>',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/allocation'
    }
  ]
});

/**
 * Perform a [cat.count](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-count.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information
 */
api.cat.prototype.count = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/count/<%=index%>',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/count'
    }
  ]
});

/**
 * Perform a [cat.health](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-health.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} [params.ts=true] - Set to false to disable timestamping
 * @param {Boolean} params.v - Verbose mode. Display column headers
 */
api.cat.prototype.health = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    ts: {
      type: 'boolean',
      'default': true
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  url: {
    fmt: '/_cat/health'
  }
});

/**
 * Perform a [cat.help](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.help - Return help information
 */
api.cat.prototype.help = ca({
  params: {
    help: {
      type: 'boolean',
      'default': false
    }
  },
  url: {
    fmt: '/_cat'
  }
});

/**
 * Perform a [cat.indices](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-indices.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.bytes - The unit in which to display byte values
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.pri - Set to true to return stats only for primary shards
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information
 */
api.cat.prototype.indices = ca({
  params: {
    bytes: {
      type: 'enum',
      options: [
        'b',
        'k',
        'm',
        'g'
      ]
    },
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    pri: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/indices/<%=index%>',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/indices'
    }
  ]
});

/**
 * Perform a [cat.master](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-master.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 */
api.cat.prototype.master = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  url: {
    fmt: '/_cat/master'
  }
});

/**
 * Perform a [cat.nodes](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-nodes.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 */
api.cat.prototype.nodes = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  url: {
    fmt: '/_cat/nodes'
  }
});

/**
 * Perform a [cat.pendingTasks](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-pending-tasks.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 */
api.cat.prototype.pendingTasks = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  url: {
    fmt: '/_cat/pending_tasks'
  }
});

/**
 * Perform a [cat.recovery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-recovery.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.bytes - The unit in which to display byte values
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information
 */
api.cat.prototype.recovery = ca({
  params: {
    bytes: {
      type: 'enum',
      options: [
        'b',
        'k',
        'm',
        'g'
      ]
    },
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/recovery/<%=index%>',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/recovery'
    }
  ]
});

/**
 * Perform a [cat.shards](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-shards.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information
 */
api.cat.prototype.shards = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/shards/<%=index%>',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/shards'
    }
  ]
});

/**
 * Perform a [cat.threadPool](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-thread-pool.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {Boolean} params.fullId - Enables displaying the complete node ids
 */
api.cat.prototype.threadPool = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    },
    fullId: {
      type: 'boolean',
      'default': false,
      name: 'full_id'
    }
  },
  url: {
    fmt: '/_cat/thread_pool'
  }
});

/**
 * Perform a [clearScroll](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-request-scroll.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.scrollId - A comma-separated list of scroll IDs to clear
 */
api.clearScroll = ca({
  url: {
    fmt: '/_search/scroll/<%=scrollId%>',
    req: {
      scrollId: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

api.cluster = function ClusterNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [cluster.getSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-update-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Date, Number} params.timeout - Explicit operation timeout
 */
api.cluster.prototype.getSettings = ca({
  params: {
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    timeout: {
      type: 'time'
    }
  },
  url: {
    fmt: '/_cluster/settings'
  }
});

/**
 * Perform a [cluster.health](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-health.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.level=cluster] - Specify the level of detail for returned information
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Number} params.waitForActiveShards - Wait until the specified number of shards is active
 * @param {String} params.waitForNodes - Wait until the specified number of nodes is available
 * @param {Number} params.waitForRelocatingShards - Wait until the specified number of relocating shards is finished
 * @param {String} params.waitForStatus - Wait until cluster is in a specific state
 * @param {String} params.index - Limit the information returned to a specific index
 */
api.cluster.prototype.health = ca({
  params: {
    level: {
      type: 'enum',
      'default': 'cluster',
      options: [
        'cluster',
        'indices',
        'shards'
      ]
    },
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    timeout: {
      type: 'time'
    },
    waitForActiveShards: {
      type: 'number',
      name: 'wait_for_active_shards'
    },
    waitForNodes: {
      type: 'string',
      name: 'wait_for_nodes'
    },
    waitForRelocatingShards: {
      type: 'number',
      name: 'wait_for_relocating_shards'
    },
    waitForStatus: {
      type: 'enum',
      'default': null,
      options: [
        'green',
        'yellow',
        'red'
      ],
      name: 'wait_for_status'
    }
  },
  urls: [
    {
      fmt: '/_cluster/health/<%=index%>',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_cluster/health'
    }
  ]
});

/**
 * Perform a [cluster.pendingTasks](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-pending.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 */
api.cluster.prototype.pendingTasks = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_cluster/pending_tasks'
  }
});

/**
 * Perform a [cluster.putSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-update-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 */
api.cluster.prototype.putSettings = ca({
  params: {
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    }
  },
  url: {
    fmt: '/_cluster/settings'
  },
  method: 'PUT'
});

/**
 * Perform a [cluster.reroute](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-reroute.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.dryRun - Simulate the operation only and return the resulting state
 * @param {Boolean} params.filterMetadata - Don't return cluster state metadata (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Date, Number} params.timeout - Explicit operation timeout
 */
api.cluster.prototype.reroute = ca({
  params: {
    dryRun: {
      type: 'boolean',
      name: 'dry_run'
    },
    filterMetadata: {
      type: 'boolean',
      name: 'filter_metadata'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    timeout: {
      type: 'time'
    }
  },
  url: {
    fmt: '/_cluster/reroute'
  },
  method: 'POST'
});

/**
 * Perform a [cluster.state](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-state.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.indexTemplates - A comma separated list to return specific index templates when returning metadata
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics
 */
api.cluster.prototype.state = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    indexTemplates: {
      type: 'list',
      name: 'index_templates'
    },
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    }
  },
  urls: [
    {
      fmt: '/_cluster/state/<%=metric%>/<%=index%>',
      req: {
        metric: {
          type: 'list',
          options: [
            '_all',
            'blocks',
            'metadata',
            'nodes',
            'routing_table',
            'master_node',
            'version'
          ]
        },
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cluster/state/<%=metric%>',
      req: {
        metric: {
          type: 'list',
          options: [
            '_all',
            'blocks',
            'metadata',
            'nodes',
            'routing_table',
            'master_node',
            'version'
          ]
        }
      }
    },
    {
      fmt: '/_cluster/state'
    }
  ]
});

/**
 * Perform a [cluster.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-stats.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
 */
api.cluster.prototype.stats = ca({
  params: {
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    },
    human: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cluster/stats/nodes/<%=nodeId%>',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cluster/stats'
    }
  ]
});

/**
 * Perform a [count](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-count.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Number} params.minScore - Include only documents with a specific `_score` value in the result
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the results
 * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the results
 */
api.count = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    minScore: {
      type: 'number',
      name: 'min_score'
    },
    preference: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_count',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_count',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_count'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [countPercolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.percolateIndex - The index to count percolate the document into. Defaults to index.
 * @param {String} params.percolateType - The type to count percolate document into. Defaults to type.
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.index - The index of the document being count percolated.
 * @param {String} params.type - The type of the document being count percolated.
 * @param {String} params.id - Substitute the document in the request body with a document that is known by the specified id. On top of the id, the index and type parameter will be used to retrieve the document from within the cluster.
 */
api.countPercolate = ca({
  params: {
    routing: {
      type: 'list'
    },
    preference: {
      type: 'string'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    percolateIndex: {
      type: 'string',
      name: 'percolate_index'
    },
    percolateType: {
      type: 'string',
      name: 'percolate_type'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external'
      ],
      name: 'version_type'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/<%=id%>/_percolate/count',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        },
        id: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/<%=type%>/_percolate/count',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    }
  ],
  method: 'POST'
});

/**
 * Perform a [delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-delete.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Specific write consistency setting for the operation
 * @param {String} params.parent - ID of parent document
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.routing - Specific routing value
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api['delete'] = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    parent: {
      type: 'string'
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    routing: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external'
      ],
      name: 'version_type'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [deleteByQuery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-delete-by-query.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.analyzer - The analyzer to use for the query string
 * @param {String} params.consistency - Specific write consistency setting for the operation
 * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR)
 * @param {String} params.df - The field to use as default where no field prefix is given in the query string
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the operation; use `_all` to perform the operation on all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the operation
 */
api.deleteByQuery = ca({
  params: {
    analyzer: {
      type: 'string'
    },
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    defaultOperator: {
      type: 'enum',
      'default': 'OR',
      options: [
        'AND',
        'OR'
      ],
      name: 'default_operator'
    },
    df: {
      type: 'string'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    q: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_query',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_query',
      req: {
        index: {
          type: 'list'
        }
      }
    }
  ],
  method: 'DELETE'
});

/**
 * Perform a [exists](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String} params.routing - Specific routing value
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types)
 */
api.exists = ca({
  params: {
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    routing: {
      type: 'string'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'HEAD'
});

/**
 * Perform a [explain](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-explain.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.analyzeWildcard - Specify whether wildcards and prefix queries in the query string query should be analyzed (default: false)
 * @param {String} params.analyzer - The analyzer for the query string query
 * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR)
 * @param {String} params.df - The default field for query string query (default: _all)
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
 * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.explain = ca({
  params: {
    analyzeWildcard: {
      type: 'boolean',
      name: 'analyze_wildcard'
    },
    analyzer: {
      type: 'string'
    },
    defaultOperator: {
      type: 'enum',
      'default': 'OR',
      options: [
        'AND',
        'OR'
      ],
      name: 'default_operator'
    },
    df: {
      type: 'string'
    },
    fields: {
      type: 'list'
    },
    lenient: {
      type: 'boolean'
    },
    lowercaseExpandedTerms: {
      type: 'boolean',
      name: 'lowercase_expanded_terms'
    },
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    q: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_explain',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [get](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String} params.routing - Specific routing value
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types)
 */
api.get = ca({
  params: {
    fields: {
      type: 'list'
    },
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    routing: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external'
      ],
      name: 'version_type'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  }
});

/**
 * Perform a [getSource](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String} params.routing - Specific routing value
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document; use `_all` to fetch the first document matching the ID across all types
 */
api.getSource = ca({
  params: {
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    routing: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external'
      ],
      name: 'version_type'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_source',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  }
});

/**
 * Perform a [index](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-index_.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {String} params.parent - ID of the parent document
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.routing - Specific routing value
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.timestamp - Explicit timestamp for the document
 * @param {Duration} params.ttl - Expiration time for the document
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - Document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.index = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    opType: {
      type: 'enum',
      'default': 'index',
      options: [
        'index',
        'create'
      ],
      name: 'op_type'
    },
    parent: {
      type: 'string'
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    routing: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    },
    timestamp: {
      type: 'time'
    },
    ttl: {
      type: 'duration'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external'
      ],
      name: 'version_type'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/<%=id%>',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        },
        id: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/<%=type%>',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    }
  ],
  needBody: true,
  method: 'POST'
});

api.indices = function IndicesNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [indices.analyze](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-analyze.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.analyzer - The name of the analyzer to use
 * @param {String} params.field - Use the analyzer configured for this field (instead of passing the analyzer name)
 * @param {String, String[], Boolean} params.filters - A comma-separated list of filters to use for the analysis
 * @param {String} params.index - The name of the index to scope the operation
 * @param {Boolean} params.preferLocal - With `true`, specify that a local shard should be used if available, with `false`, use a random shard (default: true)
 * @param {String} params.text - The text on which the analysis should be performed (when request body is not used)
 * @param {String} params.tokenizer - The name of the tokenizer to use for the analysis
 * @param {String} [params.format=detailed] - Format of the output
 */
api.indices.prototype.analyze = ca({
  params: {
    analyzer: {
      type: 'string'
    },
    field: {
      type: 'string'
    },
    filters: {
      type: 'list'
    },
    index: {
      type: 'string'
    },
    preferLocal: {
      type: 'boolean',
      name: 'prefer_local'
    },
    text: {
      type: 'string'
    },
    tokenizer: {
      type: 'string'
    },
    format: {
      type: 'enum',
      'default': 'detailed',
      options: [
        'detailed',
        'text'
      ]
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_analyze',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_analyze'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.clearCache](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-clearcache.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.fieldData - Clear field data
 * @param {Boolean} params.fielddata - Clear field data
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to clear when using the `field_data` parameter (default: all)
 * @param {Boolean} params.filter - Clear filter caches
 * @param {Boolean} params.filterCache - Clear filter caches
 * @param {Boolean} params.filterKeys - A comma-separated list of keys to clear when using the `filter_cache` parameter (default: all)
 * @param {Boolean} params.id - Clear ID caches for parent/child
 * @param {Boolean} params.idCache - Clear ID caches for parent/child
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index name to limit the operation
 * @param {Boolean} params.recycler - Clear the recycler cache
 */
api.indices.prototype.clearCache = ca({
  params: {
    fieldData: {
      type: 'boolean',
      name: 'field_data'
    },
    fielddata: {
      type: 'boolean'
    },
    fields: {
      type: 'list'
    },
    filter: {
      type: 'boolean'
    },
    filterCache: {
      type: 'boolean',
      name: 'filter_cache'
    },
    filterKeys: {
      type: 'boolean',
      name: 'filter_keys'
    },
    id: {
      type: 'boolean'
    },
    idCache: {
      type: 'boolean',
      name: 'id_cache'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    index: {
      type: 'list'
    },
    recycler: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_cache/clear',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cache/clear'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.close](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-open-close.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.index - The name of the index
 */
api.indices.prototype.close = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  url: {
    fmt: '/<%=index%>/_close',
    req: {
      index: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [indices.create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-create-index.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String} params.index - The name of the index
 */
api.indices.prototype.create = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>',
    req: {
      index: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [indices.delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-delete-index.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to delete; use `_all` or `*` string to delete all indices
 */
api.indices.prototype['delete'] = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>',
    req: {
      index: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit timestamp for the document
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names (supports wildcards); use `_all` for all indices
 * @param {String, String[], Boolean} params.name - A comma-separated list of aliases to delete (supports wildcards); use `_all` to delete all aliases for the specified indices.
 */
api.indices.prototype.deleteAlias = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>/_alias/<%=name%>',
    req: {
      index: {
        type: 'list'
      },
      name: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-delete-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names (supports wildcards); use `_all` for all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to delete (supports wildcards); use `_all` to delete all document types in the specified indices.
 */
api.indices.prototype.deleteMapping = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/_mapping',
    req: {
      index: {
        type: 'list'
      },
      type: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String} params.name - The name of the template
 */
api.indices.prototype.deleteTemplate = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_template/<%=name%>',
    req: {
      name: {
        type: 'string'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.name - A comma-separated list of warmer names to delete (supports wildcards); use `_all` to delete all warmers in the specified indices. You must specify a name either in the uri or in the parameters.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to delete warmers from (supports wildcards); use `_all` to perform the operation on all indices.
 */
api.indices.prototype.deleteWarmer = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    name: {
      type: 'list'
    }
  },
  url: {
    fmt: '/<%=index%>/_warmer/<%=name%>',
    req: {
      index: {
        type: 'list'
      },
      name: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.exists](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to check
 */
api.indices.prototype.exists = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  url: {
    fmt: '/<%=index%>',
    req: {
      index: {
        type: 'list'
      }
    }
  },
  method: 'HEAD'
});

/**
 * Perform a [indices.existsAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open,closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases
 * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return
 */
api.indices.prototype.existsAlias = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': [
        'open',
        'closed'
      ],
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_alias/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_alias/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_alias',
      req: {
        index: {
          type: 'list'
        }
      }
    }
  ],
  method: 'HEAD'
});

/**
 * Perform a [indices.existsTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String} params.name - The name of the template
 */
api.indices.prototype.existsTemplate = ca({
  params: {
    local: {
      type: 'boolean'
    }
  },
  url: {
    fmt: '/_template/<%=name%>',
    req: {
      name: {
        type: 'string'
      }
    }
  },
  method: 'HEAD'
});

/**
 * Perform a [indices.existsType](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-types-exists.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` to check the types across all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to check
 */
api.indices.prototype.existsType = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>',
    req: {
      index: {
        type: 'list'
      },
      type: {
        type: 'list'
      }
    }
  },
  method: 'HEAD'
});

/**
 * Perform a [indices.flush](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-flush.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.force - Whether a flush should be forced even if it is not necessarily needed ie. if no changes will be committed to the index. This is useful if transaction log IDs should be incremented even if no uncommitted changes are present. (This setting can be considered as internal)
 * @param {Boolean} params.full - If set to true a new index writer is created and settings that have been changed related to the index writer will be refreshed. Note: if a full flush is required for a setting to take effect this will be part of the settings update process and it not required to be executed by the user. (This setting can be considered as internal)
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string for all indices
 */
api.indices.prototype.flush = ca({
  params: {
    force: {
      type: 'boolean'
    },
    full: {
      type: 'boolean'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_flush',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_flush'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.getAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases
 * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return
 */
api.indices.prototype.getAlias = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_alias/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_alias/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_alias',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_alias'
    }
  ]
});

/**
 * Perform a [indices.getAliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases
 * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to filter
 */
api.indices.prototype.getAliases = ca({
  params: {
    timeout: {
      type: 'time'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_aliases/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_aliases',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_aliases/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_aliases'
    }
  ]
});

/**
 * Perform a [indices.getFieldMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-field-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.includeDefaults - Whether the default mapping values should be returned as well
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types
 * @param {String, String[], Boolean} params.field - A comma-separated list of fields
 */
api.indices.prototype.getFieldMapping = ca({
  params: {
    includeDefaults: {
      type: 'boolean',
      name: 'include_defaults'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_mapping/<%=type%>/field/<%=field%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        },
        field: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mapping/field/<%=field%>',
      req: {
        index: {
          type: 'list'
        },
        field: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_mapping/<%=type%>/field/<%=field%>',
      req: {
        type: {
          type: 'list'
        },
        field: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_mapping/field/<%=field%>',
      req: {
        field: {
          type: 'list'
        }
      }
    }
  ]
});

/**
 * Perform a [indices.getMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types
 */
api.indices.prototype.getMapping = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_mapping/<%=type%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mapping',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_mapping/<%=type%>',
      req: {
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_mapping'
    }
  ]
});

/**
 * Perform a [indices.getSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open,closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.name - The name of the settings that should be included
 */
api.indices.prototype.getSettings = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': [
        'open',
        'closed'
      ],
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_settings/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_settings',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_settings/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_settings'
    }
  ]
});

/**
 * Perform a [indices.getTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String} params.name - The name of the template
 */
api.indices.prototype.getTemplate = ca({
  params: {
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/_template/<%=name%>',
      req: {
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_template'
    }
  ]
});

/**
 * Perform a [indices.getWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` to perform the operation on all indices
 * @param {String, String[], Boolean} params.name - The name of the warmer (supports wildcards); leave empty to get all warmers
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types
 */
api.indices.prototype.getWarmer = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_warmer',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_warmer/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_warmer'
    }
  ]
});

/**
 * Perform a [indices.open](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-open-close.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.index - The name of the index
 */
api.indices.prototype.open = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'closed',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  url: {
    fmt: '/<%=index%>/_open',
    req: {
      index: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [indices.optimize](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-optimize.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flush - Specify whether the index should be flushed after performing the operation (default: true)
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Number} params.maxNumSegments - The number of segments the index should be merged into (default: dynamic)
 * @param {Boolean} params.onlyExpungeDeletes - Specify whether the operation should only expunge deleted documents
 * @param {Anything} params.operationThreading - : ?
 * @param {Boolean} params.waitForMerge - Specify whether the request should block until the merge process is finished (default: true)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.optimize = ca({
  params: {
    flush: {
      type: 'boolean'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    maxNumSegments: {
      type: 'number',
      name: 'max_num_segments'
    },
    onlyExpungeDeletes: {
      type: 'boolean',
      name: 'only_expunge_deletes'
    },
    operationThreading: {
      name: 'operation_threading'
    },
    waitForMerge: {
      type: 'boolean',
      name: 'wait_for_merge'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_optimize',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_optimize'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.putAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit timestamp for the document
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names the alias should point to (supports wildcards); use `_all` or omit to perform the operation on all indices.
 * @param {String} params.name - The name of the alias to be created or updated
 */
api.indices.prototype.putAlias = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_alias/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_alias/<%=name%>',
      req: {
        name: {
          type: 'string'
        }
      }
    }
  ],
  method: 'PUT'
});

/**
 * Perform a [indices.putMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-put-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreConflicts - Specify whether to ignore conflicts while updating the mapping (default: false)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.
 * @param {String} params.type - The name of the document type
 */
api.indices.prototype.putMapping = ca({
  params: {
    ignoreConflicts: {
      type: 'boolean',
      name: 'ignore_conflicts'
    },
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_mapping/<%=type%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_mapping/<%=type%>',
      req: {
        type: {
          type: 'string'
        }
      }
    }
  ],
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.putSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-update-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.putSettings = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_settings',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_settings'
    }
  ],
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.putTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Number} params.order - The order for this template when merging multiple matching ones (higher numbers are merged later, overriding the lower numbers)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {String} params.name - The name of the template
 */
api.indices.prototype.putTemplate = ca({
  params: {
    order: {
      type: 'number'
    },
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    }
  },
  url: {
    fmt: '/_template/<%=name%>',
    req: {
      name: {
        type: 'string'
      }
    }
  },
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.putWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) in the search request to warm
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices in the search request to warm. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both, in the search request to warm.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to register the warmer for; use `_all` or omit to perform the operation on all indices
 * @param {String} params.name - The name of the warmer
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to register the warmer for; leave empty to perform the operation on all types
 */
api.indices.prototype.putWarmer = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_warmer/<%=name%>',
      req: {
        name: {
          type: 'string'
        }
      }
    }
  ],
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.refresh](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-refresh.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.force - Force a refresh even if not required
 * @param {Anything} params.operationThreading - : ?
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.refresh = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    force: {
      type: 'boolean',
      'default': false
    },
    operationThreading: {
      name: 'operation_threading'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_refresh',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_refresh'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.segments](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-segments.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {Anything} params.operationThreading - : ?
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.segments = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    human: {
      type: 'boolean',
      'default': false
    },
    operationThreading: {
      name: 'operation_threading'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_segments',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_segments'
    }
  ]
});

/**
 * Perform a [indices.snapshotIndex](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-gateway-snapshot.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string for all indices
 */
api.indices.prototype.snapshotIndex = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_gateway/snapshot',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_gateway/snapshot'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-stats.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards)
 * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields for `fielddata` index metric (supports wildcards)
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards)
 * @param {Boolean} params.groups - A comma-separated list of search groups for `search` index metric
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {String} [params.level=indices] - Return stats aggregated at cluster, index or shard level
 * @param {String, String[], Boolean} params.types - A comma-separated list of document types for the `indexing` index metric
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.metric - Limit the information returned the specific metrics.
 */
api.indices.prototype.stats = ca({
  params: {
    completionFields: {
      type: 'list',
      name: 'completion_fields'
    },
    fielddataFields: {
      type: 'list',
      name: 'fielddata_fields'
    },
    fields: {
      type: 'list'
    },
    groups: {
      type: 'boolean'
    },
    human: {
      type: 'boolean',
      'default': false
    },
    level: {
      type: 'enum',
      'default': 'indices',
      options: [
        'cluster',
        'indices',
        'shards'
      ]
    },
    types: {
      type: 'list'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_stats/<%=metric%>',
      req: {
        index: {
          type: 'list'
        },
        metric: {
          type: 'list',
          options: [
            '_all',
            'completion',
            'docs',
            'fielddata',
            'filter_cache',
            'flush',
            'get',
            'id_cache',
            'indexing',
            'merge',
            'percolate',
            'refresh',
            'search',
            'segments',
            'store',
            'warmer'
          ]
        }
      }
    },
    {
      fmt: '/_stats/<%=metric%>',
      req: {
        metric: {
          type: 'list',
          options: [
            '_all',
            'completion',
            'docs',
            'fielddata',
            'filter_cache',
            'flush',
            'get',
            'id_cache',
            'indexing',
            'merge',
            'percolate',
            'refresh',
            'search',
            'segments',
            'store',
            'warmer'
          ]
        }
      }
    },
    {
      fmt: '/<%=index%>/_stats',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_stats'
    }
  ]
});

/**
 * Perform a [indices.status](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-status.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {Anything} params.operationThreading - : ?
 * @param {Boolean} params.recovery - Return information about shard recovery
 * @param {Boolean} params.snapshot - : ?
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.status = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    human: {
      type: 'boolean',
      'default': false
    },
    operationThreading: {
      name: 'operation_threading'
    },
    recovery: {
      type: 'boolean'
    },
    snapshot: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_status',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_status'
    }
  ]
});

/**
 * Perform a [indices.updateAliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Request timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 */
api.indices.prototype.updateAliases = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_aliases'
  },
  needBody: true,
  method: 'POST'
});

/**
 * Perform a [indices.validateQuery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-validate.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.explain - Return detailed information about the error
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Anything} params.operationThreading - : ?
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types
 */
api.indices.prototype.validateQuery = ca({
  params: {
    explain: {
      type: 'boolean'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    operationThreading: {
      name: 'operation_threading'
    },
    source: {
      type: 'string'
    },
    q: {
      type: 'string'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_validate/query',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_validate/query',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_validate/query'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [info](http://www.elasticsearch.org/guide/) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 */
api.info = ca({
  url: {
    fmt: '/'
  }
});

/**
 * Perform a [mget](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-multi-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.mget = ca({
  params: {
    fields: {
      type: 'list'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_mget',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mget',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_mget'
    }
  ],
  needBody: true,
  method: 'POST'
});

/**
 * Perform a [mlt](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-more-like-this.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Number} params.boostTerms - The boost factor
 * @param {Number} params.maxDocFreq - The word occurrence frequency as count: words with higher occurrence in the corpus will be ignored
 * @param {Number} params.maxQueryTerms - The maximum query terms to be included in the generated query
 * @param {Number} params.maxWordLength - The minimum length of the word: longer words will be ignored
 * @param {Number} params.minDocFreq - The word occurrence frequency as count: words with lower occurrence in the corpus will be ignored
 * @param {Number} params.minTermFreq - The term frequency as percent: terms with lower occurence in the source document will be ignored
 * @param {Number} params.minWordLength - The minimum length of the word: shorter words will be ignored
 * @param {String, String[], Boolean} params.mltFields - Specific fields to perform the query against
 * @param {Number} params.percentTermsToMatch - How many terms have to match in order to consider the document a match (default: 0.3)
 * @param {String} params.routing - Specific routing value
 * @param {Number} params.searchFrom - The offset from which to return results
 * @param {String, String[], Boolean} params.searchIndices - A comma-separated list of indices to perform the query against (default: the index containing the document)
 * @param {String} params.searchQueryHint - The search query hint
 * @param {String} params.searchScroll - A scroll search request definition
 * @param {Number} params.searchSize - The number of documents to return (default: 10)
 * @param {String} params.searchSource - A specific search request definition (instead of using the request body)
 * @param {String} params.searchType - Specific search type (eg. `dfs_then_fetch`, `count`, etc)
 * @param {String, String[], Boolean} params.searchTypes - A comma-separated list of types to perform the query against (default: the same type as the document)
 * @param {String, String[], Boolean} params.stopWords - A list of stop words to be ignored
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types)
 */
api.mlt = ca({
  params: {
    boostTerms: {
      type: 'number',
      name: 'boost_terms'
    },
    maxDocFreq: {
      type: 'number',
      name: 'max_doc_freq'
    },
    maxQueryTerms: {
      type: 'number',
      name: 'max_query_terms'
    },
    maxWordLength: {
      type: 'number',
      name: 'max_word_length'
    },
    minDocFreq: {
      type: 'number',
      name: 'min_doc_freq'
    },
    minTermFreq: {
      type: 'number',
      name: 'min_term_freq'
    },
    minWordLength: {
      type: 'number',
      name: 'min_word_length'
    },
    mltFields: {
      type: 'list',
      name: 'mlt_fields'
    },
    percentTermsToMatch: {
      type: 'number',
      name: 'percent_terms_to_match'
    },
    routing: {
      type: 'string'
    },
    searchFrom: {
      type: 'number',
      name: 'search_from'
    },
    searchIndices: {
      type: 'list',
      name: 'search_indices'
    },
    searchQueryHint: {
      type: 'string',
      name: 'search_query_hint'
    },
    searchScroll: {
      type: 'string',
      name: 'search_scroll'
    },
    searchSize: {
      type: 'number',
      name: 'search_size'
    },
    searchSource: {
      type: 'string',
      name: 'search_source'
    },
    searchType: {
      type: 'string',
      name: 'search_type'
    },
    searchTypes: {
      type: 'list',
      name: 'search_types'
    },
    stopWords: {
      type: 'list',
      name: 'stop_words'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_mlt',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [mpercolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.index - The index of the document being count percolated to use as default
 * @param {String} params.type - The type of the document being percolated to use as default.
 */
api.mpercolate = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_mpercolate',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mpercolate',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_mpercolate'
    }
  ],
  needBody: true,
  bulkBody: true,
  method: 'POST'
});

/**
 * Perform a [msearch](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-multi-search.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.searchType - Search operation type
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to use as default
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to use as default
 */
api.msearch = ca({
  params: {
    searchType: {
      type: 'enum',
      options: [
        'query_then_fetch',
        'query_and_fetch',
        'dfs_query_then_fetch',
        'dfs_query_and_fetch',
        'count',
        'scan'
      ],
      name: 'search_type'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_msearch',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_msearch',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_msearch'
    }
  ],
  needBody: true,
  bulkBody: true,
  method: 'POST'
});

/**
 * Perform a [mtermvectors](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-multi-termvectors.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.ids - A comma-separated list of documents ids. You must define ids as parameter or set "ids" or "docs" in the request body
 * @param {Boolean} params.termStatistics - Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {Boolean} [params.fieldStatistics=true] - Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {Boolean} [params.offsets=true] - Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {Boolean} [params.positions=true] - Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {Boolean} [params.payloads=true] - Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {String} params.routing - Specific routing value. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {String} params.parent - Parent id of documents. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {String} params.index - The index in which the document resides.
 * @param {String} params.type - The type of the document.
 * @param {String} params.id - The id of the document.
 */
api.mtermvectors = ca({
  params: {
    ids: {
      type: 'list',
      required: false
    },
    termStatistics: {
      type: 'boolean',
      'default': false,
      required: false,
      name: 'term_statistics'
    },
    fieldStatistics: {
      type: 'boolean',
      'default': true,
      required: false,
      name: 'field_statistics'
    },
    fields: {
      type: 'list',
      required: false
    },
    offsets: {
      type: 'boolean',
      'default': true,
      required: false
    },
    positions: {
      type: 'boolean',
      'default': true,
      required: false
    },
    payloads: {
      type: 'boolean',
      'default': true,
      required: false
    },
    preference: {
      type: 'string',
      required: false
    },
    routing: {
      type: 'string',
      required: false
    },
    parent: {
      type: 'string',
      required: false
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_mtermvectors',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mtermvectors',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_mtermvectors'
    }
  ],
  method: 'POST'
});

api.nodes = function NodesNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [nodes.hotThreads](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-hot-threads.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.interval - The interval for the second sampling of threads
 * @param {Number} params.snapshots - Number of samples of thread stacktrace (default: 10)
 * @param {Number} params.threads - Specify the number of threads to provide information for (default: 3)
 * @param {String} params.type - The type to sample (default: cpu)
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
 */
api.nodes.prototype.hotThreads = ca({
  params: {
    interval: {
      type: 'time'
    },
    snapshots: {
      type: 'number'
    },
    threads: {
      type: 'number'
    },
    type: {
      type: 'enum',
      options: [
        'cpu',
        'wait',
        'block'
      ]
    }
  },
  urls: [
    {
      fmt: '/_nodes/<%=nodeId%>/hotthreads',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_nodes/hotthreads'
    }
  ]
});

/**
 * Perform a [nodes.info](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-info.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
 * @param {String, String[], Boolean} params.metric - A comma-separated list of metrics you wish returned. Leave empty to return all.
 */
api.nodes.prototype.info = ca({
  params: {
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    },
    human: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_nodes/<%=nodeId%>/<%=metric%>',
      req: {
        nodeId: {
          type: 'list'
        },
        metric: {
          type: 'list',
          options: [
            'settings',
            'os',
            'process',
            'jvm',
            'thread_pool',
            'network',
            'transport',
            'http',
            'plugin'
          ]
        }
      }
    },
    {
      fmt: '/_nodes/<%=nodeId%>',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_nodes/<%=metric%>',
      req: {
        metric: {
          type: 'list',
          options: [
            'settings',
            'os',
            'process',
            'jvm',
            'thread_pool',
            'network',
            'transport',
            'http',
            'plugin'
          ]
        }
      }
    },
    {
      fmt: '/_nodes'
    }
  ]
});

/**
 * Perform a [nodes.shutdown](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-shutdown.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.delay - Set the delay for the operation (default: 1s)
 * @param {Boolean} params.exit - Exit the JVM as well (default: true)
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to perform the operation on; use `_local` to perform the operation on the node you're connected to, leave empty to perform the operation on all nodes
 */
api.nodes.prototype.shutdown = ca({
  params: {
    delay: {
      type: 'time'
    },
    exit: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/_cluster/nodes/<%=nodeId%>/_shutdown',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_shutdown'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [nodes.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-stats.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards)
 * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields for `fielddata` index metric (supports wildcards)
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards)
 * @param {Boolean} params.groups - A comma-separated list of search groups for `search` index metric
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {String} [params.level=node] - Return indices stats aggregated at node, index or shard level
 * @param {String, String[], Boolean} params.types - A comma-separated list of document types for the `indexing` index metric
 * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics
 * @param {String, String[], Boolean} params.indexMetric - Limit the information returned for `indices` metric to the specific index metrics. Isn't used if `indices` (or `all`) metric isn't specified.
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
 */
api.nodes.prototype.stats = ca({
  params: {
    completionFields: {
      type: 'list',
      name: 'completion_fields'
    },
    fielddataFields: {
      type: 'list',
      name: 'fielddata_fields'
    },
    fields: {
      type: 'list'
    },
    groups: {
      type: 'boolean'
    },
    human: {
      type: 'boolean',
      'default': false
    },
    level: {
      type: 'enum',
      'default': 'node',
      options: [
        'node',
        'indices',
        'shards'
      ]
    },
    types: {
      type: 'list'
    }
  },
  urls: [
    {
      fmt: '/_nodes/<%=nodeId%>/stats/<%=metric%>/<%=indexMetric%>',
      req: {
        nodeId: {
          type: 'list'
        },
        metric: {
          type: 'list',
          options: [
            '_all',
            'breaker',
            'fs',
            'http',
            'indices',
            'jvm',
            'network',
            'os',
            'process',
            'thread_pool',
            'transport'
          ]
        },
        indexMetric: {
          type: 'list',
          options: [
            '_all',
            'completion',
            'docs',
            'fielddata',
            'filter_cache',
            'flush',
            'get',
            'id_cache',
            'indexing',
            'merge',
            'percolate',
            'refresh',
            'search',
            'segments',
            'store',
            'warmer'
          ]
        }
      }
    },
    {
      fmt: '/_nodes/<%=nodeId%>/stats/<%=metric%>',
      req: {
        nodeId: {
          type: 'list'
        },
        metric: {
          type: 'list',
          options: [
            '_all',
            'breaker',
            'fs',
            'http',
            'indices',
            'jvm',
            'network',
            'os',
            'process',
            'thread_pool',
            'transport'
          ]
        }
      }
    },
    {
      fmt: '/_nodes/stats/<%=metric%>/<%=indexMetric%>',
      req: {
        metric: {
          type: 'list',
          options: [
            '_all',
            'breaker',
            'fs',
            'http',
            'indices',
            'jvm',
            'network',
            'os',
            'process',
            'thread_pool',
            'transport'
          ]
        },
        indexMetric: {
          type: 'list',
          options: [
            '_all',
            'completion',
            'docs',
            'fielddata',
            'filter_cache',
            'flush',
            'get',
            'id_cache',
            'indexing',
            'merge',
            'percolate',
            'refresh',
            'search',
            'segments',
            'store',
            'warmer'
          ]
        }
      }
    },
    {
      fmt: '/_nodes/<%=nodeId%>/stats',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_nodes/stats/<%=metric%>',
      req: {
        metric: {
          type: 'list',
          options: [
            '_all',
            'breaker',
            'fs',
            'http',
            'indices',
            'jvm',
            'network',
            'os',
            'process',
            'thread_pool',
            'transport'
          ]
        }
      }
    },
    {
      fmt: '/_nodes/stats'
    }
  ]
});

/**
 * Perform a [percolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.percolateIndex - The index to percolate the document into. Defaults to index.
 * @param {String} params.percolateType - The type to percolate document into. Defaults to type.
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.index - The index of the document being percolated.
 * @param {String} params.type - The type of the document being percolated.
 * @param {String} params.id - Substitute the document in the request body with a document that is known by the specified id. On top of the id, the index and type parameter will be used to retrieve the document from within the cluster.
 */
api.percolate = ca({
  params: {
    routing: {
      type: 'list'
    },
    preference: {
      type: 'string'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    percolateIndex: {
      type: 'string',
      name: 'percolate_index'
    },
    percolateType: {
      type: 'string',
      name: 'percolate_type'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external'
      ],
      name: 'version_type'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/<%=id%>/_percolate',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        },
        id: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/<%=type%>/_percolate',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    }
  ],
  method: 'POST'
});

/**
 * Perform a [ping](http://www.elasticsearch.org/guide/) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 */
api.ping = ca({
  url: {
    fmt: '/'
  },
  requestTimeout: 100,
  method: 'HEAD'
});

/**
 * Perform a [scroll](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-request-scroll.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search
 * @param {String} params.scrollId - The scroll ID
 */
api.scroll = ca({
  params: {
    scroll: {
      type: 'duration'
    },
    scrollId: {
      type: 'string',
      name: 'scroll_id'
    }
  },
  urls: [
    {
      fmt: '/_search/scroll/<%=scrollId%>',
      req: {
        scrollId: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_search/scroll'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [search](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-search.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.analyzer - The analyzer to use for the query string
 * @param {Boolean} params.analyzeWildcard - Specify whether wildcard and prefix queries should be analyzed (default: false)
 * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR)
 * @param {String} params.df - The field to use as default where no field prefix is given in the query string
 * @param {Boolean} params.explain - Specify whether to return detailed information about score computation as part of a hit
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return as part of a hit
 * @param {Number} params.from - Starting offset (default: 0)
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String, String[], Boolean} params.indicesBoost - Comma-separated list of index boosts
 * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
 * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values
 * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search
 * @param {String} params.searchType - Search operation type
 * @param {Number} params.size - Number of hits to return (default: 10)
 * @param {String, String[], Boolean} params.sort - A comma-separated list of <field>:<direction> pairs
 * @param {String} params.source - The URL-encoded request definition using the Query DSL (instead of using request body)
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {String, String[], Boolean} params.stats - Specific 'tag' of the request for logging and statistical purposes
 * @param {String} params.suggestField - Specify which field to use for suggestions
 * @param {String} [params.suggestMode=missing] - Specify suggest mode
 * @param {Number} params.suggestSize - How many suggestions to return in response
 * @param {Text} params.suggestText - The source text for which the suggestions should be returned
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Boolean} params.version - Specify whether to return document version as part of a hit
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to search; leave empty to perform the operation on all types
 */
api.search = ca({
  params: {
    analyzer: {
      type: 'string'
    },
    analyzeWildcard: {
      type: 'boolean',
      name: 'analyze_wildcard'
    },
    defaultOperator: {
      type: 'enum',
      'default': 'OR',
      options: [
        'AND',
        'OR'
      ],
      name: 'default_operator'
    },
    df: {
      type: 'string'
    },
    explain: {
      type: 'boolean'
    },
    fields: {
      type: 'list'
    },
    from: {
      type: 'number'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    indicesBoost: {
      type: 'list',
      name: 'indices_boost'
    },
    lenient: {
      type: 'boolean'
    },
    lowercaseExpandedTerms: {
      type: 'boolean',
      name: 'lowercase_expanded_terms'
    },
    preference: {
      type: 'string'
    },
    q: {
      type: 'string'
    },
    routing: {
      type: 'list'
    },
    scroll: {
      type: 'duration'
    },
    searchType: {
      type: 'enum',
      options: [
        'query_then_fetch',
        'query_and_fetch',
        'dfs_query_then_fetch',
        'dfs_query_and_fetch',
        'count',
        'scan'
      ],
      name: 'search_type'
    },
    size: {
      type: 'number'
    },
    sort: {
      type: 'list'
    },
    source: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    },
    stats: {
      type: 'list'
    },
    suggestField: {
      type: 'string',
      name: 'suggest_field'
    },
    suggestMode: {
      type: 'enum',
      'default': 'missing',
      options: [
        'missing',
        'popular',
        'always'
      ],
      name: 'suggest_mode'
    },
    suggestSize: {
      type: 'number',
      name: 'suggest_size'
    },
    suggestText: {
      type: 'text',
      name: 'suggest_text'
    },
    timeout: {
      type: 'time'
    },
    version: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_search',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_search',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_search'
    }
  ],
  method: 'POST'
});

api.snapshot = function SnapshotNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [snapshot.create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Boolean} params.waitForCompletion - Should this request wait until the operation has completed before returning
 * @param {String} params.repository - A repository name
 * @param {String} params.snapshot - A snapshot name
 */
api.snapshot.prototype.create = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    waitForCompletion: {
      type: 'boolean',
      'default': false,
      name: 'wait_for_completion'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>/<%=snapshot%>',
    req: {
      repository: {
        type: 'string'
      },
      snapshot: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [snapshot.createRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {String} params.repository - A repository name
 */
api.snapshot.prototype.createRepository = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    timeout: {
      type: 'time'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>',
    req: {
      repository: {
        type: 'string'
      }
    }
  },
  needBody: true,
  method: 'POST'
});

/**
 * Perform a [snapshot.delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String} params.repository - A repository name
 * @param {String} params.snapshot - A snapshot name
 */
api.snapshot.prototype['delete'] = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>/<%=snapshot%>',
    req: {
      repository: {
        type: 'string'
      },
      snapshot: {
        type: 'string'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [snapshot.deleteRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {String, String[], Boolean} params.repository - A comma-separated list of repository names
 */
api.snapshot.prototype.deleteRepository = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    timeout: {
      type: 'time'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>',
    req: {
      repository: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [snapshot.get](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String} params.repository - A repository name
 * @param {String, String[], Boolean} params.snapshot - A comma-separated list of snapshot names
 */
api.snapshot.prototype.get = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>/<%=snapshot%>',
    req: {
      repository: {
        type: 'string'
      },
      snapshot: {
        type: 'list'
      }
    }
  }
});

/**
 * Perform a [snapshot.getRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.repository - A comma-separated list of repository names
 */
api.snapshot.prototype.getRepository = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/_snapshot/<%=repository%>',
      req: {
        repository: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_snapshot'
    }
  ]
});

/**
 * Perform a [snapshot.restore](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Boolean} params.waitForCompletion - Should this request wait until the operation has completed before returning
 * @param {String} params.repository - A repository name
 * @param {String} params.snapshot - A snapshot name
 */
api.snapshot.prototype.restore = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    waitForCompletion: {
      type: 'boolean',
      'default': false,
      name: 'wait_for_completion'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>/<%=snapshot%>/_restore',
    req: {
      repository: {
        type: 'string'
      },
      snapshot: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [suggest](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-search.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded request definition (instead of using request body)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices
 */
api.suggest = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    preference: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_suggest',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_suggest'
    }
  ],
  needBody: true,
  method: 'POST'
});

/**
 * Perform a [termvector](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-termvectors.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.termStatistics - Specifies if total term frequency and document frequency should be returned.
 * @param {Boolean} [params.fieldStatistics=true] - Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned.
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return.
 * @param {Boolean} [params.offsets=true] - Specifies if term offsets should be returned.
 * @param {Boolean} [params.positions=true] - Specifies if term positions should be returned.
 * @param {Boolean} [params.payloads=true] - Specifies if term payloads should be returned.
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random).
 * @param {String} params.routing - Specific routing value.
 * @param {String} params.parent - Parent id of documents.
 * @param {String} params.index - The index in which the document resides.
 * @param {String} params.type - The type of the document.
 * @param {String} params.id - The id of the document.
 */
api.termvector = ca({
  params: {
    termStatistics: {
      type: 'boolean',
      'default': false,
      required: false,
      name: 'term_statistics'
    },
    fieldStatistics: {
      type: 'boolean',
      'default': true,
      required: false,
      name: 'field_statistics'
    },
    fields: {
      type: 'list',
      required: false
    },
    offsets: {
      type: 'boolean',
      'default': true,
      required: false
    },
    positions: {
      type: 'boolean',
      'default': true,
      required: false
    },
    payloads: {
      type: 'boolean',
      'default': true,
      required: false
    },
    preference: {
      type: 'string',
      required: false
    },
    routing: {
      type: 'string',
      required: false
    },
    parent: {
      type: 'string',
      required: false
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_termvector',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [update](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-update.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {String} params.lang - The script language (default: mvel)
 * @param {String} params.parent - ID of the parent document
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {Number} params.retryOnConflict - Specify how many times should the operation be retried when a conflict occurs (default: 0)
 * @param {String} params.routing - Specific routing value
 * @param {Anything} params.script - The URL-encoded script definition (instead of using request body)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.timestamp - Explicit timestamp for the document
 * @param {Duration} params.ttl - Expiration time for the document
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - Document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.update = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    fields: {
      type: 'list'
    },
    lang: {
      type: 'string'
    },
    parent: {
      type: 'string'
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    retryOnConflict: {
      type: 'number',
      name: 'retry_on_conflict'
    },
    routing: {
      type: 'string'
    },
    script: {},
    timeout: {
      type: 'time'
    },
    timestamp: {
      type: 'time'
    },
    ttl: {
      type: 'duration'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external'
      ],
      name: 'version_type'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_update',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-index_.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {String} params.parent - ID of the parent document
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.routing - Specific routing value
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.timestamp - Explicit timestamp for the document
 * @param {Duration} params.ttl - Expiration time for the document
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - Document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.create = ca.proxy(api.index, {
  transform: function (params) {
    params.op_type = 'create';
  }
});
},{"../client_action":195}],192:[function(require,module,exports){
/* jshint maxlen: false */

var ca = require('../client_action');
var api = module.exports = {};

api._namespaces = ['cat', 'cluster', 'indices', 'nodes', 'snapshot'];

/**
 * Perform a [bulk](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-bulk.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Explicitely set the replication type
 * @param {String} params.routing - Specific routing value
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {String} params.type - Default document type for items which don't provide one
 * @param {String} params.index - Default index for items which don't provide one
 */
api.bulk = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    routing: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    },
    type: {
      type: 'string'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_bulk',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_bulk',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_bulk'
    }
  ],
  needBody: true,
  bulkBody: true,
  method: 'POST'
});

api.cat = function CatNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [cat.aliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return
 */
api.cat.prototype.aliases = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/aliases/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/aliases'
    }
  ]
});

/**
 * Perform a [cat.allocation](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-allocation.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.bytes - The unit in which to display byte values
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information
 */
api.cat.prototype.allocation = ca({
  params: {
    bytes: {
      type: 'enum',
      options: [
        'b',
        'k',
        'm',
        'g'
      ]
    },
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/allocation/<%=nodeId%>',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/allocation'
    }
  ]
});

/**
 * Perform a [cat.count](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-count.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information
 */
api.cat.prototype.count = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/count/<%=index%>',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/count'
    }
  ]
});

/**
 * Perform a [cat.health](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-health.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} [params.ts=true] - Set to false to disable timestamping
 * @param {Boolean} params.v - Verbose mode. Display column headers
 */
api.cat.prototype.health = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    ts: {
      type: 'boolean',
      'default': true
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  url: {
    fmt: '/_cat/health'
  }
});

/**
 * Perform a [cat.help](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.help - Return help information
 */
api.cat.prototype.help = ca({
  params: {
    help: {
      type: 'boolean',
      'default': false
    }
  },
  url: {
    fmt: '/_cat'
  }
});

/**
 * Perform a [cat.indices](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-indices.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.bytes - The unit in which to display byte values
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.pri - Set to true to return stats only for primary shards
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information
 */
api.cat.prototype.indices = ca({
  params: {
    bytes: {
      type: 'enum',
      options: [
        'b',
        'k',
        'm',
        'g'
      ]
    },
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    pri: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/indices/<%=index%>',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/indices'
    }
  ]
});

/**
 * Perform a [cat.master](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-master.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 */
api.cat.prototype.master = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  url: {
    fmt: '/_cat/master'
  }
});

/**
 * Perform a [cat.nodes](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-nodes.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 */
api.cat.prototype.nodes = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  url: {
    fmt: '/_cat/nodes'
  }
});

/**
 * Perform a [cat.pendingTasks](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-pending-tasks.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 */
api.cat.prototype.pendingTasks = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  url: {
    fmt: '/_cat/pending_tasks'
  }
});

/**
 * Perform a [cat.plugins](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-plugins.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 */
api.cat.prototype.plugins = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  url: {
    fmt: '/_cat/plugins'
  }
});

/**
 * Perform a [cat.recovery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-recovery.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.bytes - The unit in which to display byte values
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information
 */
api.cat.prototype.recovery = ca({
  params: {
    bytes: {
      type: 'enum',
      options: [
        'b',
        'k',
        'm',
        'g'
      ]
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/recovery/<%=index%>',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/recovery'
    }
  ]
});

/**
 * Perform a [cat.shards](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-shards.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information
 */
api.cat.prototype.shards = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cat/shards/<%=index%>',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cat/shards'
    }
  ]
});

/**
 * Perform a [cat.threadPool](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-thread-pool.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display
 * @param {Boolean} params.help - Return help information
 * @param {Boolean} params.v - Verbose mode. Display column headers
 * @param {Boolean} params.fullId - Enables displaying the complete node ids
 */
api.cat.prototype.threadPool = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    h: {
      type: 'list'
    },
    help: {
      type: 'boolean',
      'default': false
    },
    v: {
      type: 'boolean',
      'default': false
    },
    fullId: {
      type: 'boolean',
      'default': false,
      name: 'full_id'
    }
  },
  url: {
    fmt: '/_cat/thread_pool'
  }
});

/**
 * Perform a [clearScroll](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-request-scroll.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.scrollId - A comma-separated list of scroll IDs to clear
 */
api.clearScroll = ca({
  url: {
    fmt: '/_search/scroll/<%=scrollId%>',
    req: {
      scrollId: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

api.cluster = function ClusterNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [cluster.getSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-update-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Date, Number} params.timeout - Explicit operation timeout
 */
api.cluster.prototype.getSettings = ca({
  params: {
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    timeout: {
      type: 'time'
    }
  },
  url: {
    fmt: '/_cluster/settings'
  }
});

/**
 * Perform a [cluster.health](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-health.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} [params.level=cluster] - Specify the level of detail for returned information
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Number} params.waitForActiveShards - Wait until the specified number of shards is active
 * @param {String} params.waitForNodes - Wait until the specified number of nodes is available
 * @param {Number} params.waitForRelocatingShards - Wait until the specified number of relocating shards is finished
 * @param {String} params.waitForStatus - Wait until cluster is in a specific state
 * @param {String} params.index - Limit the information returned to a specific index
 */
api.cluster.prototype.health = ca({
  params: {
    level: {
      type: 'enum',
      'default': 'cluster',
      options: [
        'cluster',
        'indices',
        'shards'
      ]
    },
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    timeout: {
      type: 'time'
    },
    waitForActiveShards: {
      type: 'number',
      name: 'wait_for_active_shards'
    },
    waitForNodes: {
      type: 'string',
      name: 'wait_for_nodes'
    },
    waitForRelocatingShards: {
      type: 'number',
      name: 'wait_for_relocating_shards'
    },
    waitForStatus: {
      type: 'enum',
      'default': null,
      options: [
        'green',
        'yellow',
        'red'
      ],
      name: 'wait_for_status'
    }
  },
  urls: [
    {
      fmt: '/_cluster/health/<%=index%>',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_cluster/health'
    }
  ]
});

/**
 * Perform a [cluster.pendingTasks](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-pending.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 */
api.cluster.prototype.pendingTasks = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_cluster/pending_tasks'
  }
});

/**
 * Perform a [cluster.putSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-update-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 */
api.cluster.prototype.putSettings = ca({
  params: {
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    }
  },
  url: {
    fmt: '/_cluster/settings'
  },
  method: 'PUT'
});

/**
 * Perform a [cluster.reroute](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-reroute.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.dryRun - Simulate the operation only and return the resulting state
 * @param {Boolean} params.explain - Return an explanation of why the commands can or cannot be executed
 * @param {Boolean} params.filterMetadata - Don't return cluster state metadata (default: false)
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Date, Number} params.timeout - Explicit operation timeout
 */
api.cluster.prototype.reroute = ca({
  params: {
    dryRun: {
      type: 'boolean',
      name: 'dry_run'
    },
    explain: {
      type: 'boolean'
    },
    filterMetadata: {
      type: 'boolean',
      name: 'filter_metadata'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    timeout: {
      type: 'time'
    }
  },
  url: {
    fmt: '/_cluster/reroute'
  },
  method: 'POST'
});

/**
 * Perform a [cluster.state](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-state.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.indexTemplates - A comma separated list to return specific index templates when returning metadata
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics
 */
api.cluster.prototype.state = ca({
  params: {
    local: {
      type: 'boolean'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    indexTemplates: {
      type: 'list',
      name: 'index_templates'
    },
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    }
  },
  urls: [
    {
      fmt: '/_cluster/state/<%=metric%>/<%=index%>',
      req: {
        metric: {
          type: 'list',
          options: [
            '_all',
            'blocks',
            'metadata',
            'nodes',
            'routing_table',
            'master_node',
            'version'
          ]
        },
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cluster/state/<%=metric%>',
      req: {
        metric: {
          type: 'list',
          options: [
            '_all',
            'blocks',
            'metadata',
            'nodes',
            'routing_table',
            'master_node',
            'version'
          ]
        }
      }
    },
    {
      fmt: '/_cluster/state'
    }
  ]
});

/**
 * Perform a [cluster.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-stats.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
 */
api.cluster.prototype.stats = ca({
  params: {
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    },
    human: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_cluster/stats/nodes/<%=nodeId%>',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cluster/stats'
    }
  ]
});

/**
 * Perform a [count](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-count.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Number} params.minScore - Include only documents with a specific `_score` value in the result
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the results
 * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the results
 */
api.count = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    minScore: {
      type: 'number',
      name: 'min_score'
    },
    preference: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_count',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_count',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_count'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [countPercolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.percolateIndex - The index to count percolate the document into. Defaults to index.
 * @param {String} params.percolateType - The type to count percolate document into. Defaults to type.
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.index - The index of the document being count percolated.
 * @param {String} params.type - The type of the document being count percolated.
 * @param {String} params.id - Substitute the document in the request body with a document that is known by the specified id. On top of the id, the index and type parameter will be used to retrieve the document from within the cluster.
 */
api.countPercolate = ca({
  params: {
    routing: {
      type: 'list'
    },
    preference: {
      type: 'string'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    percolateIndex: {
      type: 'string',
      name: 'percolate_index'
    },
    percolateType: {
      type: 'string',
      name: 'percolate_type'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external',
        'external_gte',
        'force'
      ],
      name: 'version_type'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/<%=id%>/_percolate/count',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        },
        id: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/<%=type%>/_percolate/count',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    }
  ],
  method: 'POST'
});

/**
 * Perform a [delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-delete.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Specific write consistency setting for the operation
 * @param {String} params.parent - ID of parent document
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.routing - Specific routing value
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api['delete'] = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    parent: {
      type: 'string'
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    routing: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external',
        'external_gte',
        'force'
      ],
      name: 'version_type'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [deleteByQuery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-delete-by-query.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.analyzer - The analyzer to use for the query string
 * @param {String} params.consistency - Specific write consistency setting for the operation
 * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR)
 * @param {String} params.df - The field to use as default where no field prefix is given in the query string
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the operation; use `_all` to perform the operation on all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the operation
 */
api.deleteByQuery = ca({
  params: {
    analyzer: {
      type: 'string'
    },
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    defaultOperator: {
      type: 'enum',
      'default': 'OR',
      options: [
        'AND',
        'OR'
      ],
      name: 'default_operator'
    },
    df: {
      type: 'string'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    q: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_query',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_query',
      req: {
        index: {
          type: 'list'
        }
      }
    }
  ],
  method: 'DELETE'
});

/**
 * Perform a [exists](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String} params.routing - Specific routing value
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types)
 */
api.exists = ca({
  params: {
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    routing: {
      type: 'string'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'HEAD'
});

/**
 * Perform a [explain](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-explain.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.analyzeWildcard - Specify whether wildcards and prefix queries in the query string query should be analyzed (default: false)
 * @param {String} params.analyzer - The analyzer for the query string query
 * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR)
 * @param {String} params.df - The default field for query string query (default: _all)
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
 * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.explain = ca({
  params: {
    analyzeWildcard: {
      type: 'boolean',
      name: 'analyze_wildcard'
    },
    analyzer: {
      type: 'string'
    },
    defaultOperator: {
      type: 'enum',
      'default': 'OR',
      options: [
        'AND',
        'OR'
      ],
      name: 'default_operator'
    },
    df: {
      type: 'string'
    },
    fields: {
      type: 'list'
    },
    lenient: {
      type: 'boolean'
    },
    lowercaseExpandedTerms: {
      type: 'boolean',
      name: 'lowercase_expanded_terms'
    },
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    q: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_explain',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [get](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String} params.routing - Specific routing value
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types)
 */
api.get = ca({
  params: {
    fields: {
      type: 'list'
    },
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    routing: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external',
        'external_gte',
        'force'
      ],
      name: 'version_type'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  }
});

/**
 * Perform a [getSource](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.parent - The ID of the parent document
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String} params.routing - Specific routing value
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document; use `_all` to fetch the first document matching the ID across all types
 */
api.getSource = ca({
  params: {
    parent: {
      type: 'string'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    routing: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external',
        'external_gte',
        'force'
      ],
      name: 'version_type'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_source',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  }
});

/**
 * Perform a [index](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-index_.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {String} params.parent - ID of the parent document
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.routing - Specific routing value
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.timestamp - Explicit timestamp for the document
 * @param {Duration} params.ttl - Expiration time for the document
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - Document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.index = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    opType: {
      type: 'enum',
      'default': 'index',
      options: [
        'index',
        'create'
      ],
      name: 'op_type'
    },
    parent: {
      type: 'string'
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    routing: {
      type: 'string'
    },
    timeout: {
      type: 'time'
    },
    timestamp: {
      type: 'time'
    },
    ttl: {
      type: 'duration'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external',
        'external_gte',
        'force'
      ],
      name: 'version_type'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/<%=id%>',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        },
        id: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/<%=type%>',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    }
  ],
  needBody: true,
  method: 'POST'
});

api.indices = function IndicesNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [indices.analyze](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-analyze.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.analyzer - The name of the analyzer to use
 * @param {String} params.field - Use the analyzer configured for this field (instead of passing the analyzer name)
 * @param {String, String[], Boolean} params.filters - A comma-separated list of filters to use for the analysis
 * @param {String} params.index - The name of the index to scope the operation
 * @param {Boolean} params.preferLocal - With `true`, specify that a local shard should be used if available, with `false`, use a random shard (default: true)
 * @param {String} params.text - The text on which the analysis should be performed (when request body is not used)
 * @param {String} params.tokenizer - The name of the tokenizer to use for the analysis
 * @param {String} [params.format=detailed] - Format of the output
 */
api.indices.prototype.analyze = ca({
  params: {
    analyzer: {
      type: 'string'
    },
    field: {
      type: 'string'
    },
    filters: {
      type: 'list'
    },
    index: {
      type: 'string'
    },
    preferLocal: {
      type: 'boolean',
      name: 'prefer_local'
    },
    text: {
      type: 'string'
    },
    tokenizer: {
      type: 'string'
    },
    format: {
      type: 'enum',
      'default': 'detailed',
      options: [
        'detailed',
        'text'
      ]
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_analyze',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_analyze'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.clearCache](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-clearcache.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.fieldData - Clear field data
 * @param {Boolean} params.fielddata - Clear field data
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to clear when using the `field_data` parameter (default: all)
 * @param {Boolean} params.filter - Clear filter caches
 * @param {Boolean} params.filterCache - Clear filter caches
 * @param {Boolean} params.filterKeys - A comma-separated list of keys to clear when using the `filter_cache` parameter (default: all)
 * @param {Boolean} params.id - Clear ID caches for parent/child
 * @param {Boolean} params.idCache - Clear ID caches for parent/child
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index name to limit the operation
 * @param {Boolean} params.recycler - Clear the recycler cache
 */
api.indices.prototype.clearCache = ca({
  params: {
    fieldData: {
      type: 'boolean',
      name: 'field_data'
    },
    fielddata: {
      type: 'boolean'
    },
    fields: {
      type: 'list'
    },
    filter: {
      type: 'boolean'
    },
    filterCache: {
      type: 'boolean',
      name: 'filter_cache'
    },
    filterKeys: {
      type: 'boolean',
      name: 'filter_keys'
    },
    id: {
      type: 'boolean'
    },
    idCache: {
      type: 'boolean',
      name: 'id_cache'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    index: {
      type: 'list'
    },
    recycler: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_cache/clear',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_cache/clear'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.close](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-open-close.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.index - The name of the index
 */
api.indices.prototype.close = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  url: {
    fmt: '/<%=index%>/_close',
    req: {
      index: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [indices.create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-create-index.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String} params.index - The name of the index
 */
api.indices.prototype.create = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>',
    req: {
      index: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [indices.delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-delete-index.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to delete; use `_all` or `*` string to delete all indices
 */
api.indices.prototype['delete'] = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>',
    req: {
      index: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit timestamp for the document
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names (supports wildcards); use `_all` for all indices
 * @param {String, String[], Boolean} params.name - A comma-separated list of aliases to delete (supports wildcards); use `_all` to delete all aliases for the specified indices.
 */
api.indices.prototype.deleteAlias = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>/_alias/<%=name%>',
    req: {
      index: {
        type: 'list'
      },
      name: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-delete-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names (supports wildcards); use `_all` for all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to delete (supports wildcards); use `_all` to delete all document types in the specified indices.
 */
api.indices.prototype.deleteMapping = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/_mapping',
    req: {
      index: {
        type: 'list'
      },
      type: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String} params.name - The name of the template
 */
api.indices.prototype.deleteTemplate = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_template/<%=name%>',
    req: {
      name: {
        type: 'string'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.deleteWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.name - A comma-separated list of warmer names to delete (supports wildcards); use `_all` to delete all warmers in the specified indices. You must specify a name either in the uri or in the parameters.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to delete warmers from (supports wildcards); use `_all` to perform the operation on all indices.
 */
api.indices.prototype.deleteWarmer = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    name: {
      type: 'list'
    }
  },
  url: {
    fmt: '/<%=index%>/_warmer/<%=name%>',
    req: {
      index: {
        type: 'list'
      },
      name: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [indices.exists](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of indices to check
 */
api.indices.prototype.exists = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  url: {
    fmt: '/<%=index%>',
    req: {
      index: {
        type: 'list'
      }
    }
  },
  method: 'HEAD'
});

/**
 * Perform a [indices.existsAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open,closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases
 * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return
 */
api.indices.prototype.existsAlias = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': [
        'open',
        'closed'
      ],
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_alias/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_alias/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_alias',
      req: {
        index: {
          type: 'list'
        }
      }
    }
  ],
  method: 'HEAD'
});

/**
 * Perform a [indices.existsTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String} params.name - The name of the template
 */
api.indices.prototype.existsTemplate = ca({
  params: {
    local: {
      type: 'boolean'
    }
  },
  url: {
    fmt: '/_template/<%=name%>',
    req: {
      name: {
        type: 'string'
      }
    }
  },
  method: 'HEAD'
});

/**
 * Perform a [indices.existsType](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-types-exists.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` to check the types across all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to check
 */
api.indices.prototype.existsType = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>',
    req: {
      index: {
        type: 'list'
      },
      type: {
        type: 'list'
      }
    }
  },
  method: 'HEAD'
});

/**
 * Perform a [indices.flush](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-flush.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.force - Whether a flush should be forced even if it is not necessarily needed ie. if no changes will be committed to the index. This is useful if transaction log IDs should be incremented even if no uncommitted changes are present. (This setting can be considered as internal)
 * @param {Boolean} params.full - If set to true a new index writer is created and settings that have been changed related to the index writer will be refreshed. Note: if a full flush is required for a setting to take effect this will be part of the settings update process and it not required to be executed by the user. (This setting can be considered as internal)
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string for all indices
 */
api.indices.prototype.flush = ca({
  params: {
    force: {
      type: 'boolean'
    },
    full: {
      type: 'boolean'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_flush',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_flush'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.getAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases
 * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return
 */
api.indices.prototype.getAlias = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_alias/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_alias/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_alias',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_alias'
    }
  ]
});

/**
 * Perform a [indices.getAliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases
 * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to filter
 */
api.indices.prototype.getAliases = ca({
  params: {
    timeout: {
      type: 'time'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_aliases/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_aliases',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_aliases/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_aliases'
    }
  ]
});

/**
 * Perform a [indices.getFieldMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-field-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.includeDefaults - Whether the default mapping values should be returned as well
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types
 * @param {String, String[], Boolean} params.field - A comma-separated list of fields
 */
api.indices.prototype.getFieldMapping = ca({
  params: {
    includeDefaults: {
      type: 'boolean',
      name: 'include_defaults'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_mapping/<%=type%>/field/<%=field%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        },
        field: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mapping/field/<%=field%>',
      req: {
        index: {
          type: 'list'
        },
        field: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_mapping/<%=type%>/field/<%=field%>',
      req: {
        type: {
          type: 'list'
        },
        field: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_mapping/field/<%=field%>',
      req: {
        field: {
          type: 'list'
        }
      }
    }
  ]
});

/**
 * Perform a [indices.getMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types
 */
api.indices.prototype.getMapping = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_mapping/<%=type%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mapping',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_mapping/<%=type%>',
      req: {
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_mapping'
    }
  ]
});

/**
 * Perform a [indices.getSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open,closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.name - The name of the settings that should be included
 */
api.indices.prototype.getSettings = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': [
        'open',
        'closed'
      ],
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_settings/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_settings',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_settings/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_settings'
    }
  ]
});

/**
 * Perform a [indices.getTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String} params.name - The name of the template
 */
api.indices.prototype.getTemplate = ca({
  params: {
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/_template/<%=name%>',
      req: {
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_template'
    }
  ]
});

/**
 * Perform a [indices.getWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` to perform the operation on all indices
 * @param {String, String[], Boolean} params.name - The name of the warmer (supports wildcards); leave empty to get all warmers
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types
 */
api.indices.prototype.getWarmer = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_warmer',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_warmer/<%=name%>',
      req: {
        name: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_warmer'
    }
  ]
});

/**
 * Perform a [indices.open](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-open-close.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.index - The name of the index
 */
api.indices.prototype.open = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'closed',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  url: {
    fmt: '/<%=index%>/_open',
    req: {
      index: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [indices.optimize](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-optimize.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flush - Specify whether the index should be flushed after performing the operation (default: true)
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Number} params.maxNumSegments - The number of segments the index should be merged into (default: dynamic)
 * @param {Boolean} params.onlyExpungeDeletes - Specify whether the operation should only expunge deleted documents
 * @param {Anything} params.operationThreading - : ?
 * @param {Boolean} params.waitForMerge - Specify whether the request should block until the merge process is finished (default: true)
 * @param {Boolean} params.force - Force a merge operation to run, even if there is a single segment in the index (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.optimize = ca({
  params: {
    flush: {
      type: 'boolean'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    maxNumSegments: {
      type: 'number',
      name: 'max_num_segments'
    },
    onlyExpungeDeletes: {
      type: 'boolean',
      name: 'only_expunge_deletes'
    },
    operationThreading: {
      name: 'operation_threading'
    },
    waitForMerge: {
      type: 'boolean',
      name: 'wait_for_merge'
    },
    force: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_optimize',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_optimize'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.putAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Explicit timestamp for the document
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names the alias should point to (supports wildcards); use `_all` or omit to perform the operation on all indices.
 * @param {String} params.name - The name of the alias to be created or updated
 */
api.indices.prototype.putAlias = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_alias/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_alias/<%=name%>',
      req: {
        name: {
          type: 'string'
        }
      }
    }
  ],
  method: 'PUT'
});

/**
 * Perform a [indices.putMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-put-mapping.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreConflicts - Specify whether to ignore conflicts while updating the mapping (default: false)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.
 * @param {String} params.type - The name of the document type
 */
api.indices.prototype.putMapping = ca({
  params: {
    ignoreConflicts: {
      type: 'boolean',
      name: 'ignore_conflicts'
    },
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_mapping/<%=type%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_mapping/<%=type%>',
      req: {
        type: {
          type: 'string'
        }
      }
    }
  ],
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.putSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-update-settings.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.putSettings = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_settings',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_settings'
    }
  ],
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.putTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Number} params.order - The order for this template when merging multiple matching ones (higher numbers are merged later, overriding the lower numbers)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {String} params.name - The name of the template
 */
api.indices.prototype.putTemplate = ca({
  params: {
    order: {
      type: 'number'
    },
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    }
  },
  url: {
    fmt: '/_template/<%=name%>',
    req: {
      name: {
        type: 'string'
      }
    }
  },
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.putWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) in the search request to warm
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices in the search request to warm. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both, in the search request to warm.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to register the warmer for; use `_all` or omit to perform the operation on all indices
 * @param {String} params.name - The name of the warmer
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to register the warmer for; leave empty to perform the operation on all types
 */
api.indices.prototype.putWarmer = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_warmer/<%=name%>',
      req: {
        index: {
          type: 'list'
        },
        name: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_warmer/<%=name%>',
      req: {
        name: {
          type: 'string'
        }
      }
    }
  ],
  needBody: true,
  method: 'PUT'
});

/**
 * Perform a [indices.recovery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/indices-recovery.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.detailed - Whether to display detailed information about shard recovery
 * @param {Boolean} params.activeOnly - Display only those recoveries that are currently on-going
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.recovery = ca({
  params: {
    detailed: {
      type: 'boolean',
      'default': false
    },
    activeOnly: {
      type: 'boolean',
      'default': false,
      name: 'active_only'
    },
    human: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_recovery',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_recovery'
    }
  ]
});

/**
 * Perform a [indices.refresh](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-refresh.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.force - Force a refresh even if not required
 * @param {Anything} params.operationThreading - : ?
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.refresh = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    force: {
      type: 'boolean',
      'default': false
    },
    operationThreading: {
      name: 'operation_threading'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_refresh',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_refresh'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.segments](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-segments.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {Anything} params.operationThreading - : ?
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.segments = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    human: {
      type: 'boolean',
      'default': false
    },
    operationThreading: {
      name: 'operation_threading'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_segments',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_segments'
    }
  ]
});

/**
 * Perform a [indices.snapshotIndex](http://www.elasticsearch.org/guide/en/elasticsearch/reference/0.90/indices-gateway-snapshot.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string for all indices
 */
api.indices.prototype.snapshotIndex = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_gateway/snapshot',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_gateway/snapshot'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [indices.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-stats.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards)
 * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields for `fielddata` index metric (supports wildcards)
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards)
 * @param {Boolean} params.groups - A comma-separated list of search groups for `search` index metric
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {String} [params.level=indices] - Return stats aggregated at cluster, index or shard level
 * @param {String, String[], Boolean} params.types - A comma-separated list of document types for the `indexing` index metric
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.metric - Limit the information returned the specific metrics.
 */
api.indices.prototype.stats = ca({
  params: {
    completionFields: {
      type: 'list',
      name: 'completion_fields'
    },
    fielddataFields: {
      type: 'list',
      name: 'fielddata_fields'
    },
    fields: {
      type: 'list'
    },
    groups: {
      type: 'boolean'
    },
    human: {
      type: 'boolean',
      'default': false
    },
    level: {
      type: 'enum',
      'default': 'indices',
      options: [
        'cluster',
        'indices',
        'shards'
      ]
    },
    types: {
      type: 'list'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_stats/<%=metric%>',
      req: {
        index: {
          type: 'list'
        },
        metric: {
          type: 'list',
          options: [
            '_all',
            'completion',
            'docs',
            'fielddata',
            'filter_cache',
            'flush',
            'get',
            'id_cache',
            'indexing',
            'merge',
            'percolate',
            'refresh',
            'search',
            'segments',
            'store',
            'warmer'
          ]
        }
      }
    },
    {
      fmt: '/_stats/<%=metric%>',
      req: {
        metric: {
          type: 'list',
          options: [
            '_all',
            'completion',
            'docs',
            'fielddata',
            'filter_cache',
            'flush',
            'get',
            'id_cache',
            'indexing',
            'merge',
            'percolate',
            'refresh',
            'search',
            'segments',
            'store',
            'warmer'
          ]
        }
      }
    },
    {
      fmt: '/<%=index%>/_stats',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_stats'
    }
  ]
});

/**
 * Perform a [indices.status](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-status.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {Anything} params.operationThreading - : ?
 * @param {Boolean} params.recovery - Return information about shard recovery
 * @param {Boolean} params.snapshot - : ?
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
 */
api.indices.prototype.status = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    human: {
      type: 'boolean',
      'default': false
    },
    operationThreading: {
      name: 'operation_threading'
    },
    recovery: {
      type: 'boolean'
    },
    snapshot: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_status',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_status'
    }
  ]
});

/**
 * Perform a [indices.updateAliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.timeout - Request timeout
 * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master
 */
api.indices.prototype.updateAliases = ca({
  params: {
    timeout: {
      type: 'time'
    },
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_aliases'
  },
  needBody: true,
  method: 'POST'
});

/**
 * Perform a [indices.validateQuery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-validate.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.explain - Return detailed information about the error
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {Anything} params.operationThreading - : ?
 * @param {String} params.source - The URL-encoded query definition (instead of using the request body)
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types
 */
api.indices.prototype.validateQuery = ca({
  params: {
    explain: {
      type: 'boolean'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    operationThreading: {
      name: 'operation_threading'
    },
    source: {
      type: 'string'
    },
    q: {
      type: 'string'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_validate/query',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_validate/query',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_validate/query'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [info](http://www.elasticsearch.org/guide/) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 */
api.info = ca({
  url: {
    fmt: '/'
  }
});

/**
 * Perform a [mget](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-multi-get.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode
 * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.mget = ca({
  params: {
    fields: {
      type: 'list'
    },
    preference: {
      type: 'string'
    },
    realtime: {
      type: 'boolean'
    },
    refresh: {
      type: 'boolean'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_mget',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mget',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_mget'
    }
  ],
  needBody: true,
  method: 'POST'
});

/**
 * Perform a [mlt](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-more-like-this.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Number} params.boostTerms - The boost factor
 * @param {Number} params.maxDocFreq - The word occurrence frequency as count: words with higher occurrence in the corpus will be ignored
 * @param {Number} params.maxQueryTerms - The maximum query terms to be included in the generated query
 * @param {Number} params.maxWordLength - The minimum length of the word: longer words will be ignored
 * @param {Number} params.minDocFreq - The word occurrence frequency as count: words with lower occurrence in the corpus will be ignored
 * @param {Number} params.minTermFreq - The term frequency as percent: terms with lower occurence in the source document will be ignored
 * @param {Number} params.minWordLength - The minimum length of the word: shorter words will be ignored
 * @param {String, String[], Boolean} params.mltFields - Specific fields to perform the query against
 * @param {Number} params.percentTermsToMatch - How many terms have to match in order to consider the document a match (default: 0.3)
 * @param {String} params.routing - Specific routing value
 * @param {Number} params.searchFrom - The offset from which to return results
 * @param {String, String[], Boolean} params.searchIndices - A comma-separated list of indices to perform the query against (default: the index containing the document)
 * @param {String} params.searchQueryHint - The search query hint
 * @param {String} params.searchScroll - A scroll search request definition
 * @param {Number} params.searchSize - The number of documents to return (default: 10)
 * @param {String} params.searchSource - A specific search request definition (instead of using the request body)
 * @param {String} params.searchType - Specific search type (eg. `dfs_then_fetch`, `count`, etc)
 * @param {String, String[], Boolean} params.searchTypes - A comma-separated list of types to perform the query against (default: the same type as the document)
 * @param {String, String[], Boolean} params.stopWords - A list of stop words to be ignored
 * @param {String} params.id - The document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types)
 */
api.mlt = ca({
  params: {
    boostTerms: {
      type: 'number',
      name: 'boost_terms'
    },
    maxDocFreq: {
      type: 'number',
      name: 'max_doc_freq'
    },
    maxQueryTerms: {
      type: 'number',
      name: 'max_query_terms'
    },
    maxWordLength: {
      type: 'number',
      name: 'max_word_length'
    },
    minDocFreq: {
      type: 'number',
      name: 'min_doc_freq'
    },
    minTermFreq: {
      type: 'number',
      name: 'min_term_freq'
    },
    minWordLength: {
      type: 'number',
      name: 'min_word_length'
    },
    mltFields: {
      type: 'list',
      name: 'mlt_fields'
    },
    percentTermsToMatch: {
      type: 'number',
      name: 'percent_terms_to_match'
    },
    routing: {
      type: 'string'
    },
    searchFrom: {
      type: 'number',
      name: 'search_from'
    },
    searchIndices: {
      type: 'list',
      name: 'search_indices'
    },
    searchQueryHint: {
      type: 'string',
      name: 'search_query_hint'
    },
    searchScroll: {
      type: 'string',
      name: 'search_scroll'
    },
    searchSize: {
      type: 'number',
      name: 'search_size'
    },
    searchSource: {
      type: 'string',
      name: 'search_source'
    },
    searchType: {
      type: 'string',
      name: 'search_type'
    },
    searchTypes: {
      type: 'list',
      name: 'search_types'
    },
    stopWords: {
      type: 'list',
      name: 'stop_words'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_mlt',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [mpercolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.index - The index of the document being count percolated to use as default
 * @param {String} params.type - The type of the document being percolated to use as default.
 */
api.mpercolate = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_mpercolate',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mpercolate',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_mpercolate'
    }
  ],
  needBody: true,
  bulkBody: true,
  method: 'POST'
});

/**
 * Perform a [msearch](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-multi-search.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.searchType - Search operation type
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to use as default
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to use as default
 */
api.msearch = ca({
  params: {
    searchType: {
      type: 'enum',
      options: [
        'query_then_fetch',
        'query_and_fetch',
        'dfs_query_then_fetch',
        'dfs_query_and_fetch',
        'count',
        'scan'
      ],
      name: 'search_type'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_msearch',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_msearch',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_msearch'
    }
  ],
  needBody: true,
  bulkBody: true,
  method: 'POST'
});

/**
 * Perform a [mtermvectors](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-multi-termvectors.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.ids - A comma-separated list of documents ids. You must define ids as parameter or set "ids" or "docs" in the request body
 * @param {Boolean} params.termStatistics - Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {Boolean} [params.fieldStatistics=true] - Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {Boolean} [params.offsets=true] - Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {Boolean} [params.positions=true] - Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {Boolean} [params.payloads=true] - Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {String} params.routing - Specific routing value. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {String} params.parent - Parent id of documents. Applies to all returned documents unless otherwise specified in body "params" or "docs".
 * @param {String} params.index - The index in which the document resides.
 * @param {String} params.type - The type of the document.
 * @param {String} params.id - The id of the document.
 */
api.mtermvectors = ca({
  params: {
    ids: {
      type: 'list',
      required: false
    },
    termStatistics: {
      type: 'boolean',
      'default': false,
      required: false,
      name: 'term_statistics'
    },
    fieldStatistics: {
      type: 'boolean',
      'default': true,
      required: false,
      name: 'field_statistics'
    },
    fields: {
      type: 'list',
      required: false
    },
    offsets: {
      type: 'boolean',
      'default': true,
      required: false
    },
    positions: {
      type: 'boolean',
      'default': true,
      required: false
    },
    payloads: {
      type: 'boolean',
      'default': true,
      required: false
    },
    preference: {
      type: 'string',
      required: false
    },
    routing: {
      type: 'string',
      required: false
    },
    parent: {
      type: 'string',
      required: false
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_mtermvectors',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/_mtermvectors',
      req: {
        index: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_mtermvectors'
    }
  ],
  method: 'POST'
});

api.nodes = function NodesNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [nodes.hotThreads](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-hot-threads.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.interval - The interval for the second sampling of threads
 * @param {Number} params.snapshots - Number of samples of thread stacktrace (default: 10)
 * @param {Number} params.threads - Specify the number of threads to provide information for (default: 3)
 * @param {String} params.type - The type to sample (default: cpu)
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
 */
api.nodes.prototype.hotThreads = ca({
  params: {
    interval: {
      type: 'time'
    },
    snapshots: {
      type: 'number'
    },
    threads: {
      type: 'number'
    },
    type: {
      type: 'enum',
      options: [
        'cpu',
        'wait',
        'block'
      ]
    }
  },
  urls: [
    {
      fmt: '/_nodes/<%=nodeId%>/hotthreads',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_nodes/hotthreads'
    }
  ]
});

/**
 * Perform a [nodes.info](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-info.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.flatSettings - Return settings in flat format (default: false)
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
 * @param {String, String[], Boolean} params.metric - A comma-separated list of metrics you wish returned. Leave empty to return all.
 */
api.nodes.prototype.info = ca({
  params: {
    flatSettings: {
      type: 'boolean',
      name: 'flat_settings'
    },
    human: {
      type: 'boolean',
      'default': false
    }
  },
  urls: [
    {
      fmt: '/_nodes/<%=nodeId%>/<%=metric%>',
      req: {
        nodeId: {
          type: 'list'
        },
        metric: {
          type: 'list',
          options: [
            'settings',
            'os',
            'process',
            'jvm',
            'thread_pool',
            'network',
            'transport',
            'http',
            'plugins'
          ]
        }
      }
    },
    {
      fmt: '/_nodes/<%=nodeId%>',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_nodes/<%=metric%>',
      req: {
        metric: {
          type: 'list',
          options: [
            'settings',
            'os',
            'process',
            'jvm',
            'thread_pool',
            'network',
            'transport',
            'http',
            'plugins'
          ]
        }
      }
    },
    {
      fmt: '/_nodes'
    }
  ]
});

/**
 * Perform a [nodes.shutdown](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-shutdown.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.delay - Set the delay for the operation (default: 1s)
 * @param {Boolean} params.exit - Exit the JVM as well (default: true)
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to perform the operation on; use `_local` to perform the operation on the node you're connected to, leave empty to perform the operation on all nodes
 */
api.nodes.prototype.shutdown = ca({
  params: {
    delay: {
      type: 'time'
    },
    exit: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/_cluster/nodes/<%=nodeId%>/_shutdown',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_shutdown'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [nodes.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-stats.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards)
 * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields for `fielddata` index metric (supports wildcards)
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards)
 * @param {Boolean} params.groups - A comma-separated list of search groups for `search` index metric
 * @param {Boolean} params.human - Whether to return time and byte values in human-readable format.
 * @param {String} [params.level=node] - Return indices stats aggregated at node, index or shard level
 * @param {String, String[], Boolean} params.types - A comma-separated list of document types for the `indexing` index metric
 * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics
 * @param {String, String[], Boolean} params.indexMetric - Limit the information returned for `indices` metric to the specific index metrics. Isn't used if `indices` (or `all`) metric isn't specified.
 * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
 */
api.nodes.prototype.stats = ca({
  params: {
    completionFields: {
      type: 'list',
      name: 'completion_fields'
    },
    fielddataFields: {
      type: 'list',
      name: 'fielddata_fields'
    },
    fields: {
      type: 'list'
    },
    groups: {
      type: 'boolean'
    },
    human: {
      type: 'boolean',
      'default': false
    },
    level: {
      type: 'enum',
      'default': 'node',
      options: [
        'node',
        'indices',
        'shards'
      ]
    },
    types: {
      type: 'list'
    }
  },
  urls: [
    {
      fmt: '/_nodes/<%=nodeId%>/stats/<%=metric%>/<%=indexMetric%>',
      req: {
        nodeId: {
          type: 'list'
        },
        metric: {
          type: 'list',
          options: [
            '_all',
            'breaker',
            'fs',
            'http',
            'indices',
            'jvm',
            'network',
            'os',
            'process',
            'thread_pool',
            'transport'
          ]
        },
        indexMetric: {
          type: 'list',
          options: [
            '_all',
            'completion',
            'docs',
            'fielddata',
            'filter_cache',
            'flush',
            'get',
            'id_cache',
            'indexing',
            'merge',
            'percolate',
            'refresh',
            'search',
            'segments',
            'store',
            'warmer'
          ]
        }
      }
    },
    {
      fmt: '/_nodes/<%=nodeId%>/stats/<%=metric%>',
      req: {
        nodeId: {
          type: 'list'
        },
        metric: {
          type: 'list',
          options: [
            '_all',
            'breaker',
            'fs',
            'http',
            'indices',
            'jvm',
            'network',
            'os',
            'process',
            'thread_pool',
            'transport'
          ]
        }
      }
    },
    {
      fmt: '/_nodes/stats/<%=metric%>/<%=indexMetric%>',
      req: {
        metric: {
          type: 'list',
          options: [
            '_all',
            'breaker',
            'fs',
            'http',
            'indices',
            'jvm',
            'network',
            'os',
            'process',
            'thread_pool',
            'transport'
          ]
        },
        indexMetric: {
          type: 'list',
          options: [
            '_all',
            'completion',
            'docs',
            'fielddata',
            'filter_cache',
            'flush',
            'get',
            'id_cache',
            'indexing',
            'merge',
            'percolate',
            'refresh',
            'search',
            'segments',
            'store',
            'warmer'
          ]
        }
      }
    },
    {
      fmt: '/_nodes/<%=nodeId%>/stats',
      req: {
        nodeId: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_nodes/stats/<%=metric%>',
      req: {
        metric: {
          type: 'list',
          options: [
            '_all',
            'breaker',
            'fs',
            'http',
            'indices',
            'jvm',
            'network',
            'os',
            'process',
            'thread_pool',
            'transport'
          ]
        }
      }
    },
    {
      fmt: '/_nodes/stats'
    }
  ]
});

/**
 * Perform a [percolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.percolateIndex - The index to percolate the document into. Defaults to index.
 * @param {String} params.percolateType - The type to percolate document into. Defaults to type.
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.index - The index of the document being percolated.
 * @param {String} params.type - The type of the document being percolated.
 * @param {String} params.id - Substitute the document in the request body with a document that is known by the specified id. On top of the id, the index and type parameter will be used to retrieve the document from within the cluster.
 */
api.percolate = ca({
  params: {
    routing: {
      type: 'list'
    },
    preference: {
      type: 'string'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    percolateIndex: {
      type: 'string',
      name: 'percolate_index'
    },
    percolateType: {
      type: 'string',
      name: 'percolate_type'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external',
        'external_gte',
        'force'
      ],
      name: 'version_type'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/<%=id%>/_percolate',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        },
        id: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/<%=index%>/<%=type%>/_percolate',
      req: {
        index: {
          type: 'string'
        },
        type: {
          type: 'string'
        }
      }
    }
  ],
  method: 'POST'
});

/**
 * Perform a [ping](http://www.elasticsearch.org/guide/) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 */
api.ping = ca({
  url: {
    fmt: '/'
  },
  requestTimeout: 100,
  method: 'HEAD'
});

/**
 * Perform a [scroll](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-request-scroll.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search
 * @param {String} params.scrollId - The scroll ID
 */
api.scroll = ca({
  params: {
    scroll: {
      type: 'duration'
    },
    scrollId: {
      type: 'string',
      name: 'scroll_id'
    }
  },
  urls: [
    {
      fmt: '/_search/scroll/<%=scrollId%>',
      req: {
        scrollId: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_search/scroll'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [search](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-search.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.analyzer - The analyzer to use for the query string
 * @param {Boolean} params.analyzeWildcard - Specify whether wildcard and prefix queries should be analyzed (default: false)
 * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR)
 * @param {String} params.df - The field to use as default where no field prefix is given in the query string
 * @param {Boolean} params.explain - Specify whether to return detailed information about score computation as part of a hit
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return as part of a hit
 * @param {Number} params.from - Starting offset (default: 0)
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String, String[], Boolean} params.indicesBoost - Comma-separated list of index boosts
 * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
 * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.q - Query in the Lucene query string syntax
 * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values
 * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search
 * @param {String} params.searchType - Search operation type
 * @param {Number} params.size - Number of hits to return (default: 10)
 * @param {String, String[], Boolean} params.sort - A comma-separated list of <field>:<direction> pairs
 * @param {String} params.source - The URL-encoded request definition using the Query DSL (instead of using request body)
 * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return
 * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field
 * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field
 * @param {String, String[], Boolean} params.stats - Specific 'tag' of the request for logging and statistical purposes
 * @param {String} params.suggestField - Specify which field to use for suggestions
 * @param {String} [params.suggestMode=missing] - Specify suggest mode
 * @param {Number} params.suggestSize - How many suggestions to return in response
 * @param {Text} params.suggestText - The source text for which the suggestions should be returned
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Boolean} params.version - Specify whether to return document version as part of a hit
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to search; leave empty to perform the operation on all types
 */
api.search = ca({
  params: {
    analyzer: {
      type: 'string'
    },
    analyzeWildcard: {
      type: 'boolean',
      name: 'analyze_wildcard'
    },
    defaultOperator: {
      type: 'enum',
      'default': 'OR',
      options: [
        'AND',
        'OR'
      ],
      name: 'default_operator'
    },
    df: {
      type: 'string'
    },
    explain: {
      type: 'boolean'
    },
    fields: {
      type: 'list'
    },
    from: {
      type: 'number'
    },
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    indicesBoost: {
      type: 'list',
      name: 'indices_boost'
    },
    lenient: {
      type: 'boolean'
    },
    lowercaseExpandedTerms: {
      type: 'boolean',
      name: 'lowercase_expanded_terms'
    },
    preference: {
      type: 'string'
    },
    q: {
      type: 'string'
    },
    routing: {
      type: 'list'
    },
    scroll: {
      type: 'duration'
    },
    searchType: {
      type: 'enum',
      options: [
        'query_then_fetch',
        'query_and_fetch',
        'dfs_query_then_fetch',
        'dfs_query_and_fetch',
        'count',
        'scan'
      ],
      name: 'search_type'
    },
    size: {
      type: 'number'
    },
    sort: {
      type: 'list'
    },
    source: {
      type: 'string'
    },
    _source: {
      type: 'list'
    },
    _sourceExclude: {
      type: 'list',
      name: '_source_exclude'
    },
    _sourceInclude: {
      type: 'list',
      name: '_source_include'
    },
    stats: {
      type: 'list'
    },
    suggestField: {
      type: 'string',
      name: 'suggest_field'
    },
    suggestMode: {
      type: 'enum',
      'default': 'missing',
      options: [
        'missing',
        'popular',
        'always'
      ],
      name: 'suggest_mode'
    },
    suggestSize: {
      type: 'number',
      name: 'suggest_size'
    },
    suggestText: {
      type: 'text',
      name: 'suggest_text'
    },
    timeout: {
      type: 'time'
    },
    version: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_search',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_search',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_search'
    }
  ],
  method: 'POST'
});

/**
 * Perform a [searchTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-search.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
 * @param {String, String[], Boolean} params.type - A comma-separated list of document types to search; leave empty to perform the operation on all types
 */
api.searchTemplate = ca({
  urls: [
    {
      fmt: '/<%=index%>/<%=type%>/_search/template',
      req: {
        index: {
          type: 'list'
        },
        type: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/<%=index%>/_search/template',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_search/template'
    }
  ],
  method: 'POST'
});

api.snapshot = function SnapshotNS(transport) {
  this.transport = transport;
};

/**
 * Perform a [snapshot.create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Boolean} params.waitForCompletion - Should this request wait until the operation has completed before returning
 * @param {String} params.repository - A repository name
 * @param {String} params.snapshot - A snapshot name
 */
api.snapshot.prototype.create = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    waitForCompletion: {
      type: 'boolean',
      'default': false,
      name: 'wait_for_completion'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>/<%=snapshot%>',
    req: {
      repository: {
        type: 'string'
      },
      snapshot: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [snapshot.createRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {String} params.repository - A repository name
 */
api.snapshot.prototype.createRepository = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    timeout: {
      type: 'time'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>',
    req: {
      repository: {
        type: 'string'
      }
    }
  },
  needBody: true,
  method: 'POST'
});

/**
 * Perform a [snapshot.delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String} params.repository - A repository name
 * @param {String} params.snapshot - A snapshot name
 */
api.snapshot.prototype['delete'] = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>/<%=snapshot%>',
    req: {
      repository: {
        type: 'string'
      },
      snapshot: {
        type: 'string'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [snapshot.deleteRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {String, String[], Boolean} params.repository - A comma-separated list of repository names
 */
api.snapshot.prototype.deleteRepository = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    timeout: {
      type: 'time'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>',
    req: {
      repository: {
        type: 'list'
      }
    }
  },
  method: 'DELETE'
});

/**
 * Perform a [snapshot.get](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String} params.repository - A repository name
 * @param {String, String[], Boolean} params.snapshot - A comma-separated list of snapshot names
 */
api.snapshot.prototype.get = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>/<%=snapshot%>',
    req: {
      repository: {
        type: 'string'
      },
      snapshot: {
        type: 'list'
      }
    }
  }
});

/**
 * Perform a [snapshot.getRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false)
 * @param {String, String[], Boolean} params.repository - A comma-separated list of repository names
 */
api.snapshot.prototype.getRepository = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    local: {
      type: 'boolean'
    }
  },
  urls: [
    {
      fmt: '/_snapshot/<%=repository%>',
      req: {
        repository: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_snapshot'
    }
  ]
});

/**
 * Perform a [snapshot.restore](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {Boolean} params.waitForCompletion - Should this request wait until the operation has completed before returning
 * @param {String} params.repository - A repository name
 * @param {String} params.snapshot - A snapshot name
 */
api.snapshot.prototype.restore = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    },
    waitForCompletion: {
      type: 'boolean',
      'default': false,
      name: 'wait_for_completion'
    }
  },
  url: {
    fmt: '/_snapshot/<%=repository%>/<%=snapshot%>/_restore',
    req: {
      repository: {
        type: 'string'
      },
      snapshot: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [snapshot.status](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node
 * @param {String} params.repository - A repository name
 * @param {String, String[], Boolean} params.snapshot - A comma-separated list of snapshot names
 */
api.snapshot.prototype.status = ca({
  params: {
    masterTimeout: {
      type: 'time',
      name: 'master_timeout'
    }
  },
  urls: [
    {
      fmt: '/_snapshot/<%=repository%>/<%=snapshot%>/_status',
      req: {
        repository: {
          type: 'string'
        },
        snapshot: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_snapshot/<%=repository%>/_status',
      req: {
        repository: {
          type: 'string'
        }
      }
    },
    {
      fmt: '/_snapshot/_status'
    }
  ]
});

/**
 * Perform a [suggest](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-search.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
 * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
 * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both.
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random)
 * @param {String} params.routing - Specific routing value
 * @param {String} params.source - The URL-encoded request definition (instead of using request body)
 * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices
 */
api.suggest = ca({
  params: {
    ignoreUnavailable: {
      type: 'boolean',
      name: 'ignore_unavailable'
    },
    allowNoIndices: {
      type: 'boolean',
      name: 'allow_no_indices'
    },
    expandWildcards: {
      type: 'enum',
      'default': 'open',
      options: [
        'open',
        'closed'
      ],
      name: 'expand_wildcards'
    },
    preference: {
      type: 'string'
    },
    routing: {
      type: 'string'
    },
    source: {
      type: 'string'
    }
  },
  urls: [
    {
      fmt: '/<%=index%>/_suggest',
      req: {
        index: {
          type: 'list'
        }
      }
    },
    {
      fmt: '/_suggest'
    }
  ],
  needBody: true,
  method: 'POST'
});

/**
 * Perform a [termvector](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-termvectors.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {Boolean} params.termStatistics - Specifies if total term frequency and document frequency should be returned.
 * @param {Boolean} [params.fieldStatistics=true] - Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned.
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return.
 * @param {Boolean} [params.offsets=true] - Specifies if term offsets should be returned.
 * @param {Boolean} [params.positions=true] - Specifies if term positions should be returned.
 * @param {Boolean} [params.payloads=true] - Specifies if term payloads should be returned.
 * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random).
 * @param {String} params.routing - Specific routing value.
 * @param {String} params.parent - Parent id of documents.
 * @param {String} params.index - The index in which the document resides.
 * @param {String} params.type - The type of the document.
 * @param {String} params.id - The id of the document.
 */
api.termvector = ca({
  params: {
    termStatistics: {
      type: 'boolean',
      'default': false,
      required: false,
      name: 'term_statistics'
    },
    fieldStatistics: {
      type: 'boolean',
      'default': true,
      required: false,
      name: 'field_statistics'
    },
    fields: {
      type: 'list',
      required: false
    },
    offsets: {
      type: 'boolean',
      'default': true,
      required: false
    },
    positions: {
      type: 'boolean',
      'default': true,
      required: false
    },
    payloads: {
      type: 'boolean',
      'default': true,
      required: false
    },
    preference: {
      type: 'string',
      required: false
    },
    routing: {
      type: 'string',
      required: false
    },
    parent: {
      type: 'string',
      required: false
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_termvector',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [update](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-update.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response
 * @param {String} params.lang - The script language (default: mvel)
 * @param {String} params.parent - ID of the parent document
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {Number} params.retryOnConflict - Specify how many times should the operation be retried when a conflict occurs (default: 0)
 * @param {String} params.routing - Specific routing value
 * @param {Anything} params.script - The URL-encoded script definition (instead of using request body)
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.timestamp - Explicit timestamp for the document
 * @param {Duration} params.ttl - Expiration time for the document
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - Document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.update = ca({
  params: {
    consistency: {
      type: 'enum',
      options: [
        'one',
        'quorum',
        'all'
      ]
    },
    fields: {
      type: 'list'
    },
    lang: {
      type: 'string'
    },
    parent: {
      type: 'string'
    },
    refresh: {
      type: 'boolean'
    },
    replication: {
      type: 'enum',
      'default': 'sync',
      options: [
        'sync',
        'async'
      ]
    },
    retryOnConflict: {
      type: 'number',
      name: 'retry_on_conflict'
    },
    routing: {
      type: 'string'
    },
    script: {},
    timeout: {
      type: 'time'
    },
    timestamp: {
      type: 'time'
    },
    ttl: {
      type: 'duration'
    },
    version: {
      type: 'number'
    },
    versionType: {
      type: 'enum',
      options: [
        'internal',
        'external',
        'external_gte',
        'force'
      ],
      name: 'version_type'
    }
  },
  url: {
    fmt: '/<%=index%>/<%=type%>/<%=id%>/_update',
    req: {
      index: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      id: {
        type: 'string'
      }
    }
  },
  method: 'POST'
});

/**
 * Perform a [create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-index_.html) request
 *
 * @param {Object} params - An object with parameters used to carry out this action
 * @param {String} params.consistency - Explicit write consistency setting for the operation
 * @param {String} params.parent - ID of the parent document
 * @param {Boolean} params.refresh - Refresh the index after performing the operation
 * @param {String} [params.replication=sync] - Specific replication type
 * @param {String} params.routing - Specific routing value
 * @param {Date, Number} params.timeout - Explicit operation timeout
 * @param {Date, Number} params.timestamp - Explicit timestamp for the document
 * @param {Duration} params.ttl - Expiration time for the document
 * @param {Number} params.version - Explicit version number for concurrency control
 * @param {String} params.versionType - Specific version type
 * @param {String} params.id - Document ID
 * @param {String} params.index - The name of the index
 * @param {String} params.type - The type of the document
 */
api.create = ca.proxy(api.index, {
  transform: function (params) {
    params.op_type = 'create';
  }
});
},{"../client_action":195}],193:[function(require,module,exports){
module.exports = {
  '1.1': require('./1_1'),
  '1.0': require('./1_0'),
  '0.90': require('./0_90')
};

},{"./0_90":190,"./1_0":191,"./1_1":192}],194:[function(require,module,exports){
/**
 * A client that makes requests to Elasticsearch via a {{#crossLink "Transport"}}Transport{{/crossLink}}
 *
 * Initializing a client might look something like:
 *
 * ```
 * var client = new es.Client({
 *   hosts: [
 *     'es1.net:9200',
 *     {
 *       host: 'es2.net',
 *       port: 9200
 *     }
 *   ],
 *   sniffOnStart: true,
 *   log: {
 *     type: 'file',
 *     level: 'warning'
 *   }
 * });
 * ```
 *
 * @class Client
 * @constructor
 */

module.exports = Client;

var Transport = require('./transport');
var _ = require('./utils');

function Client(config) {
  config = config || {};

  if (config.__reused) {
    throw new Error('Do not reuse objects to configure the elasticsearch Client class: ' +
      'https://github.com/elasticsearch/elasticsearch-js/issues/33');
  } else {
    config.__reused = true;
  }
    
  function EsApiClient() {
    // our client will log minimally by default
    if (!config.hasOwnProperty('log')) {
      config.log = 'warning';
    }

    if (!config.hosts && !config.host) {
      config.host = 'http://localhost:9200';
    }

    this.close = function () {
      this.transport.close();
    };

    this.transport = new Transport(config);

    // instantiate the api's namespaces
    for (var i = 0; i < this._namespaces.length; i++) {
      this[this._namespaces[i]] = new this[this._namespaces[i]](this.transport);
    }

    delete this._namespaces;
  }

  EsApiClient.prototype = _.funcEnum(config, 'apiVersion', Client.apis, '1.1');
  if (!config.sniffEndpoint && EsApiClient.prototype === Client.apis['0.90']) {
    config.sniffEndpoint = '/_cluster/nodes';
  }

  return new EsApiClient();
}

Client.apis = require('./apis');
},{"./apis":193,"./transport":211,"./utils":213}],195:[function(require,module,exports){
/**
 * Constructs a function that can be called to make a request to ES
 * @type {[type]}
 */
module.exports = ClientAction;

var _ = require('./utils');

function ClientAction(spec) {
  if (!_.isPlainObject(spec.params)) {
    spec.params = {};
  }

  if (!spec.method) {
    spec.method = 'GET';
  }

  function action(params, cb) {
    if (typeof params === 'function') {
      cb = params;
      params = {};
    } else {
      params = params || {};
      cb = typeof cb === 'function' ? cb : null;
    }

    try {
      return exec(this.transport, spec, _.clone(params), cb);
    } catch (e) {
      if (typeof cb === 'function') {
        _.nextTick(cb, e);
      } else {
        var def = this.transport.defer();
        def.reject(e);
        return def.promise;
      }
    }
  }

  action.spec = spec;

  return action;
}

var castType = {
  'enum': function (param, val, name) {
    /* jshint eqeqeq: false */
    for (var i = 0; i < param.options.length; i++) {
      if (param.options[i] == val) {
        return param.options[i];
      }
    }
    throw new TypeError('Invalid ' + name + ': expected ' + (
      param.options.length > 1
      ? 'one of ' + param.options.join(',')
      : param.options[0]
    ));
  },
  duration: function (param, val, name) {
    if (_.isNumeric(val) || _.isInterval(val)) {
      return val;
    } else {
      throw new TypeError(
        'Invalid ' + name + ': expected a number or interval ' +
        '(an integer followed by one of Mwdhmsy).'
      );
    }
  },
  list: function (param, val, name) {
    switch (typeof val) {
    case 'number':
    case 'string':
    case 'boolean':
      return '' + val;
    case 'object':
      if (_.isArray(val)) {
        return val.join(',');
      }
      /* falls through */
    default:
      throw new TypeError('Invalid ' + name + ': expected be a comma seperated list, array, number or string.');
    }
  },
  'boolean': function (param, val) {
    val = _.isString(val) ? val.toLowerCase() : val;
    return (val === 'no' || val === 'off') ? false : !!val;
  },
  number: function (param, val, name) {
    if (_.isNumeric(val)) {
      return val * 1;
    } else {
      throw new TypeError('Invalid ' + name + ': expected a number.');
    }
  },
  string: function (param, val, name) {
    switch (typeof val) {
    case 'number':
    case 'string':
      return '' + val;
    default:
      throw new TypeError('Invalid ' + name + ': expected a string.');
    }
  },
  time: function (param, val, name) {
    if (typeof val === 'string') {
      return val;
    }
    else if (_.isNumeric(val)) {
      return '' + val;
    }
    else if (val instanceof Date) {
      return '' + val.getTime();
    }
    else {
      throw new TypeError('Invalid ' + name + ': expected some sort of time.');
    }
  }
};

function resolveUrl(url, params) {
  var vars = {}, i, key;

  if (url.req) {
    // url has required params
    if (!url.reqParamKeys) {
      // create cached key list on demand
      url.reqParamKeys = _.keys(url.req);
    }

    for (i = 0; i < url.reqParamKeys.length; i ++) {
      key = url.reqParamKeys[i];
      if (!params.hasOwnProperty(key) || params[key] == null) {
        // missing a required param
        return false;
      } else {
        // cast of copy required param
        if (castType[url.req[key].type]) {
          vars[key] = castType[url.req[key].type](url.req[key], params[key], key);
        } else {
          vars[key] = params[key];
        }
      }
    }
  }

  if (url.opt) {
    // url has optional params
    if (!url.optParamKeys) {
      url.optParamKeys = _.keys(url.opt);
    }

    for (i = 0; i < url.optParamKeys.length; i ++) {
      key = url.optParamKeys[i];
      if (params[key]) {
        if (castType[url.opt[key].type] || params[key] == null) {
          vars[key] = castType[url.opt[key].type](url.opt[key], params[key], key);
        } else {
          vars[key] = params[key];
        }
      } else {
        vars[key] = url.opt[key]['default'];
      }
    }
  }

  if (!url.template) {
    // compile the template on demand
    url.template = _.template(url.fmt);
  }

  return url.template(_.transform(vars, function (note, val, name) {
    // encode each value
    note[name] = encodeURIComponent(val);
    // remove it from the params so that it isn't sent to the final request
    delete params[name];
  }, {}));
}

// export so that we can test this
ClientAction.resolveUrl = resolveUrl;

function exec(transport, spec, params, cb) {
  var request = {
    method: spec.method
  };
  var query = {};
  var i;

  // pass the timeout from the spec
  if (spec.requestTimeout) {
    request.requestTimeout = spec.requestTimeout;
  }

  // verify that we have the body if needed
  if (spec.needsBody && !params.body) {
    throw new TypeError('A request body is required.');
  }

  // control params
  if (spec.bulkBody) {
    request.bulkBody = true;
  }

  if (spec.method === 'HEAD') {
    request.castExists = true;
  }

  // pick the url
  if (spec.url) {
    // only one url option
    request.path = resolveUrl(spec.url, params);
  } else {
    for (i = 0; i < spec.urls.length; i++) {
      if (request.path = resolveUrl(spec.urls[i], params)) {
        break;
      }
    }
  }

  if (!request.path) {
    // there must have been some mimimun requirements that were not met
    var minUrl = spec.url || spec.urls[spec.urls.length - 1];
    throw new TypeError('Unable to build a path with those params. Supply at least ' + _.keys(minUrl.req).join(', '));
  }

  // build the query string
  if (!spec.paramKeys) {
    // build a key list on demand
    spec.paramKeys = _.keys(spec.params);
    spec.requireParamKeys = _.transform(spec.params, function (req, param, key) {
      if (param.required) {
        req.push(key);
      }
    }, []);
  }

  var key, paramSpec;

  for (key in params) {
    if (params.hasOwnProperty(key) && params[key] != null) {
      switch (key) {
      case 'body':
      case 'requestTimeout':
      case 'maxRetries':
        request[key] = params[key];
        break;
      case 'ignore':
        request.ignore = _.isArray(params[key]) ? params[key] : [params[key]];
        break;
      case 'method':
        request.method = _.toUpperString(params[key]);
        break;
      default:
        paramSpec = spec.params[key];
        if (paramSpec) {
          // param keys don't always match the param name, in those cases it's stored in the param def as "name"
          paramSpec.name = paramSpec.name || key;
          if (params[key] != null) {
            if (castType[paramSpec.type]) {
              query[paramSpec.name] = castType[paramSpec.type](paramSpec, params[key], key);
            } else {
              query[paramSpec.name] = params[key];
            }

            if (paramSpec['default'] && query[paramSpec.name] === paramSpec['default']) {
              delete query[paramSpec.name];
            }
          }
        } else {
          query[key] = params[key];
        }
      }
    }
  }

  for (i = 0; i < spec.requireParamKeys.length; i ++) {
    if (!query.hasOwnProperty(spec.requireParamKeys[i])) {
      throw new TypeError('Missing required parameter ' + spec.requireParamKeys[i]);
    }
  }

  request.query = query;

  return transport.request(request, cb);
}



ClientAction.proxy = function (fn, spec) {
  return function (params, cb) {
    if (typeof params === 'function') {
      cb = params;
      params = {};
    } else {
      params = params || {};
      cb = typeof cb === 'function' ? cb : null;
    }

    if (spec.transform) {
      spec.transform(params);
    }

    return fn.call(this, params, cb);
  };
};

},{"./utils":213}],196:[function(require,module,exports){
module.exports = ConnectionAbstract;

var _ = require('./utils');
var EventEmitter = require('events').EventEmitter;
var Log = require('./log');
var Host = require('./host');
var errors = require('./errors');

/**
 * Abstract class used for Connection classes
 * @class ConnectionAbstract
 * @constructor
 */
function ConnectionAbstract(host, config) {
  config = config || {};
  EventEmitter.call(this);

  this.requestTimeout = config.hasOwnProperty('requestTimeout') ? config.requestTimeout : 30000;
  this.log = config.log || new Log();

  if (!host) {
    throw new TypeError('Missing host');
  } else if (host instanceof Host) {
    this.host = host;
  } else {
    throw new TypeError('Invalid host');
  }

  _.makeBoundMethods(this);
}
_.inherits(ConnectionAbstract, EventEmitter);

/**
 * Make a request using this connection. Must be overridden by Connection classes, which can add whatever keys to
 * params that they like. These are just the basics.
 *
 * @param [params] {Object} - The parameters for the request
 * @param params.path {String} - The path for which you are requesting
 * @param params.method {String} - The HTTP method for the request (GET, HEAD, etc.)
 * @param params.requestTimeout {Integer} - The amount of time in milliseconds that this request should be allowed to run for.
 * @param cb {Function} - A callback to be called once with `cb(err, responseBody, responseStatus)`
 */
ConnectionAbstract.prototype.request = function () {
  throw new Error('Connection#request must be overwritten by the Connector');
};

ConnectionAbstract.prototype.ping = function (params, cb) {
  if (typeof params === 'function') {
    cb = params;
    params = null;
  } else {
    cb = typeof cb === 'function' ? cb : null;
  }

  var requestTimeout = 100;
  var requestTimeoutId;
  var aborted;
  var abort;

  if (params && params.hasOwnProperty('requestTimeout')) {
    requestTimeout = params.requestTimeout;
  }

  abort = this.request(_.defaults(params || {}, {
    path: '/',
    method: 'HEAD'
  }), function (err) {
    if (aborted) {
      return;
    }
    clearTimeout(requestTimeoutId);
    if (cb) {
      cb(err);
    }
  });

  if (requestTimeout) {
    requestTimeoutId = setTimeout(function () {
      if (abort) {
        abort();
      }
      aborted = true;
      if (cb) {
        cb(new errors.RequestTimeout('Ping Timeout after ' + requestTimeout + 'ms'));
      }
    }, requestTimeout);
  }
};

ConnectionAbstract.prototype.setStatus = function (status) {
  var origStatus = this.status;
  this.status = status;

  this.emit('status set', status, origStatus, this);

  if (status === 'closed') {
    this.removeAllListeners();
  }
};
},{"./errors":200,"./host":201,"./log":202,"./utils":213,"events":4}],197:[function(require,module,exports){
var process=require("__browserify_process");/**
 * Manager of connections to a node(s), capable of ensuring that connections are clear and living
 * before providing them to the application
 *
 * @class ConnectionPool
 * @constructor
 * @param {Object} config - The config object passed to the transport.
 */

module.exports = ConnectionPool;

var _ = require('./utils');
var Log = require('./log');

function ConnectionPool(config) {
  config = config || {};
  _.makeBoundMethods(this);

  if (!config.log) {
    this.log = new Log();
    config.log = this.log;
  } else {
    this.log = config.log;
  }

  // we will need this when we create connections down the road
  this._config = config;

  // get the selector config var
  this.selector = _.funcEnum(config, 'selector', ConnectionPool.selectors, ConnectionPool.defaultSelector);

  // get the connection class
  this.Connection = _.funcEnum(config, 'connectionClass', ConnectionPool.connectionClasses,
    ConnectionPool.defaultConnectionClass);

  // time that connections will wait before being revived
  this.deadTimeout = config.hasOwnProperty('deadTimeout') ? config.deadTimeout : 60000;
  this.maxDeadTimeout = config.hasOwnProperty('maxDeadTimeout') ? config.maxDeadTimeout : 18e5;
  this.calcDeadTimeout = _.funcEnum(config, 'calcDeadTimeout', ConnectionPool.calcDeadTimeoutOptions, 'exponential');

  // a map of connections to their "id" property, used when sniffing
  this.index = {};

  this._conns = {
    alive: [],
    dead: []
  };

  // information about timeouts for dead connections
  this._timeouts = [];
}

// selector options
ConnectionPool.selectors = require('./selectors');
ConnectionPool.defaultSelector = 'roundRobin';

// get the connection options
ConnectionPool.connectionClasses = require('./connectors');
ConnectionPool.defaultConnectionClass = ConnectionPool.connectionClasses._default;
delete ConnectionPool.connectionClasses._default;

// the function that calculates timeouts based on attempts
ConnectionPool.calcDeadTimeoutOptions = {
  flat: function (attempt, baseTimeout) {
    return baseTimeout;
  },
  exponential: function (attempt, baseTimeout) {
    return Math.min(baseTimeout * 2 * Math.pow(2, (attempt * 0.5 - 1)), this.maxDeadTimeout);
  }
};

/**
 * Selects a connection from the list using the this.selector
 * Features:
 *  - detects if the selector is async or not
 *  - sync selectors should still return asynchronously
 *  - catches errors in sync selectors
 *  - automatically selects the first dead connection when there no living connections
 *
 * @param  {Function} cb [description]
 * @return {[type]}      [description]
 */
ConnectionPool.prototype.select = function (cb) {
  if (this._conns.alive.length) {
    if (this.selector.length > 1) {
      this.selector(this._conns.alive, cb);
    } else {
      try {
        _.nextTick(cb, void 0, this.selector(this._conns.alive));
      } catch (e) {
        cb(e);
      }
    }
  } else if (this._timeouts.length) {
    this._selectDeadConnection(cb);
  } else {
    _.nextTick(cb, void 0);
  }
};

/**
 * Handler for the "set status" event emitted but the connections. It will move
 * the connection to it's proper connection list (unless it was closed).
 *
 * @param  {String} status - the connection's new status
 * @param  {String} oldStatus - the connection's old status
 * @param  {ConnectionAbstract} connection - the connection object itself
 */
ConnectionPool.prototype.onStatusSet = _.handler(function (status, oldStatus, connection) {
  var index;

  var died = (status === 'dead');
  var wasAlreadyDead = (died && oldStatus === 'dead');
  var revived = (!died && oldStatus === 'dead');
  var noChange = (oldStatus === status);
  var from = this._conns[oldStatus];
  var to = this._conns[status];

  if (noChange && !died) {
    return true;
  }

  if (from !== to) {
    if (_.isArray(from)) {
      index = from.indexOf(connection);
      if (index !== -1) {
        from.splice(index, 1);
      }
    }

    if (_.isArray(to)) {
      index = to.indexOf(connection);
      if (index === -1) {
        to.push(connection);
      }
    }
  }

  if (died) {
    this._onConnectionDied(connection, wasAlreadyDead);
  }

  if (revived) {
    this._onConnectionRevived(connection);
  }
});

/**
 * Handler used to clear the times created when a connection dies
 * @param  {ConnectionAbstract} connection
 */
ConnectionPool.prototype._onConnectionRevived = function (connection) {
  var timeout;
  for (var i = 0; i < this._timeouts.length; i++)  {
    if (this._timeouts[i].conn === connection) {
      timeout = this._timeouts[i];
      if (timeout.id) {
        clearTimeout(timeout.id);
      }
      this._timeouts.splice(i, 1);
      break;
    }
  }
};

/**
 * Handler used to update or create a timeout for the connection which has died
 * @param  {ConnectionAbstract} connection
 * @param  {Boolean} alreadyWasDead - If the connection was preivously dead this must be set to true
 */
ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDead) {
  var timeout;
  if (alreadyWasDead) {
    for (var i = 0; i < this._timeouts.length; i++)  {
      if (this._timeouts[i].conn === connection) {
        timeout = this._timeouts[i];
        break;
      }
    }
  } else {
    timeout = {
      conn: connection,
      attempt: 0,
      revive: function (cb) {
        timeout.attempt++;
        connection.ping(function (err) {
          connection.setStatus(err ? 'dead' : 'alive');
          if (cb && typeof cb === 'function') {
            cb(err);
          }
        });
      }
    };
    this._timeouts.push(timeout);
  }

  if (timeout.id) {
    clearTimeout(timeout.id);
  }

  var ms = this.calcDeadTimeout(timeout.attempt, this.deadTimeout);
  timeout.id = setTimeout(timeout.revive, ms);
  timeout.runAt = _.now() + ms;
};

ConnectionPool.prototype._selectDeadConnection = function (cb) {
  var orderedTimeouts = _.sortBy(this._timeouts, 'runAt');
  var log = this.log;

  process.nextTick(function next() {
    var timeout = orderedTimeouts.shift();
    if (!timeout) {
      cb(void 0);
      return;
    }

    if (!timeout.conn) {
      next();
      return;
    }

    if (timeout.conn.status === 'dead') {
      timeout.revive(function (err) {
        if (err) {
          log.warning('Unable to revive connection: ' + timeout.conn.id);
          process.nextTick(next);
        } else {
          cb(void 0, timeout.conn);
        }
      });
    } else {
      cb(void 0, timeout.conn);
    }
  });
};

/**
 * Returns a random list of nodes from the living connections up to the limit.
 * If there are no living connections it will fall back to the dead connections.
 * If there are no dead connections it will return nothing.
 *
 * This is used for testing (when we just want the one existing node)
 * and sniffing, where using the selector to get all of the living connections
 * is not reasonable.
 *
 * @param {Number} limit - Max number to return
 */
ConnectionPool.prototype.getConnections = function (status, limit) {
  var list;
  if (status) {
    list = this._conns[status];
  } else {
    list = this._conns[this._conns.alive.length ? 'alive' : 'dead'];
  }

  return _.shuffle(list).slice(0, typeof limit === 'undefined' ? list.length : limit);
};

/**
 * Add a single connection to the pool and change it's status to "alive".
 * The connection should inherit from ConnectionAbstract
 *
 * @param {ConnectionAbstract} connection - The connection to add
 */
ConnectionPool.prototype.addConnection = function (connection) {
  if (!connection.id) {
    connection.id = connection.host.toString();
  }

  if (!this.index[connection.id]) {
    this.log.info('Adding connection to', connection.id);
    this.index[connection.id] = connection;
    connection.on('status set', this.bound.onStatusSet);
    connection.setStatus('alive');
  }
};

/**
 * Remove a connection from the pool, and set it's status to "closed".
 *
 * @param  {ConnectionAbstract} connection - The connection to remove/close
 */
ConnectionPool.prototype.removeConnection = function (connection) {
  if (!connection.id) {
    connection.id = connection.host.toString();
  }

  if (this.index[connection.id]) {
    delete this.index[connection.id];
    connection.setStatus('closed');
    connection.removeListener('status set', this.bound.onStatusSet);
  }
};

/**
 * Override the internal node list. All connections that are not in the new host
 * list are closed and removed. Non-unique hosts are ignored.
 *
 * @param {Host[]} hosts - An array of Host instances.
 */
ConnectionPool.prototype.setHosts = function (hosts) {
  var connection;
  var i;
  var id;
  var host;
  var toRemove = _.clone(this.index);

  for (i = 0; i < hosts.length; i++) {
    host = hosts[i];
    id = host.toString();
    if (this.index[id]) {
      delete toRemove[id];
    } else {
      connection = new this.Connection(host, this._config);
      connection.id = id;
      this.addConnection(connection);
    }
  }

  var removeIds = _.keys(toRemove);
  for (i = 0; i < removeIds.length; i++) {
    this.removeConnection(this.index[removeIds[i]]);
  }
};

/**
 * Close the conncetion pool, as well as all of it's connections
 */
ConnectionPool.prototype.close = function () {
  this.setHosts([]);
};
ConnectionPool.prototype.empty = ConnectionPool.prototype.close;
},{"./connectors":199,"./log":202,"./selectors":207,"./utils":213,"__browserify_process":13}],198:[function(require,module,exports){
var Buffer=require("__browserify_Buffer").Buffer;/**
 * Connection that registers a module with angular, using angular's $http service
 * to communicate with ES.
 *
 * @class connections.Angular
 */
module.exports = AngularConnector;

var _ = require('../utils');
var ConnectionAbstract = require('../connection');
var ConnectionFault = require('../errors').ConnectionFault;

function AngularConnector(host, config) {
  ConnectionAbstract.call(this, host, config);
  this.defer = config.defer;
  this.$http = config.$http;
  if (this.host.auth) {
    this.$http.defaults.headers.common.Authorization = 'Basic ' + (new Buffer(this.host.auth, 'utf8')).toString('base64');
  }
}
_.inherits(AngularConnector, ConnectionAbstract);

AngularConnector.prototype.request = function (params, cb) {
  var abort = this.defer();
  this.$http({
    method: params.method,
    url: this.host.makeUrl(params),
    data: params.body,
    cache: false,
    headers: this.host.getHeaders(params.headers),
    transformRequest: [],
    transformResponse: []
  }).then(function (response) {
    cb(null, response.data, response.status, response.headers());
  }, function (err) {
    if (err.status) {
      cb(null, err.data, err.status, err.headers());
    } else {
      cb(new ConnectionFault(err.message));
    }
  });

  return function () {
    abort.resolve();
  };
};

},{"../connection":196,"../errors":200,"../utils":213,"__browserify_Buffer":12}],199:[function(require,module,exports){
var opts = {
  xhr: require('./xhr'),
  jquery: require('./jquery'),
  angular: require('./angular')
};
var _ = require('../utils');

// remove modules that have been ignored by browserify
_.each(opts, function (conn, name) {
  if (typeof conn !== 'function') {
    delete opts[name];
  }
});

// custom _default specification
if (opts.xhr) {
  opts._default = 'xhr';
} else if (opts.angular) {
  opts._default = 'angular';
} else {
  opts._default = 'jquery';
}

module.exports = opts;

},{"../utils":213,"./angular":198,"./jquery":1,"./xhr":1}],200:[function(require,module,exports){
var process=require("__browserify_process");var _ = require('./utils');
var errors = module.exports;

function ErrorAbstract(msg, constructor) {
  this.message = msg;

  Error.call(this, this.message);
  if (process.browser) {
    this.stack = '';
  } else {
    Error.captureStackTrace(this, constructor);
  }
}
errors._Abstract = ErrorAbstract;
_.inherits(ErrorAbstract, Error);

/**
 * Connection Error
 * @param {String} [msg] - An error message that will probably end up in a log.
 */
errors.ConnectionFault = function ConnectionFault(msg) {
  ErrorAbstract.call(this, msg || 'Connection Failure', errors.ConnectionFault);
};
_.inherits(errors.ConnectionFault, ErrorAbstract);

/**
 * No Living Connections
 * @param {String} [msg] - An error message that will probably end up in a log.
 */
errors.NoConnections = function NoConnections(msg) {
  ErrorAbstract.call(this, msg || 'No Living connections', errors.NoConnections);
};
_.inherits(errors.NoConnections, ErrorAbstract);

/**
 * Generic Error
 * @param {String} [msg] - An error message that will probably end up in a log.
 */
errors.Generic = function Generic(msg) {
  ErrorAbstract.call(this, msg || 'Generic Error', errors.Generic);
};
_.inherits(errors.Generic, ErrorAbstract);

/**
 * Request Timeout Error
 * @param {String} [msg] - An error message that will probably end up in a log.
 */
errors.RequestTimeout = function RequestTimeout(msg) {
  ErrorAbstract.call(this, msg || 'Request Timeout', errors.RequestTimeout);
};
_.inherits(errors.RequestTimeout, ErrorAbstract);


/**
 * Request Body could not be parsed
 * @param {String} [msg] - An error message that will probably end up in a log.
 */
errors.Serialization = function Serialization(msg) {
  ErrorAbstract.call(this, msg || 'Unable to parse/serialize body', errors.Serialization);
};
_.inherits(errors.Serialization, ErrorAbstract);


var statusCodes = {

  /**
   * Service Unavailable
   * @param {String} [msg] - An error message that will probably end up in a log.
   */
  503: 'Service Unavailable',

  /**
   * Internal Server Error
   * @param {String} [msg] - An error message that will probably end up in a log.
   */
  500: 'Internal Server Error',

  /**
   * Precondition Failed
   * @param {String} [msg] - An error message that will probably end up in a log.
   */
  412: 'Precondition Failed',

  /**
   * Conflict
   * @param {String} [msg] - An error message that will probably end up in a log.
   */
  409: 'Conflict',

  /**
   * Forbidden
   * @param {String} [msg] - An error message that will probably end up in a log.
   */
  403: 'Forbidden',

  /**
   * Not Found
   * @param {String} [msg] - An error message that will probably end up in a log.
   */
  404: 'Not Found',

  /**
   * Bad Request
   * @param {String} [msg] - An error message that will probably end up in a log.
   */
  400: 'Bad Request',

  /**
   * Moved Permanently
   * @param {String} [msg] - An error message that will probably end up in a log.
   */
  301: 'Moved Permanently'
};

_.each(statusCodes, function (name, status) {
  var className = _.studlyCase(name);

  function StatusCodeError(msg) {
    ErrorAbstract.call(this, msg || name, errors[className]);
  }

  _.inherits(StatusCodeError, ErrorAbstract);
  errors[className] = StatusCodeError;
  errors[status] = StatusCodeError;
});

},{"./utils":213,"__browserify_process":13}],201:[function(require,module,exports){
/**
 * Class to wrap URLS, formatting them and maintaining their separate details
 * @type {[type]}
 */
module.exports = Host;

var url = require('url');
var qs = require('querystring');
var _ = require('./utils');

var startsWithProtocolRE = /^([a-z]+:)?\/\//;

var urlParseFields = [
  'protocol', 'hostname', 'pathname', 'port', 'auth', 'query'
];

var simplify = ['host', 'path'];

// simple reference used when formatting as a url
// and defines when parsing from a string
Host.defaultPorts = {
  http: 80,
  https: 443
};

function Host(config) {
  config = config || {};

  // defaults
  this.protocol = 'http';
  this.host = 'localhost';
  this.path = '';
  this.port = 9200;
  this.auth = null;
  this.query = null;
  this.headers = null;

  if (typeof config === 'string') {
    if (!startsWithProtocolRE.test(config)) {
      config = 'http://' + config;
    }
    config = _.pick(url.parse(config, false, true), urlParseFields);
    // default logic for the port is to use 9200 for the default. When a string is specified though,
    // we will use the default from the protocol of the string.
    if (!config.port) {
      var proto = config.protocol || 'http';
      if (proto.charAt(proto.length - 1) === ':') {
        proto = proto.substring(0, proto.length - 1);
      }
      if (Host.defaultPorts[proto]) {
        config.port = Host.defaultPorts[proto];
      }
    }
  }

  if (_.isObject(config)) {
    // move hostname/portname to host/port semi-intelligently.
    _.each(simplify, function (to) {
      var from = to + 'name';
      if (config[from] && config[to]) {
        if (config[to].indexOf(config[from]) === 0) {
          config[to] = config[from];
        }
      } else if (config[from]) {
        config[to] = config[from];
      }
      delete config[from];
    });
  } else {
    config = {};
  }

  _.assign(this, config);

  // make sure the query string is parsed
  if (this.query === null) {
    // majority case
    this.query = {};
  } else if (!_.isPlainObject(this.query)) {
    this.query = qs.parse(this.query);
  }

  // make sure that the port is a number
  if (_.isNumeric(this.port)) {
    this.port = parseInt(this.port, 10);
  } else {
    this.port = 9200;
  }

  // make sure the path starts with a leading slash
  if (this.path === '/') {
    this.path = '';
  } else if (this.path && this.path.charAt(0) !== '/') {
    this.path = '/' + (this.path || '');
  }

  // strip trailing ':' on the protocol (when config comes from url.parse)
  if (this.protocol.substr(-1) === ':') {
    this.protocol = this.protocol.substring(0, this.protocol.length - 1);
  }
}

Host.prototype.makeUrl = function (params) {
  params = params || {};
  // build the port
  var port = '';
  if (this.port !== Host.defaultPorts[this.protocol]) {
    // add an actual port
    port = ':' + this.port;
  }

  // build the path
  var path = '' + (this.path || '') + (params.path || '');

  // if path doesn't start with '/' add it.
  if (path.charAt(0) !== '/') {
    path = '/' + path;
  }

  // build the query string
  var query = qs.stringify(this.getQuery(params.query));

  var auth = '';
  if (params.auth) {
    auth = params.auth + '@';
  } else if (this.auth) {
    auth = this.auth + '@';
  }

  if (this.host) {
    return this.protocol + '://' + auth + this.host + port + path + (query ? '?' + query : '');
  } else {
    return path + (query ? '?' + query : '');
  }
};

function objectPropertyGetter(prop, preOverride) {
  return function (overrides) {
    if (preOverride) {
      overrides = preOverride(overrides);
    }

    var obj = this[prop];
    if (!obj && !overrides) {
      return null;
    }

    if (overrides) {
      obj = _.assign({}, obj, overrides);
    }

    return _.size(obj) ? obj : null;
  };
}

Host.prototype.getHeaders = objectPropertyGetter('headers');
Host.prototype.getQuery = objectPropertyGetter('query', function (query) {
  return typeof query === 'string' ? qs.parse(query) : query;
});

Host.prototype.toString = function () {
  return this.makeUrl();
};

},{"./utils":213,"querystring":6,"url":7}],202:[function(require,module,exports){
var process=require("__browserify_process");var _ = require('./utils');
var url = require('url');
var EventEmitter = require('events').EventEmitter;

/**
 * Log bridge, which is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)
 * that sends events to one or more outputs/loggers. Setup these loggers by
 * specifying their config as the first argument, or by passing it to addOutput().
 *
 * @class Log
 * @uses Loggers.Stdio
 * @constructor
 * @param {string|Object|ArrayOfStrings|ArrayOfObjects} output - Either the level
 *  to setup a single logger, a full config object for alogger, or an array of
 *  config objects to use for creating log outputs.
 * @param {string} output.level - One of the keys in Log.levels (error, warning, etc.)
 * @param {string} output.type - The name of the logger to use for this output
 */
function Log(config) {
  config = config || {};

  var i;
  var outputs;

  if (config.log) {
    if (_.isArrayOfStrings(config.log)) {
      outputs = [{
        levels: config.log
      }];
    } else {
      outputs = _.createArray(config.log, function (val) {
        if (_.isPlainObject(val)) {
          return val;
        }
        if (typeof val === 'string') {
          return {
            level: val
          };
        }
      });
    }

    if (!outputs) {
      throw new TypeError('Invalid logging output config. Expected either a log level, array of log levels, ' +
        'a logger config object, or an array of logger config objects.');
    }

    for (i = 0; i < outputs.length; i++) {
      this.addOutput(outputs[i]);
    }
  }
}
_.inherits(Log, EventEmitter);

Log.loggers = require('./loggers');

Log.prototype.close = function () {
  this.emit('closing');
  if (this.listenerCount()) {
    console.error('Something is still listening for log events, but the logger is closing.');
    this.clearAllListeners();
  }
};

Log.prototype.listenerCount = function (event) {
  // compatability for node < 0.10
  if (EventEmitter.listenerCount) {
    return EventEmitter.listenerCount(this, event);
  } else {
    return this.listeners(event).length;
  }
};

/**
 * Levels observed by the loggers, ordered by rank
 *
 * @property levels
 * @type Array
 * @static
 */
Log.levels = [
  /**
   * Event fired for error level log entries
   * @event error
   * @param {Error} error - The error object to log
   */
  'error',
  /**
   * Event fired for "warning" level log entries, which usually represent things
   * like correctly formatted error responses from ES (400, ...) and recoverable
   * errors (one node unresponsive)
   *
   * @event warning
   * @param {String} message - A message to be logged
   */
  'warning',
  /**
   * Event fired for "info" level log entries, which usually describe what a
   * client is doing (sniffing etc)
   *
   * @event info
   * @param {String} message - A message to be logged
   */
  'info',
  /**
   * Event fired for "debug" level log entries, which will describe requests sent,
   * including their url (no data, response codes, or exec times)
   *
   * @event debug
   * @param {String} message - A message to be logged
   */
  'debug',
  /**
   * Event fired for "trace" level log entries, which provide detailed information
   * about each request made from a client, including reponse codes, execution times,
   * and a full curl command that can be copied and pasted into a terminal
   *
   * @event trace
   * @param {String} method method, , body, responseStatus, responseBody
   * @param {String} url - The url the request was made to
   * @param {String} body - The body of the request
   * @param {Integer} responseStatus - The status code returned from the response
   * @param {String} responseBody - The body of the response
   */
  'trace'
];

/**
 * Converts a log config value (string or array) to an array of level names which
 * it represents
 *
 * @method parseLevels
 * @static
 * @private
 * @param  {String|ArrayOfStrings} input - Cound be a string to specify the max
 *   level, or an array of exact levels
 * @return {Array} -
 */
Log.parseLevels = function (input) {
  switch (typeof input) {
  case 'string':
    var i = _.indexOf(Log.levels, input);
    if (i >= 0) {
      return Log.levels.slice(0, i + 1);
    }
    /* fall through */
  case 'object':
    if (_.isArray(input)) {
      var valid = _.intersection(input, Log.levels);
      if (valid.length === input.length) {
        return valid;
      }
    }
    /* fall through */
  default:
    throw new TypeError('invalid logging level ' + input + '. Expected zero or more of these options: ' +
      Log.levels.join(', '));
  }
};

/**
 * Combine the array-like param into a simple string
 *
 * @method join
 * @static
 * @private
 * @param  {*} arrayish - An array like object that can be itterated by _.each
 * @return {String} - The final string.
 */
Log.join = function (arrayish) {
  return _.map(arrayish, function (item) {
    if (_.isPlainObject(item)) {
      return _.inspect(item) + '\n';
    } else {
      return item.toString();
    }
  }).join(' ');
};

/**
 * Create a new logger, based on the config.
 *
 * @method addOutput
 * @param {object} config - An object with config options for the logger.
 * @param {String} [config.type=stdio] - The name of an output/logger. Options
 *   can be found in the `src/loggers` directory.
 * @param {String|ArrayOfStrings} [config.levels=warning] - The levels to output
 *   to this logger, when an array is specified no levels other than the ones
 *   specified will be listened to. When a string is specified, that and all lower
 *   levels will be logged.
 * @return {Logger}
 */
Log.prototype.addOutput = function (config) {
  config = config || {};

  // force "levels" key
  config.levels = Log.parseLevels(config.levels || config.level || 'warning');
  delete config.level;

  var Logger = _.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio');
  return new Logger(this, config);
};

/**
 * Log an error
 *
 * @method error
 * @param  {Error|String} error  The Error to log
 * @return {Boolean} - True if any outputs accepted the message
 */
Log.prototype.error = function (e) {
  if (this.listenerCount('error')) {
    return this.emit('error', e instanceof Error ? e : new Error(e));
  }
};


/**
 * Log a warning message
 *
 * @method warning
 * @param  {*} msg* - Any amount of messages that will be joined before logged
 * @return {Boolean} - True if any outputs accepted the message
 */
Log.prototype.warning = function (/* ...msg */) {
  if (this.listenerCount('warning')) {
    return this.emit('warning', Log.join(arguments));
  }
};


/**
 * Log useful info about what's going on
 *
 * @method info
 * @param  {*} msg* - Any amount of messages that will be joined before logged
 * @return {Boolean} - True if any outputs accepted the message
 */
Log.prototype.info = function (/* ...msg */) {
  if (this.listenerCount('info')) {
    return this.emit('info', Log.join(arguments));
  }
};

/**
 * Log a debug level message
 *
 * @method debug
 * @param  {*} msg* - Any amount of messages that will be joined before logged
 * @return {Boolean} - True if any outputs accepted the message
 */
Log.prototype.debug = function (/* ...msg */) {
  if (this.listenerCount('debug')) {
    return this.emit('debug', Log.join(arguments) /*+ _.getStackTrace(Log.prototype.debug)*/);
  }
};

/**
 * Log a trace level message
 *
 * @method trace
 * @param {String} method - HTTP request method
 * @param {String|Object} requestUrl - URL requested. If the value is an object,
 *   it is expected to be the return value of Node's url.parse()
 * @param {String} body - The request's body
 * @param {String} responseBody - body returned from ES
 * @param {String} responseStatus - HTTP status code
 * @return {Boolean} - True if any outputs accepted the message
 */
Log.prototype.trace = function (method, requestUrl, body, responseBody, responseStatus) {
  if (this.listenerCount('trace')) {
    return this.emit('trace', Log.normalizeTraceArgs(method, requestUrl, body, responseBody, responseStatus));
  }
};

Log.normalizeTraceArgs = function (method, requestUrl, body, responseBody, responseStatus) {
  if (typeof requestUrl === 'string') {
    requestUrl = url.parse(requestUrl, true, true);
  } else {
    requestUrl = _.clone(requestUrl);
    if (requestUrl.path) {
      requestUrl.query = url.parse(requestUrl.path, true, false).query;
    }
    if (!requestUrl.pathname && requestUrl.path) {
      requestUrl.pathname = requestUrl.path.split('?').shift();
    }
  }

  delete requestUrl.auth;

  return {
    method: method,
    url: url.format(requestUrl),
    body: body,
    status: responseStatus,
    response: responseBody
  };
};

module.exports = Log;

},{"./loggers":204,"./utils":213,"__browserify_process":13,"events":4,"url":7}],203:[function(require,module,exports){
var _ = require('./utils');

/**
 * Abstract class providing common functionality to loggers
 * @param {[type]} log [description]
 * @param {[type]} config [description]
 */
function LoggerAbstract(log, config) {
  this.log = log;
  this.listeningLevels = [];

  _.makeBoundMethods(this);

  // when the log closes, remove our event listeners
  this.log.once('closing', this.bound.cleanUpListeners);

  this.setupListeners(config.levels);
}

function padNumToTen(n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}

/**
 * Create a timestamp string used in the format function. Defers to Log.timestamp if it is defined,
 * Also, feel free to override this at the logger level.
 * @return {String} - Timestamp in ISO 8601 UTC
 */
LoggerAbstract.prototype.timestamp = function () {
  var d = new Date();
  return d.getUTCFullYear() + '-' +
    padNumToTen(d.getUTCMonth() + 1) + '-' +
    padNumToTen(d.getUTCDate()) + 'T' +
    padNumToTen(d.getUTCHours()) + ':' +
    padNumToTen(d.getUTCMinutes()) + ':' +
    padNumToTen(d.getUTCSeconds()) + 'Z';
};

function indent(text, spaces) {
  var space = _.repeat(' ', spaces || 2);
  return (text || '').split(/\r?\n/).map(function (line) {
    return space + line;
  }).join('\n');
}

LoggerAbstract.prototype.format = function (label, message) {
  return label + ': ' + this.timestamp() + '\n' + indent(message) + '\n\n';
};

LoggerAbstract.prototype.write = function () {
  throw new Error('This should be overwritten by the logger');
};

/**
 * Clear the current event listeners and then re-listen for events based on the level specified
 *
 * @method setupListeners
 * @private
 * @param  {Integer} level - The max log level that this logger should listen to
 * @return {undefined}
 */
LoggerAbstract.prototype.setupListeners = function (levels) {
  this.cleanUpListeners();

  this.listeningLevels = [];

  _.each(levels, function (level) {
    var fnName = 'on' + _.ucfirst(level);
    if (this.bound[fnName]) {
      this.listeningLevels.push(level);
      this.log.on(level, this.bound[fnName]);
    } else {
      throw new Error('Unable to listen for level "' + level + '"');
    }
  }, this);
};

/**
 * Clear the current event listeners
 *
 * @method cleanUpListeners
 * @private
 * @return {undefined}
 */
LoggerAbstract.prototype.cleanUpListeners = _.handler(function () {
  _.each(this.listeningLevels, function (level) {
    this.log.removeListener(level, this.bound['on' + _.ucfirst(level)]);
  }, this);
});

/**
 * Handler for the logs "error" event
 *
 * @method onError
 * @private
 * @param  {Error} e - The Error object to log
 * @return {undefined}
 */
LoggerAbstract.prototype.onError = _.handler(function (e) {
  this.write((e.name === 'Error' ? 'ERROR' : e.name), e.stack);
});

/**
 * Handler for the logs "warning" event
 *
 * @method onWarning
 * @private
 * @param  {String} msg - The message to be logged
 * @return {undefined}
 */
LoggerAbstract.prototype.onWarning = _.handler(function (msg) {
  this.write('WARNING', msg);
});

/**
 * Handler for the logs "info" event
 *
 * @method onInfo
 * @private
 * @param  {String} msg - The message to be logged
 * @return {undefined}
 */
LoggerAbstract.prototype.onInfo = _.handler(function (msg) {
  this.write('INFO', msg);
});

/**
 * Handler for the logs "debug" event
 *
 * @method onDebug
 * @private
 * @param  {String} msg - The message to be logged
 * @return {undefined}
 */
LoggerAbstract.prototype.onDebug = _.handler(function (msg) {
  this.write('DEBUG', msg);
});

/**
 * Handler for the logs "trace" event
 *
 * @method onTrace
 * @private
 * @param  {String} msg - The message to be logged
 * @return {undefined}
 */
LoggerAbstract.prototype.onTrace = _.handler(function (requestDetails) {
  this.write('TRACE', this._formatTraceMessage(requestDetails));
});

LoggerAbstract.prototype._formatTraceMessage = function (req) {
  return '-> ' + req.method + ' ' + req.url + '\n' +
    this._prettyJson(req.body) + '\n' +
    '<- ' + req.status + '\n' +
    this._prettyJson(req.response);
/*
-> GET https://sldfkjsdlfksjdf:9200/slsdkfjlxckvxhclks?sdlkj=sdlfkje
{
  asdflksjdf
}

<- 502
{
  sldfksjdlf
}
*/
};

LoggerAbstract.prototype._prettyJson = function (body) {
  try {
    if (typeof body === 'string') {
      body = JSON.parse(body);
    }
    return JSON.stringify(body, null, '  ').replace(/'/g, '\\u0027');
  } catch (e) {
    return typeof body === 'string' ? body : '';
  }
};

module.exports = LoggerAbstract;

},{"./utils":213}],204:[function(require,module,exports){
module.exports = {
  console: require('./console')
};

},{"./console":205}],205:[function(require,module,exports){
/**
 * Special version of the Stream logger, which logs errors and warnings to stderr and all other
 * levels to stdout.
 *
 * @class Loggers.Console
 * @extends LoggerAbstract
 * @constructor
 * @param {Object} config - The configuration for the Logger
 * @param {string} config.level - The highest log level for this logger to output.
 * @param {Log} bridge - The object that triggers logging events, which we will record
 */

module.exports = Console;

var LoggerAbstract = require('../logger');
var _ = require('../utils');

function Console(log, config) {
  LoggerAbstract.call(this, log, config);

  // config/state
  this.color = _.has(config, 'color') ? !!config.color : true;
}
_.inherits(Console, LoggerAbstract);

/**
 * Override the LoggerAbstract's setup listeners to do a little extra setup
 *
 * @param  {Array} levels - The levels that we should be listeneing for
 */
Console.prototype.setupListeners = function (levels) {
  // call the super method
  LoggerAbstract.prototype.setupListeners.call(this, levels);
};

Console.prototype.write = function (label, message, to) {
  if (console[to]) {
    console[to](this.format(label, message));
  }
};

/**
 * Handler for the bridges "error" event
 *
 * @method onError
 * @private
 * @param  {Error} e - The Error object to log
 * @return {undefined}
 */
Console.prototype.onError = _.handler(function (e) {
  var to = console.error ? 'error' : 'log';
  this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack || e.message, to);
});

/**
 * Handler for the bridges "warning" event
 *
 * @method onWarning
 * @private
 * @param  {String} msg - The message to be logged
 * @return {undefined}
 */
Console.prototype.onWarning = _.handler(function (msg) {
  this.write('WARNING', msg, console.warn ? 'warn' : 'log');
});

/**
 * Handler for the bridges "info" event
 *
 * @method onInfo
 * @private
 * @param  {String} msg - The message to be logged
 * @return {undefined}
 */
Console.prototype.onInfo = _.handler(function (msg) {
  this.write('INFO', msg, console.info ? 'info' : 'log');
});

/**
 * Handler for the bridges "debug" event
 *
 * @method onDebug
 * @private
 * @param  {String} msg - The message to be logged
 * @return {undefined}
 */
Console.prototype.onDebug = _.handler(function (msg) {
  this.write('DEBUG', msg, console.debug ? 'debug' : 'log');
});
/**
 * Handler for the bridges "trace" event
 *
 * @method onTrace
 * @private
 * @return {undefined}
 */
Console.prototype.onTrace = _.handler(function (msg) {
  this.write('TRACE', this._formatTraceMessage(msg), 'log');
});

},{"../logger":203,"../utils":213}],206:[function(require,module,exports){
var _ = require('./utils');
var extractHostPartsRE = /\[\/*([^:]+):(\d+)\]/;

function makeNodeParser(hostProp) {
  return function (nodes) {
    return _.transform(nodes, function (hosts, node, id) {
      if (!node[hostProp]) {
        return;
      }

      var hostnameMatches = extractHostPartsRE.exec(node[hostProp]);
      if (!hostnameMatches) {
        throw new Error('node\'s ' + hostProp + ' property (' + JSON.stringify(node[hostProp]) +
          ') does not match the expected pattern ' + extractHostPartsRE + '.');
      }

      hosts.push({
        host: hostnameMatches[1],
        port: parseInt(hostnameMatches[2], 10),
        _meta: {
          id: id,
          name: node.name,
          hostname: node.hostname,
          version: node.version
        }
      });
    }, []);
  };
}

module.exports = makeNodeParser('http_address');
module.exports.thrift = makeNodeParser('transport_address');

},{"./utils":213}],207:[function(require,module,exports){
module.exports = {
  random: require('./random'),
  roundRobin: require('./round_robin')
};

},{"./random":208,"./round_robin":209}],208:[function(require,module,exports){
/**
 * Selects a connection randomly
 *
 * @module selectors
 * @type {Function}
 * @param {Array} connection - The list of connections to choose from
 * @return {Connection} - The selected connection
 */
module.exports = function RandomSelector(connections) {
  return connections[Math.floor(Math.random() * connections.length)];
};

},{}],209:[function(require,module,exports){
/**
 * Selects a connection the simplest way possible, Round Robin
 *
 * @module selectors
 * @type {Function}
 * @param {Array} connections - The list of connections that this selector needs to choose from
 * @return {Connection} - The selected connection
 */
module.exports = function (connections) {
  var connection = connections[0];
  connections.push(connections.shift());
  return connection;
};

},{}],210:[function(require,module,exports){
/**
 * Simple JSON serializer
 * @type {[type]}
 */
module.exports = Json;

var _ = require('../utils');

function Json() {}

/**
 * Converts a value into a string, or an error
 * @param  {*} val - Any value, methods are stripped and
 * see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify about other params
 * @return {String|Error} - A string is always returned, unless an error occured. then it will be that error.
 */
Json.prototype.serialize = function (val, replacer, spaces) {
  switch (typeof val) {
  case 'string':
    return val;
  case 'object':
    if (val) {
      return JSON.stringify(val, replacer, spaces);
    }
    /* falls through */
  default:
    return;
  }
};

/**
 * Parse a JSON string, if it is already parsed it is ignored
 * @param  {String} str - the string to parse
 * @return {[type]}
 */
Json.prototype.deserialize = function (str) {
  if (typeof str === 'string') {
    try {
      return JSON.parse(str);
    } catch (e) {}
  }
};

Json.prototype.bulkBody = function (val) {
  var body = '', i;

  if (_.isArray(val)) {
    for (i = 0; i < val.length; i++) {
      body += this.serialize(val[i]) + '\n';
    }
  } else if (typeof val === 'string') {
    // make sure the string ends in a new line
    body = val + (val[val.length - 1] === '\n' ? '' : '\n');
  } else {
    throw new TypeError('Bulk body should either be an Array of commands/string, or a String');
  }

  return body;
};

},{"../utils":213}],211:[function(require,module,exports){
/**
 * Class that manages making request, called by all of the API methods.
 * @type {[type]}
 */
module.exports = Transport;

var _ = require('./utils');
var errors = require('./errors');
var Host = require('./host');
var Promise = require('bluebird');
var patchSniffOnConnectionFault = require('./transport/sniff_on_connection_fault');

function Transport(config) {
  var self = this;
  config = config || {};

  var LogClass = (typeof config.log === 'function') ? config.log : require('./log');
  config.log = this.log = new LogClass(config);

  // setup the connection pool
  var ConnectionPool = _.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main');
  this.connectionPool = new ConnectionPool(config);

  // setup the serializer
  var Serializer = _.funcEnum(config, 'serializer', Transport.serializers, 'json');
  this.serializer = new Serializer(config);

  // setup the nodesToHostCallback
  this.nodesToHostCallback = _.funcEnum(config, 'nodesToHostCallback', Transport.nodesToHostCallbacks, 'main');

  // setup max retries
  this.maxRetries = config.hasOwnProperty('maxRetries') ? config.maxRetries : 3;

  // setup endpoint to use for sniffing
  this.sniffEndpoint = config.hasOwnProperty('sniffEndpoint') ? config.sniffEndpoint : '/_nodes/_all/clear';

  // setup requestTimeout default
  this.requestTimeout = config.hasOwnProperty('requestTimeout') ? config.requestTimeout : 30000;

  if (config.hasOwnProperty('defer')) {
    this.defer = config.defer;
  }

  // randomizeHosts option
  var randomizeHosts = config.hasOwnProperty('randomizeHosts') ? !!config.randomizeHosts : true;

  if (config.host) {
    config.hosts = config.host;
  }

  if (config.hosts) {
    var hostsConfig = _.createArray(config.hosts, function (val) {
      if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) {
        return val;
      }
    });
    if (!hostsConfig) {
      throw new TypeError('Invalid hosts config. Expected a URL, an array of urls, a host config object, ' +
        'or an array of host config objects.');
    }

    var hosts = _.map(hostsConfig, function (conf) {
      return (conf instanceof Host) ? conf : new Host(conf);
    });

    if (randomizeHosts) {
      hosts = _.shuffle(hosts);
    }

    this.connectionPool.setHosts(hosts);
  }

  if (config.sniffOnStart) {
    this.sniff();
  }

  if (config.sniffInterval) {
    this._timeout(function doSniff() {
      self.sniff();
      self._timeout(doSniff, config.sniffInterval);
    }, config.sniffInterval);
  }

  if (config.sniffOnConnectionFault) {
    patchSniffOnConnectionFault(this);
  }
}

Transport.connectionPools = {
  main: require('./connection_pool')
};

Transport.serializers = {
  json: require('./serializers/json')
};

Transport.nodesToHostCallbacks = {
  main: require('./nodes_to_host')
};

Transport.prototype.defer = function () {
  return Promise.defer();
};

/**
 * Perform a request with the client's transport
 *
 * @method request
 * @ async body writing
 * @ abort
 * @ access to custom headers, modifying of request in general
 * @param {object} params
 * @param {Number} params.requestTimeout - timeout for the entire request (inculding all retries)
 * @param {Number} params.maxRetries - number of times the request will be re-run in
 *   the original node chosen can not be connected to.
 * @param {String} params.url - The url for the request
 * @param {String} params.method - The HTTP method for the request
 * @param {String} params.body - The body of the HTTP request
 * @param {Function} cb - A function to call back with (error, responseBody, responseStatus)
 */
Transport.prototype.request = function (params, cb) {
  var self = this;
  var remainingRetries = this.maxRetries;
  var requestTimeout = this.requestTimeout;

  var connection; // set in sendReqWithConnection
  var aborted = false; // several connector will respond with an error when the request is aborted
  var requestAborter; // an abort function, returned by connection#request()
  var requestTimeoutId; // the id of the ^timeout
  var ret; // the object returned to the user, might be a promise
  var defer; // the defer object, will be set when we are using promises.

  self.log.debug('starting request', params);

  if (params.body && params.method === 'GET') {
    _.nextTick(respond, new TypeError('Body can not be sent with method "GET"'));
    return;
  }

  // serialize the body
  if (params.body) {
    params.body = self.serializer[params.bulkBody ? 'bulkBody' : 'serialize'](params.body);
  }

  if (params.hasOwnProperty('maxRetries')) {
    remainingRetries = params.maxRetries;
  }

  if (params.hasOwnProperty('requestTimeout')) {
    requestTimeout = params.requestTimeout;
  }

  params.req = {
    method: params.method,
    path: params.path || '/',
    query: params.query,
    body: params.body,
  };

  function sendReqWithConnection(err, _connection) {
    if (aborted) {
      return;
    }

    if (err) {
      respond(err);
    } else if (_connection) {
      connection = _connection;
      requestAborter = connection.request(params.req, checkRespForFailure);
    } else {
      self.log.warning('No living connections');
      respond(new errors.NoConnections());
    }
  }

  function checkRespForFailure(err, body, status, headers) {
    if (aborted) {
      return;
    }

    requestAborter = void 0;

    if (err) {
      connection.setStatus('dead');
      if (remainingRetries) {
        remainingRetries--;
        self.log.error('Request error, retrying' + (err.message ? ' -- ' + err.message : ''));
        self.connectionPool.select(sendReqWithConnection);
      } else {
        self.log.error('Request complete with error' + (err.message ? ' -- ' + err.message : ''));
        respond(new errors.ConnectionFault(err));
      }
    } else {
      self.log.info('Request complete');
      respond(void 0, body, status, headers);
    }
  }

  function respond(err, body, status, headers) {
    if (aborted) {
      return;
    }

    self._timeout(requestTimeoutId);
    var parsedBody;
    var isJson = !headers || (headers['content-type'] && ~headers['content-type'].indexOf('application/json'));

    if (!err && body) {
      if (isJson) {
        parsedBody = self.serializer.deserialize(body);
        if (parsedBody == null) {
          err = new errors.Serialization();
          parsedBody = body;
        }
      } else {
        parsedBody = body;
      }
    }

    // does the response represent an error?
    if (
      (!err || err instanceof errors.Serialization)
      && (status < 200 || status >= 300)
      && (!params.ignore || !_.contains(params.ignore, status))
    ) {
      if (errors[status]) {
        err = new errors[status](parsedBody && parsedBody.error);
      } else {
        err = new errors.Generic('unknown error');
      }
    }

    // can we cast notfound to false?
    if (params.castExists) {
      if (err && err instanceof errors.NotFound) {
        parsedBody = false;
        err = void 0;
      } else {
        parsedBody = !err;
      }
    }

    // how do we send the response?
    if (typeof cb === 'function') {
      if (err) {
        cb(err, parsedBody, status);
      } else {
        cb(void 0, parsedBody, status);
      }
    } else if (err) {
      err.body = parsedBody;
      err.status = status;
      defer.reject(err);
    } else {
      defer.resolve(parsedBody);
    }
  }

  function abortRequest() {
    if (aborted) {
      return;
    }

    aborted = true;
    remainingRetries = 0;
    self._timeout(requestTimeoutId);
    if (typeof requestAborter === 'function') {
      requestAborter();
    }
  }

  if (requestTimeout && requestTimeout !== Infinity) {
    requestTimeoutId = this._timeout(function () {
      respond(new errors.RequestTimeout('Request Timeout after ' + requestTimeout + 'ms'));
      abortRequest();
    }, requestTimeout);
  }

  // determine the response based on the presense of a callback
  if (typeof cb === 'function') {
    ret = {
      abort: abortRequest
    };
  } else {
    defer = this.defer();
    ret = defer.promise;
    ret.abort = abortRequest;
  }


  if (connection) {
    sendReqWithConnection(void 0, connection);
  } else {
    self.connectionPool.select(sendReqWithConnection);
  }

  return ret;
};

Transport.prototype._timeout = function (cb, delay) {
  this._timers = this._timers || [];
  var id;

  if ('function' !== typeof cb) {
    id = cb;
    cb = void 0;
  }

  if (cb) {
    // set the timer
    id = setTimeout(cb, delay);
    this._timers.push(id);
    return id;
  }

  if (id) {
    clearTimeout(id);

    var i = this._timers.indexOf(id);
    if (i !== -1) {
      this._timers.splice(i, 1);
    }
  }
};

/**
 * Ask an ES node for a list of all the nodes, add/remove nodes from the connection
 * pool as appropriate
 *
 * @param  {Function} cb - Function to call back once complete
 */
Transport.prototype.sniff = function (cb) {
  var connectionPool = this.connectionPool;
  var nodesToHostCallback = this.nodesToHostCallback;
  var log = this.log;

  // make cb a function if it isn't
  cb = typeof cb === 'function' ? cb : _.noop;

  this.request({
    path: this.sniffEndpoint,
    method: 'GET'
  }, function (err, resp, status) {
    if (!err && resp && resp.nodes) {
      var hostsConfigs;

      try {
        hostsConfigs = nodesToHostCallback(resp.nodes);
      } catch (e) {
        log.error(new Error('Unable to convert node list from ' + this.sniffEndpoint +
          ' to hosts durring sniff. Encountered error:\n' + (e.stack || e.message)));
        return;
      }

      connectionPool.setHosts(_.map(hostsConfigs, function (hostConfig) {
        return new Host(hostConfig);
      }));
    }
    cb(err, resp, status);
  });
};

/**
 * Close the Transport, which closes the logs and connection pool
 * @return {[type]} [description]
 */
Transport.prototype.close = function () {
  this.log.close();
  _.each(this._timers, clearTimeout);
  this.connectionPool.close();
};
},{"./connection_pool":197,"./errors":200,"./host":201,"./log":202,"./nodes_to_host":206,"./serializers/json":210,"./transport/sniff_on_connection_fault":212,"./utils":213,"bluebird":1}],212:[function(require,module,exports){
var _ = require('../utils');


/**
 * Patch the transport's connection pool to schedule a sniff after a connection fails.
 * When a connection fails for the first time it will schedule a sniff 1 second in the
 * future, and increase the timeout based on the deadTimeout algorithm chosen by the
 * connectionPool, and the number of times the sniff has failed.
 *
 * @param  {Transport} transport - the transport that will be using this behavior
 * @return {undefined}
 */
module.exports = function setupSniffOnConnectionFault(transport) {
  var failures = 0;
  var pool = transport.connectionPool;
  var originalOnDied = pool._onConnectionDied;

  // do the actual sniff, if the sniff is unable to
  // connect to a node this function will be called again by the connectionPool
  var work = function () {
    work.timerId = transport._timeout(work.timerId);
    transport.sniff();
  };

  // create a function that will count down to a
  // point n milliseconds into the future
  var countdownTo = function (ms) {
    var start = _.now();
    return function () {
      return start - ms;
    };
  };

  // overwrite the function, but still call it
  pool._onConnectionDied = function (connection, wasAlreadyDead) {
    var ret = originalOnDied.call(pool, connection, wasAlreadyDead);

    // clear the failures if this is the first failure we have seen
    failures = work.timerId ? failures + 1 : 0;

    var ms = pool.calcDeadTimeout(failures, 1000);

    if (work.timerId && ms < work.timerId && work.countdown()) {
      // clear the timer
      work.timerId = transport._timeout(work.timerId);
    }

    if (!work.timerId) {
      work.timerId = transport._timeout(work, ms);
      work.countdown = countdownTo(ms);
    }

    return ret;
  };

  pool._onConnectionDied.restore = function () {
    pool._onConnectionDied = originalOnDied;
  };
};
},{"../utils":213}],213:[function(require,module,exports){
var process=require("__browserify_process"),Buffer=require("__browserify_Buffer").Buffer;var path = require('path');
var _ = require('lodash-node/modern');
var nodeUtils = require('util');

/**
 * Custom utils library, basically a modified version of [lodash](http://lodash.com/docs) +
 * [node.utils](http://nodejs.org/api/util.html#util_util) that doesn't use mixins to prevent
 * confusion when requiring lodash itself.
 *
 * @class utils
 * @static
 */
var utils = _.extend({}, _, nodeUtils);
_ = utils;

/**
 * Link to [path.join](http://nodejs.org/api/path.html#path_path_join_path1_path2)
 *
 * @method utils.joinPath
 * @type {function}
 */
utils.joinPath = path.join;

/**
 * Recursively merge two objects, walking into each object and concating arrays. If both to and from have a value at a
 * key, but the values' types don't match to's value is left unmodified. Only Array and Object values are merged - that
 * it to say values with a typeof "object"
 *
 * @param  {Object} to - Object to merge into (no cloning, the original object
 *   is modified)
 * @param  {Object} from - Object to pull changed from
 * @return {Object} - returns the modified to value
 */
utils.deepMerge = function (to, from) {
  _.each(from, function (fromVal, key) {
    switch (typeof to[key]) {
    case 'undefined':
      to[key] = from[key];
      break;
    case 'object':
      if (_.isArray(to[key]) && _.isArray(from[key])) {
        to[key] = to[key].concat(from[key]);
      }
      else if (_.isPlainObject(to[key]) && _.isPlainObject(from[key])) {
        utils.deepMerge(to[key], from[key]);
      }
    }
  });
  return to;
};

/**
 * Test if a value is an array and it's contents are of a specific type
 *
 * @method isArrayOf<Strings|Object|Array|Finite|Function|RegExp>s
 * @param  {Array} arr - An array to check
 * @return {Boolean}
 */
_.each([
  'String',
  'Object',
  'PlainObject',
  'Array',
  'Finite',
  'Function',
  'RegExp'
], function (type) {
  var check = _['is' + type];

  utils['isArrayOf' + type + 's'] = function (arr) {
    // quick shallow check of arrays
    return _.isArray(arr) && _.every(arr.slice(0, 10), check);
  };
});


/**
 * Capitalize the first letter of a word
 *
 * @method  ucfirst
 * @param  {string} word - The word to transform
 * @return {string}
 */
utils.ucfirst = function (word) {
  return word[0].toUpperCase() + word.substring(1).toLowerCase();
};

/**
 * Base algo for studlyCase and camelCase
 * @param  {boolean} firstWordCap - Should the first character of the first word be capitalized
 * @return {Function}
 */
function adjustWordCase(firstWordCap, otherWordsCap, sep) {
  return function (string) {
    var i = 0;
    var words = [];
    var word = '';
    var code, c, upper, lower;

    for (; i < string.length; i++) {
      code = string.charCodeAt(i);
      c = string.charAt(i);
      lower = (code >= 97 && code <= 122) || (code >= 48 && code <= 57);
      upper = code >= 65 && code <= 90;

      if (upper || !lower) {
        // new word
        if (word.length) {
          words.push(word);
        }
        word = '';
      }

      if (upper || lower) {
        if (lower && word.length) {
          word += c;
        } else {
          if ((!words.length && firstWordCap) || (words.length && otherWordsCap)) {
            word = c.toUpperCase();
          }
          else {
            word = c.toLowerCase();
          }
        }
      }
    }
    if (word.length) {
      words.push(word);
    }
    // add the leading underscore back to strings the had it originally
    if (words.length && string.charAt(0) === '_') {
      words[0] = '_' + words[0];
    }
    return words.join(sep);
  };
}

/**
 * Transform a string into StudlyCase
 *
 * @method studlyCase
 * @param  {String} string
 * @return {String}
 */
utils.studlyCase = adjustWordCase(true, true, '');

/**
 * Transform a string into camelCase
 *
 * @method camelCase
 * @param  {String} string
 * @return {String}
 */
utils.camelCase = adjustWordCase(false, true, '');

/**
 * Transform a string into snakeCase
 *
 * @method snakeCase
 * @param  {String} string
 * @return {String}
 */
utils.snakeCase = adjustWordCase(false, false, '_');

/**
 * Lower-case a string, and return an empty string if any is not a string
 *
 * @param any {*} - Something or nothing
 * @returns {string}
 */
utils.toLowerString = function (any) {
  if (any) {
    if (typeof any !== 'string') {
      any = any.toString();
    }
  } else {
    any = '';
  }
  return any.toLowerCase();
};

/**
 * Upper-case the string, return an empty string if any is not a string
 *
 * @param any {*} - Something or nothing
 * @returns {string}
 */
utils.toUpperString = function (any) {
  if (any) {
    if (typeof any !== 'string') {
      any = any.toString();
    }
  } else {
    any = '';
  }
  return any.toUpperCase();
};

/**
 * Test if a value is "numeric" meaning that it can be transformed into something besides NaN
 *
 * @method isNumeric
 * @param  {*} val
 * @return {Boolean}
 */
utils.isNumeric = function (val) {
  return typeof val !== 'object' && val - parseFloat(val) >= 0;
};

// regexp to test for intervals
var intervalRE = /^(\d+(?:\.\d+)?)([Mwdhmsy])$/;

/**
 * Test if a string represents an interval (eg. 1m, 2Y)
 *
 * @method isInterval
 * @param {String} val
 * @return {Boolean}
 */
utils.isInterval = function (val) {
  return !!(val.match && val.match(intervalRE));
};

/**
 * Repeat a string n times
 *
 * @ TestPerformance
 * @method repeat
 * @param {String} what - The string to repeat
 * @param {Number} times - Times the string should be repeated
 * @return {String}
 */
utils.repeat = function (what, times) {
  return (new Array(times + 1)).join(what);
};

/**
 * Call a function, applying the arguments object to it in an optimized way, rather than always turning it into an array
 *
 * @param func {Function} - The function to execute
 * @param context {*} - The context the function will be executed with
 * @param args {Arguments} - The arguments to send to func
 * @param [sliceIndex=0] {Integer} - The index that args should be sliced at, before feeding args to func
 * @returns {*} - the return value of func
 */
utils.applyArgs = function (func, context, args, sliceIndex) {
  sliceIndex = sliceIndex || 0;
  switch (args.length - sliceIndex) {
  case 0:
    return func.call(context);
  case 1:
    return func.call(context, args[0 + sliceIndex]);
  case 2:
    return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex]);
  case 3:
    return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex], args[2 + sliceIndex]);
  case 4:
    return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex], args[2 + sliceIndex], args[3 + sliceIndex]);
  case 5:
    return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex],
      args[2 + sliceIndex], args[3 + sliceIndex], args[4 + sliceIndex]);
  default:
    return func.apply(context, Array.prototype.slice.call(args, sliceIndex));
  }
};

/**
 * Schedule a function to be called on the next tick, and supply it with these arguments
 * when it is called.
 * @return {[type]} [description]
 */
_.nextTick = function (cb) {
  // bind the function and schedule it
  process.nextTick(_.bindKey(_, 'applyArgs', cb, null, arguments, 1));
};

/**
 * Marks a method as a handler. Currently this just makes a property on the method
 * flagging it to be bound to the object at object creation when "makeBoundMethods" is called
 *
 * ```
 * ClassName.prototype.methodName = _.handler(function () {
 *   // this will always be bound when called via classInstance.bound.methodName
 *   this === classInstance
 * });
 * ```
 *
 * @alias _.scheduled
 * @param  {Function} func - The method that is being defined
 * @return {Function}
 */
_.handler = function (func) {
  func._provideBound = true;
  return func;
};
_.scheduled = _.handler;

/**
 * Creates an "bound" property on an object, which all or a subset of methods from
 * the object which are bound to the original object.
 *
 * ```
 * var obj = {
 *   onEvent: function () {}
 * };
 *
 * _.makeBoundMethods(obj);
 *
 * obj.bound.onEvent() // is bound to obj, and can safely be used as an event handler.
 * ```
 *
 * @param {Object} obj - The object to bind the methods to
 */
_.makeBoundMethods = function (obj) {
  obj.bound = {};
  for (var prop in obj) {
    // dearest maintainer, we want to look through the prototype
    if (typeof obj[prop] === 'function' && obj[prop]._provideBound === true) {
      obj.bound[prop] = _.bind(obj[prop], obj);
    }
  }
};

_.noop = function () {};

/**
 * Implements the standard "string or constructor" check that I was copy/pasting everywhere
 * @param  {String|Function} val - the value that the user passed in
 * @param  {Object} opts - a map of the options
 * @return {Function|undefined} - If a valid option was specified, then the constructor is returned
 */
_.funcEnum = function (config, name, opts, def) {
  var val = config[name];
  switch (typeof val) {
  case 'undefined':
    return opts[def];
  case 'function':
    return val;
  case 'string':
    if (opts.hasOwnProperty(val)) {
      return opts[val];
    }
    /* falls through */
  default:
    var err = 'Invalid ' + name + ' "' + val + '", expected a function';
    switch (_.size(opts)) {
    case 0:
      break;
    case 1:
      err += ' or ' + _.keys(opts)[0];
      break;
    default:
      err += ' or one of ' + _.keys(opts).join(', ');
      break;
    }
    throw new TypeError(err);
  }
};

/**
 * Accepts any object and attempts to convert it into an array. If the object passed in is not
 * an array it will be wrapped in one. Then the transform/map function will be called for each element
 * and create a new array that is returned. If the map function fails to return something, the loop is
 * halted and false is returned instead of an array.
 *
 * @param  {*} input - The value to convert
 * @param  {Function} transform - A function called for each element of the resulting array
 * @return {Array|false} - an array on success, or false on failure.
 */
_.createArray = function (input, transform) {
  transform = typeof transform === 'function' ? transform : _.identity;
  var output = [];
  var item;
  var i;

  if (!_.isArray(input)) {
    input = [input];
  }

  for (i = 0; i < input.length; i++) {
    item = transform(input[i]);
    if (item === void 0) {
      return false;
    } else {
      output.push(item);
    }
  }
  return output;
};

/**
 * Takes a WritableStream, and returns the chunks that have not successfully written, returning them as a string.
 *
 * ONLY WORKS FOR TEXT STREAMS
 *
 * @param  {WritableStream} stream - an instance of stream.Writable
 * @return {string} - the remaining test to be written to the stream
 */
_.getUnwrittenFromStream = function (stream) {
  if (stream && stream._writableState && stream._writableState.buffer) {
    // flush the write buffer to disk
    var writeBuffer = stream._writableState.buffer;
    var out = '';
    if (writeBuffer.length) {
      _.each(writeBuffer, function (writeReq) {
        if (writeReq.chunk) {
          // 0.9.12+ uses WriteReq objects with a chunk prop
          out += '' + writeReq.chunk;
        } else if (_.isArray(writeReq) && (typeof writeReq[0] === 'string' || Buffer.isBuffer(writeReq[0]))) {
          // 0.9.4 - 0.9.9 buffers are arrays of arrays like [[chunk, cb], [chunk, undef], ...].
          out += '' + writeReq[0];
        } else {
          return false;
        }
      });
    }
    return out;
  }
};

/**
 * return the current time in milliseconds since epoch
 */
_.now = function () {
  return (typeof Date.now === 'function') ? Date.now() : (new Date()).getTime();
};

module.exports = utils;

},{"__browserify_Buffer":12,"__browserify_process":13,"lodash-node/modern":87,"path":5,"util":8}]},{},[189])
;
;
/*! elastic.js - v1.1.1 - 2014-03-21
 * https://github.com/fullscale/elastic.js
 * Copyright (c) 2014 FullScale Labs, LLC; Licensed MIT */

/**
 @namespace
 @name ejs
 @desc All elastic.js modules are organized under the ejs namespace.
 */
(function () {
    'use strict';

    var

      // save reference to global object
      // `window` in browser
      // `exports` on server
      root = this,

      // save the previous version of ejs
      _ejs = root && root.ejs,

      // from underscore.js, used in utils
      ArrayProto = Array.prototype,
      ObjProto = Object.prototype,
      slice = ArrayProto.slice,
      toString = ObjProto.toString,
      hasOwnProp = ObjProto.hasOwnProperty,
      nativeForEach = ArrayProto.forEach,
      nativeIsArray = Array.isArray,
      nativeIndexOf = ArrayProto.indexOf,
      breaker = {},
      has,
      each,
      extend,
      indexOf,
      isArray,
      isObject,
      isString,
      isNumber,
      isBoolean,
      isFunction,
      isEJSObject, // checks if valid ejs object
      isQuery, // checks valid ejs Query object
      isRescore, // checks valid ejs Rescore object
      isFilter, // checks valid ejs Filter object
      isFacet, // checks valid ejs Facet object
      isAggregation, // checks valid ejs Aggregation object
      isScriptField, // checks valid ejs ScriptField object
      isGeoPoint, // checks valid ejs GeoPoint object
      isIndexedShape, // checks valid ejs IndexedShape object
      isShape, // checks valid ejs Shape object
      isSort, // checks valid ejs Sort object
      isHighlight, // checks valid ejs Highlight object
      isSuggest, // checks valid ejs Suggest object
      isGenerator, // checks valid ejs Generator object
      isScoreFunction, // checks valid ejs ScoreFunction object

      // create ejs object
      ejs;

    if (typeof exports !== 'undefined') {
        ejs = exports;
    } else {
        ejs = root.ejs = {};
    }

    /* Utility methods, most of which are pulled from underscore.js. */

    // Shortcut function for checking if an object has a given property directly
    // on itself (in other words, not on a prototype).
    has = function (obj, key) {
        return hasOwnProp.call(obj, key);
    };

    // The cornerstone, an `each` implementation, aka `forEach`.
    // Handles objects with the built-in `forEach`, arrays, and raw objects.
    // Delegates to **ECMAScript 5**'s native `forEach` if available.
    each = function (obj, iterator, context) {
        if (obj == null) {
            return;
        }
        if (nativeForEach && obj.forEach === nativeForEach) {
            obj.forEach(iterator, context);
        } else if (obj.length === +obj.length) {
            for (var i = 0, l = obj.length; i < l; i++) {
                if (iterator.call(context, obj[i], i, obj) === breaker) {
                    return;
                }
            }
        } else {
            for (var key in obj) {
                if (has(obj, key)) {
                    if (iterator.call(context, obj[key], key, obj) === breaker) {
                        return;
                    }
                }
            }
        }
    };

    // Extend a given object with all the properties in passed-in object(s).
    extend = function (obj) {
        each(slice.call(arguments, 1), function (source) {
            for (var prop in source) {
                obj[prop] = source[prop];
            }
        });
        return obj;
    };

    // Returns the index at which value can be found in the array, or -1 if
    // value is not present in the array.
    indexOf = function (array, item) {
        if (array == null) {
            return -1;
        }

        var i = 0, l = array.length;
        if (nativeIndexOf && array.indexOf === nativeIndexOf) {
            return array.indexOf(item);
        }

        for (; i < l; i++) {
            if (array[i] === item) {
                return i;

            }
        }

        return -1;
    };

    // Is a given value an array?
    // Delegates to ECMA5's native Array.isArray
    // switched to ===, not sure why underscore used ==
    isArray = nativeIsArray || function (obj) {
        return toString.call(obj) === '[object Array]';
    };

    // Is a given variable an object?
    isObject = function (obj) {
        return obj === Object(obj);
    };

    // switched to ===, not sure why underscore used ==
    isString = function (obj) {
        return toString.call(obj) === '[object String]';
    };

    // switched to ===, not sure why underscore used ==
    isNumber = function (obj) {
        return toString.call(obj) === '[object Number]';
    };

    isBoolean = function (obj) {
        return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
    };

    // switched to ===, not sure why underscore used ==
    if (typeof (/./) !== 'function') {
        isFunction = function (obj) {
            return typeof obj === 'function';
        };
    } else {
        isFunction = function (obj) {
            return toString.call(obj) === '[object Function]';
        };
    }

    // Is a given value an ejs object?
    // Yes if object and has "_type", "toJSON", and "toString" properties
    isEJSObject = function (obj) {
        return (isObject(obj) &&
          has(obj, '_type') &&
          has(obj, 'toJSON'));
    };

    isQuery = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'query');
    };

    isRescore = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'rescore');
    };

    isFilter = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'filter');
    };

    isFacet = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'facet');
    };

    isAggregation = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'aggregation');
    };

    isScriptField = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'script field');
    };

    isGeoPoint = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'geo point');
    };

    isIndexedShape = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'indexed shape');
    };

    isShape = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'shape');
    };

    isSort = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'sort');
    };

    isHighlight = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'highlight');
    };

    isSuggest = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'suggest');
    };

    isGenerator = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'generator');
    };

    isScoreFunction = function (obj) {
        return (isEJSObject(obj) && obj._type() === 'score function');
    };

    /**
      @mixin
      <p>The AggregationMixin provides support for common options used across
      various <code>Aggregation</code> implementations.  This object should not be
      used directly.</p>
  
      @name ejs.AggregationMixin
      */
    ejs.AggregationMixin = function (name) {

        var aggs = {};
        aggs[name] = {};

        return {

            /**
            Add a nesated aggregation.  This method can be called multiple times
            in order to set multiple nested aggregations what will be executed
            at the same time as the parent aggregation.
      
            @member ejs.AggregationMixin
            @param {Aggregation} agg Any valid <code>Aggregation</code> object.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            aggregation: function (agg) {
                if (agg == null) {
                    return aggs[name].aggs;
                }

                if (aggs[name].aggs == null) {
                    aggs[name].aggs = {};
                }

                if (!isAggregation(agg)) {
                    throw new TypeError('Argument must be an Aggregation');
                }

                extend(aggs[name].aggs, agg.toJSON());

                return this;
            },

            /**
            Add a nesated aggregation.  This method can be called multiple times
            in order to set multiple nested aggregations what will be executed
            at the same time as the parent aggregation.  Alias for the
            aggregation method.
      
            @member ejs.AggregationMixin
            @param {Aggregation} agg Any valid <code>Aggregation</code> object.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            agg: function (agg) {
                return this.aggregation(agg);
            },

            /**
                  The type of ejs object.  For internal use only.
      
                  @member ejs.AggregationMixin
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'aggregation';
            },

            /**
                  <p>Retrieves the internal <code>agg</code> object. This is typically used by
                     internal API functions so use with caution.</p>
      
                  @member ejs.AggregationMixin
                  @returns {String} returns this object's internal object.
                  */
            toJSON: function () {
                return aggs;
            }

        };
    };

    /**
      @mixin
      <p>The DirectSettingsMixin provides support for common options used across 
      various <code>Suggester</code> implementations.  This object should not be 
      used directly.</p>
  
      @name ejs.DirectSettingsMixin
    
      @param {String} settings The object to set the options on.
      */
    ejs.DirectSettingsMixin = function (settings) {

        return {

            /**
                  <p>Sets the accuracy.  How similar the suggested terms at least 
                  need to be compared to the original suggest text.</p>
      
                  @member ejs.DirectSettingsMixin
                  @param {Double} a A positive double value between 0 and 1.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            accuracy: function (a) {
                if (a == null) {
                    return settings.accuracy;
                }

                settings.accuracy = a;
                return this;
            },

            /**
                  <p>Sets the suggest mode.  Valid values are:</p>
      
                  <dl>
                    <dd><code>missing</code> - Only suggest terms in the suggest text that aren't in the index</dd>
                    <dd><code>popular</code> - Only suggest suggestions that occur in more docs then the original suggest text term</dd>
                    <dd><code>always</code> - Suggest any matching suggestions based on terms in the suggest text</dd> 
                  </dl>
      
                  @member ejs.DirectSettingsMixin
                  @param {String} m The mode of missing, popular, or always.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            suggestMode: function (m) {
                if (m == null) {
                    return settings.suggest_mode;
                }

                m = m.toLowerCase();
                if (m === 'missing' || m === 'popular' || m === 'always') {
                    settings.suggest_mode = m;
                }

                return this;
            },

            /**
                  <p>Sets the sort mode.  Valid values are:</p>
      
                  <dl>
                    <dd><code>score</code> - Sort by score first, then document frequency, and then the term itself</dd>
                    <dd><code>frequency</code> - Sort by document frequency first, then simlarity score and then the term itself</dd>
                  </dl>
      
                  @member ejs.DirectSettingsMixin
                  @param {String} s The score type of score or frequency.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            sort: function (s) {
                if (s == null) {
                    return settings.sort;
                }

                s = s.toLowerCase();
                if (s === 'score' || s === 'frequency') {
                    settings.sort = s;
                }

                return this;
            },

            /**
                  <p>Sets what string distance implementation to use for comparing 
                  how similar suggested terms are.  Valid values are:</p>
      
                  <dl>
                    <dd><code>internal</code> - based on damerau_levenshtein but but highly optimized for comparing string distance for terms inside the index</dd>
                    <dd><code>damerau_levenshtein</code> - String distance algorithm based on Damerau-Levenshtein algorithm</dd>
                    <dd><code>levenstein</code> - String distance algorithm based on Levenstein edit distance algorithm</dd>
                    <dd><code>jarowinkler</code> - String distance algorithm based on Jaro-Winkler algorithm</dd>
                    <dd><code>ngram</code> - String distance algorithm based on character n-grams</dd>
                  </dl>
      
                  @member ejs.DirectSettingsMixin
                  @param {String} s The string distance algorithm name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            stringDistance: function (s) {
                if (s == null) {
                    return settings.string_distance;
                }

                s = s.toLowerCase();
                if (s === 'internal' || s === 'damerau_levenshtein' ||
                    s === 'levenstein' || s === 'jarowinkler' || s === 'ngram') {
                    settings.string_distance = s;
                }

                return this;
            },

            /**
                  <p>Sets the maximum edit distance candidate suggestions can have 
                  in order to be considered as a suggestion.</p>
      
                  @member ejs.DirectSettingsMixin
                  @param {Integer} max An integer value greater than 0.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxEdits: function (max) {
                if (max == null) {
                    return settings.max_edits;
                }

                settings.max_edits = max;
                return this;
            },

            /**
                  <p>The factor that is used to multiply with the size in order 
                  to inspect more candidate suggestions.</p>
      
                  @member ejs.DirectSettingsMixin
                  @param {Integer} max A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxInspections: function (max) {
                if (max == null) {
                    return settings.max_inspections;
                }

                settings.max_inspections = max;
                return this;
            },

            /**
                  <p>Sets a maximum threshold in number of documents a suggest text 
                  token can exist in order to be corrected.</p>
      
                  @member ejs.DirectSettingsMixin
                  @param {Double} max A positive double value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxTermFreq: function (max) {
                if (max == null) {
                    return settings.max_term_freq;
                }

                settings.max_term_freq = max;
                return this;
            },

            /**
                  <p>Sets the number of minimal prefix characters that must match in 
                  order be a candidate suggestion.</p>
      
                  @member ejs.DirectSettingsMixin
                  @param {Integer} len A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            prefixLen: function (len) {
                if (len == null) {
                    return settings.prefix_len;
                }

                settings.prefix_len = len;
                return this;
            },

            /**
                  <p>Sets the minimum length a suggest text term must have in order 
                  to be corrected.</p>
      
                  @member ejs.DirectSettingsMixin
                  @param {Integer} len A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minWordLen: function (len) {
                if (len == null) {
                    return settings.min_word_len;
                }

                settings.min_word_len = len;
                return this;
            },

            /**
                  <p>Sets a minimal threshold of the number of documents a suggested 
                  term should appear in.</p>
      
                  @member ejs.DirectSettingsMixin
                  @param {Double} min A positive double value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minDocFreq: function (min) {
                if (min == null) {
                    return settings.min_doc_freq;
                }

                settings.min_doc_freq = min;
                return this;
            }

        };
    };

    /**
      @mixin
      <p>The FacetMixin provides support for common options used across 
      various <code>Facet</code> implementations.  This object should not be 
      used directly.</p>
  
      @name ejs.FacetMixin
      */
    ejs.FacetMixin = function (name) {

        var facet = {};
        facet[name] = {};

        return {

            /**
                  <p>Allows you to reduce the documents used for computing facet results.</p>
      
                  @member ejs.FacetMixin
                  @param {Object} oFilter A valid <code>Filter</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            facetFilter: function (oFilter) {
                if (oFilter == null) {
                    return facet[name].facet_filter;
                }

                if (!isFilter(oFilter)) {
                    throw new TypeError('Argument must be a Filter');
                }

                facet[name].facet_filter = oFilter.toJSON();
                return this;
            },

            /**
                  <p>Computes values across the entire index</p>
      
                  @member ejs.FacetMixin
                  @param {Boolean} trueFalse Calculate facet counts globally or not.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            global: function (trueFalse) {
                if (trueFalse == null) {
                    return facet[name].global;
                }

                facet[name].global = trueFalse;
                return this;
            },

            /**
                  <p>Sets the mode the facet will use.<p>
                  
                  <dl>
                      <dd><code>collector</code></dd>
                      <dd><code>post</code></dd>
                  <dl>
                  
                  @member ejs.FacetMixin
                  @param {String} m The mode: collector or post.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            mode: function (m) {
                if (m == null) {
                    return facet[name].mode;
                }

                m = m.toLowerCase();
                if (m === 'collector' || m === 'post') {
                    facet[name].mode = m;
                }

                return this;
            },

            /**
                  <p>Enables caching of the <code>facetFilter</code></p>
      
                  @member ejs.FacetMixin
                  @param {Boolean} trueFalse If the facetFilter should be cached or not
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            cacheFilter: function (trueFalse) {
                if (trueFalse == null) {
                    return facet[name].cache_filter;
                }

                facet[name].cache_filter = trueFalse;
                return this;
            },

            /**
                  <p>Computes values across the the specified scope</p>
      
                  @deprecated since elasticsearch 0.90
                  @member ejs.FacetMixin
                  @param {String} scope The scope name to calculate facet counts with.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scope: function (scope) {
                return this;
            },

            /**
                  <p>Sets the path to the nested document if faceting against a
                  nested field.</p>
      
                  @member ejs.FacetMixin
                  @param {String} path The nested path
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            nested: function (path) {
                if (path == null) {
                    return facet[name].nested;
                }

                facet[name].nested = path;
                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
                  
                  @member ejs.FacetMixin
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'facet';
            },

            /**
                  <p>Retrieves the internal <code>facet</code> object. This is typically used by
                     internal API functions so use with caution.</p>
      
                  @member ejs.FacetMixin
                  @returns {String} returns this object's internal <code>facet</code> property.
                  */
            toJSON: function () {
                return facet;
            }

        };
    };

    /**
      @mixin
      <p>The FilterMixin provides support for common options used across 
      various <code>Filter</code> implementations.  This object should not be 
      used directly.</p>
  
      @name ejs.FilterMixin
      */
    ejs.FilterMixin = function (type) {

        var filter = {};
        filter[type] = {};

        return {

            /**
                  Sets the filter name.
      
                  @member ejs.FilterMixin
                  @param {String} name A name for the filter.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            name: function (name) {
                if (name == null) {
                    return filter[type]._name;
                }

                filter[type]._name = name;
                return this;
            },

            /**
                  Enable or disable caching of the filter
      
                  @member ejs.FilterMixin
                  @param {Boolean} trueFalse True to cache the filter, false otherwise.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            cache: function (trueFalse) {
                if (trueFalse == null) {
                    return filter[type]._cache;
                }

                filter[type]._cache = trueFalse;
                return this;
            },

            /**
                  Sets the cache key.
      
                  @member ejs.FilterMixin
                  @param {String} key the cache key as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            cacheKey: function (key) {
                if (key == null) {
                    return filter[type]._cache_key;
                }

                filter[type]._cache_key = key;
                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
                
                  @member ejs.FilterMixin
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'filter';
            },

            /**
                   Returns the filter object.
      
                   @member ejs.FilterMixin
                   @returns {Object} filter object
                   */
            toJSON: function () {
                return filter;
            }

        };
    };

    /**
      @mixin
      <p>The MetricsAggregationMixin provides support for common options used across
      various metrics <code>Aggregation</code> implementations.  This object should
      not be used directly.</p>
  
      @name ejs.MetricsAggregationMixin
      @ejs aggregation
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      */
    ejs.MetricsAggregationMixin = function (name, type) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        // remove ability for sub-aggregations since metrics aggregations dont
        // support them.
        delete _common.aggregation;
        delete _common.agg;

        agg[name][type] = {};

        return extend(_common, {

            /**
            <p>Sets the field to operate on.</p>
      
            @member ejs.MetricsAggregationMixin
            @param {String} field a valid field name..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (field) {
                if (field == null) {
                    return agg[name][type].field;
                }

                agg[name][type].field = field;
                return this;
            },

            /**
            Allows you generate or modify the terms/values using a script.
      
            @member ejs.MetricsAggregationMixin
            @param {String} scriptCode A valid script string to execute.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            script: function (scriptCode) {
                if (scriptCode == null) {
                    return agg[name][type].script;
                }

                agg[name][type].script = scriptCode;
                return this;
            },

            /**
            The script language being used.
      
            @member ejs.MetricsAggregationMixin
            @param {String} language The language of the script.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            lang: function (language) {
                if (language == null) {
                    return agg[name][type].lang;
                }

                agg[name][type].lang = language;
                return this;
            },

            /**
            Set to true to assume script values are sorted.
      
            @member ejs.MetricsAggregationMixin
            @param {Boolean} trueFalse assume sorted values or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            scriptValuesSorted: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name][type].script_values_sorted;
                }

                agg[name][type].script_values_sorted = trueFalse;
                return this;
            },

            /**
            Sets parameters that will be applied to the script.  Overwrites
            any existing params.
      
            @member ejs.MetricsAggregationMixin
            @param {Object} p An object where the keys are the parameter name and
              values are the parameter value.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            params: function (p) {
                if (p == null) {
                    return agg[name][type].params;
                }

                agg[name][type].params = p;
                return this;
            }

        });
    };

    /**
      @mixin
      <p>The QueryMixin provides support for common options used across 
      various <code>Query</code> implementations.  This object should not be 
      used directly.</p>
  
      @name ejs.QueryMixin
      */
    ejs.QueryMixin = function (type) {

        var query = {};
        query[type] = {};

        return {

            /**
                  Sets the boost value for documents matching the <code>Query</code>.
      
                  @member ejs.QueryMixin
                  @param {Double} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query[type].boost;
                }

                query[type].boost = boost;
                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
                
                  @member ejs.QueryMixin
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'query';
            },

            /**
                  Retrieves the internal <code>query</code> object. This is typically used by
                  internal API functions so use with caution.
      
                  @member ejs.QueryMixin
                  @returns {String} returns this object's internal <code>query</code> property.
                  */
            toJSON: function () {
                return query;
            }

        };
    };

    /**
      @mixin
      <p>The ScoreFunctionMixin provides support for common options used across
      various <code>ScoreFunction</code> implementations.  This object should not be
      used directly.</p>
  
      @name ejs.ScoreFunctionMixin
      */
    ejs.ScoreFunctionMixin = function (name) {

        var func = {};
        func[name] = {};

        return {

            /**
            Adds a filter whose matching documents will have the score function applied.
      
            @member ejs.ScoreFunctionMixin
            @param {Filter} oFilter Any valid <code>Filter</code> object.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            filter: function (oFilter) {
                if (oFilter == null) {
                    return func.filter;
                }

                if (!isFilter(oFilter)) {
                    throw new TypeError('Argument must be a Filter');
                }

                func.filter = oFilter.toJSON();
                return this;
            },

            /**
            The type of ejs object.  For internal use only.
      
            @member ejs.ScoreFunctionMixin
            @returns {String} the type of object
            */
            _type: function () {
                return 'score function';
            },

            /**
            <p>Retrieves the internal <code>agg</code> object. This is typically used by
               internal API functions so use with caution.</p>
      
            @member ejs.ScoreFunctionMixin
            @returns {String} returns this object's internal object.
            */
            toJSON: function () {
                return func;
            }

        };
    };

    /**
      @mixin
      <p>The SuggestContextMixin provides support for suggest context settings 
      across various <code>Suggester</code> implementations.  This object should not be 
      used directly.</p>
  
      @name ejs.SuggestContextMixin
    
      @param {String} settings The object to set the options on.
      */
    ejs.SuggestContextMixin = function (settings) {

        return {

            /**
                  <p>Sets analyzer used to analyze the suggest text.</p>
      
                  @member ejs.SuggestContextMixin
                  @param {String} analyzer A valid analyzer name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            analyzer: function (analyzer) {
                if (analyzer == null) {
                    return settings.analyzer;
                }

                settings.analyzer = analyzer;
                return this;
            },

            /**
                  <p>Sets the field used to generate suggestions from.</p>
      
                  @member ejs.SuggestContextMixin
                  @param {String} field A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (field) {
                if (field == null) {
                    return settings.field;
                }

                settings.field = field;
                return this;
            },

            /**
                  <p>Sets the number of suggestions returned for each token.</p>
      
                  @member ejs.SuggestContextMixin
                  @param {Integer} s A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            size: function (s) {
                if (s == null) {
                    return settings.size;
                }

                settings.size = s;
                return this;
            },

            /**
                  <p>Sets the maximum number of suggestions to be retrieved from 
                  each individual shard.</p>
      
                  @member ejs.SuggestContextMixin
                  @param {Integer} s A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            shardSize: function (s) {
                if (s == null) {
                    return settings.shard_size;
                }

                settings.shard_size = s;
                return this;
            }

        };
    };

    /**
      @mixin
      <p>The SuggesterMixin provides support for the base setting of all suggesters. 
      This object should not be used directly.</p>
  
      @name ejs.SuggesterMixin
    
      @param {String} name The name of the suggester.
      */
    ejs.SuggesterMixin = function (name) {

        var suggest = {};
        suggest[name] = {};

        return {

            /**
                  <p>Sets the text to get suggestions for.  If not set, the global
                  suggestion text will be used.</p>
      
                  @member ejs.SuggesterMixin
                  @param {String} txt A string to get suggestions for.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            text: function (txt) {
                if (txt == null) {
                    return suggest[name].text;
                }

                suggest[name].text = txt;
                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
              
                  @member ejs.SuggesterMixin
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'suggest';
            },

            /**
                  <p>Retrieves the internal <code>suggest</code> object. This is typically used by
                     internal API functions so use with caution.</p>
      
                  @member ejs.SuggesterMixin
                  @returns {String} returns this object's internal <code>suggest</code> property.
                  */
            toJSON: function () {
                return suggest;
            }

        };
    };

    /**
      @class
      <p>The DateHistogram facet works with time-based values by building a histogram across time
         intervals of the <code>value</code> field. Each value is <em>rounded</em> into an interval (or
         placed in a bucket), and statistics are provided per interval/bucket (count and total).</p>
  
      <p>Facets are similar to SQL <code>GROUP BY</code> statements but perform much
         better. You can also construct several <em>"groups"</em> at once by simply
         specifying multiple facets.</p>
  
      <div class="alert-message block-message info">
          <p>
              <strong>Tip: </strong>
              For more information on faceted navigation, see
              <a href="http://en.wikipedia.org/wiki/Faceted_classification">this</a>
              Wikipedia article on Faceted Classification.
          </p>
      </div>
  
      @name ejs.DateHistogramFacet
      @ejs facet
      @borrows ejs.FacetMixin.facetFilter as facetFilter
      @borrows ejs.FacetMixin.global as global
      @borrows ejs.FacetMixin.mode as mode
      @borrows ejs.FacetMixin.cacheFilter as cacheFilter
      @borrows ejs.FacetMixin.scope as scope
      @borrows ejs.FacetMixin.nested as nested
      @borrows ejs.FacetMixin._type as _type
      @borrows ejs.FacetMixin.toJSON as toJSON
    
      @desc
      <p>A facet which returns the N most frequent terms within a collection
         or set of collections.</p>
  
      @param {String} name The name which be used to refer to this facet. For instance,
          the facet itself might utilize a field named <code>doc_authors</code>. Setting
          <code>name</code> to <code>Authors</code> would allow you to refer to the
          facet by that name, possibly simplifying some of the display logic.
  
      */
    ejs.DateHistogramFacet = function (name) {

        var
          _common = ejs.FacetMixin(name),
          facet = _common.toJSON();

        facet[name].date_histogram = {};

        return extend(_common, {

            /**
                  Sets the field to be used to construct the this facet.
      
                  @member ejs.DateHistogramFacet
                  @param {String} fieldName The field name whose data will be used to construct the facet.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].date_histogram.field;
                }

                facet[name].date_histogram.field = fieldName;
                return this;
            },

            /**
                  Allows you to specify a different key field to be used to group intervals.
      
                  @member ejs.DateHistogramFacet
                  @param {String} fieldName The name of the field to be used.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            keyField: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].date_histogram.key_field;
                }

                facet[name].date_histogram.key_field = fieldName;
                return this;
            },

            /**
                  Allows you to specify a different value field to aggrerate over.
      
                  @member ejs.DateHistogramFacet
                  @param {String} fieldName The name of the field to be used.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            valueField: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].date_histogram.value_field;
                }

                facet[name].date_histogram.value_field = fieldName;
                return this;
            },

            /**
                  Sets the bucket interval used to calculate the distribution.
      
                  @member ejs.DateHistogramFacet
                  @param {String} timeInterval The bucket interval. Valid values are <code>year, month, week, day, hour,</code> and <code>minute</code>.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            interval: function (timeInterval) {
                if (timeInterval == null) {
                    return facet[name].date_histogram.interval;
                }

                facet[name].date_histogram.interval = timeInterval;
                return this;
            },

            /**
                  <p>By default, time values are stored in UTC format.<p> 
      
                  <p>This method allows users to set a time zone value that is then used 
                  to compute intervals before rounding on the interval value. Equalivent to 
                  <coe>preZone</code>.  Use <code>preZone</code> if possible. The 
                  value is an offset from UTC.<p>
                  
                  <p>For example, to use EST you would set the value to <code>-5</code>.</p>
      
                  @member ejs.DateHistogramFacet
                  @param {Integer} tz An offset value from UTC.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            timeZone: function (tz) {
                if (tz == null) {
                    return facet[name].date_histogram.time_zone;
                }

                facet[name].date_histogram.time_zone = tz;
                return this;
            },

            /**
                  <p>By default, time values are stored in UTC format.<p> 
      
                  <p>This method allows users to set a time zone value that is then used to 
                  compute intervals before rounding on the interval value.  The value is an 
                  offset from UTC.<p>
                  
                  <p>For example, to use EST you would set the value to <code>-5</code>.</p>
      
                  @member ejs.DateHistogramFacet
                  @param {Integer} tz An offset value from UTC.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            preZone: function (tz) {
                if (tz == null) {
                    return facet[name].date_histogram.pre_zone;
                }

                facet[name].date_histogram.pre_zone = tz;
                return this;
            },

            /**
                  <p>Enables large date interval conversions (day and up).</p>  
      
                  <p>Set to true to enable and then set the <code>interval</code> to an 
                  interval greater than a day.</p>
                  
                  @member ejs.DateHistogramFacet
                  @param {Boolean} trueFalse A valid boolean value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            preZoneAdjustLargeInterval: function (trueFalse) {
                if (trueFalse == null) {
                    return facet[name].date_histogram.pre_zone_adjust_large_interval;
                }

                facet[name].date_histogram.pre_zone_adjust_large_interval = trueFalse;
                return this;
            },

            /**
                  <p>By default, time values are stored in UTC format.<p> 
      
                  <p>This method allows users to set a time zone value that is then used to compute 
                  intervals after rounding on the interval value.  The value is an offset from UTC.  
                  The tz offset value is simply added to the resulting bucket's date value.<p>
                  
                  <p>For example, to use EST you would set the value to <code>-5</code>.</p>
      
                  @member ejs.DateHistogramFacet
                  @param {Integer} tz An offset value from UTC.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            postZone: function (tz) {
                if (tz == null) {
                    return facet[name].date_histogram.post_zone;
                }

                facet[name].date_histogram.post_zone = tz;
                return this;
            },

            /**
                  Set's a specific pre-rounding offset.  Format is 1d, 1h, etc.
      
                  @member ejs.DateHistogramFacet
                  @param {String} offset The offset as a string (1d, 1h, etc)
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            preOffset: function (offset) {
                if (offset == null) {
                    return facet[name].date_histogram.pre_offset;
                }

                facet[name].date_histogram.pre_offset = offset;
                return this;
            },

            /**
                  Set's a specific post-rounding offset.  Format is 1d, 1h, etc.
      
                  @member ejs.DateHistogramFacet
                  @param {String} offset The offset as a string (1d, 1h, etc)
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            postOffset: function (offset) {
                if (offset == null) {
                    return facet[name].date_histogram.post_offset;
                }

                facet[name].date_histogram.post_offset = offset;
                return this;
            },

            /**
                  <p>The date histogram works on numeric values (since time is stored 
                  in milliseconds since the epoch in UTC).<p> 
      
                  <p>But, sometimes, systems will store a different resolution (like seconds since UTC) 
                  in a numeric field. The factor parameter can be used to change the value in the field 
                  to milliseconds to actual do the relevant rounding, and then be applied again to get to 
                  the original unit.</p>
      
                  <p>For example, when storing in a numeric field seconds resolution, 
                  the factor can be set to 1000.<p>
      
                  @member ejs.DateHistogramFacet
                  @param {Integer} f The conversion factor.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            factor: function (f) {
                if (f == null) {
                    return facet[name].date_histogram.factor;
                }

                facet[name].date_histogram.factor = f;
                return this;
            },

            /**
                  Allows you modify the <code>value</code> field using a script. The modified value
                  is then used to compute the statistical data.
      
                  @member ejs.DateHistogramFacet
                  @param {String} scriptCode A valid script string to execute.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            valueScript: function (scriptCode) {
                if (scriptCode == null) {
                    return facet[name].date_histogram.value_script;
                }

                facet[name].date_histogram.value_script = scriptCode;
                return this;
            },

            /**
                  <p>Sets the type of ordering that will be performed on the date
                  buckets.  Valid values are:<p>
                  
                  <dl>
                      <dd><code>time</code> - the default, sort by the buckets start time in milliseconds.</dd>
                      <dd><code>count</code> - sort by the number of items in the bucket</dd>
                      <dd><code>total</code> - sort by the sum/total of the items in the bucket</dd>
                  <dl>
                  
                  @member ejs.DateHistogramFacet
                  @param {String} o The ordering method: time, count, or total.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            order: function (o) {
                if (o == null) {
                    return facet[name].date_histogram.order;
                }

                o = o.toLowerCase();
                if (o === 'time' || o === 'count' || o === 'total') {
                    facet[name].date_histogram.order = o;
                }

                return this;
            },

            /**
                  The script language being used. Currently supported values are
                  <code>javascript</code>, <code>groovy</code>, and <code>mvel</code>.
      
                  @member ejs.DateHistogramFacet
                  @param {String} language The language of the script.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lang: function (language) {
                if (language == null) {
                    return facet[name].date_histogram.lang;
                }

                facet[name].date_histogram.lang = language;
                return this;
            },

            /**
                  Sets parameters that will be applied to the script.  Overwrites 
                  any existing params.
      
                  @member ejs.DateHistogramFacet
                  @param {Object} p An object where the keys are the parameter name and 
                    values are the parameter value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            params: function (p) {
                if (p == null) {
                    return facet[name].date_histogram.params;
                }

                facet[name].date_histogram.params = p;
                return this;
            }

        });
    };

    /**
      @class
      <p>The FilterFacet allows you to specify any valid <code>Filter</code> and
      have the number of matching hits returned as the value.</p>
  
      <p>Facets are similar to SQL <code>GROUP BY</code> statements but perform much
         better. You can also construct several <em>"groups"</em> at once by simply
         specifying multiple facets.</p>
  
      <div class="alert-message block-message info">
          <p>
              <strong>Tip: </strong>
              For more information on faceted navigation, see
              <a href="http://en.wikipedia.org/wiki/Faceted_classification">this</a>
              Wikipedia article on Faceted Classification.
          </p>
      </div>
  
      @name ejs.FilterFacet
      @ejs facet
      @borrows ejs.FacetMixin.facetFilter as facetFilter
      @borrows ejs.FacetMixin.global as global
      @borrows ejs.FacetMixin.mode as mode
      @borrows ejs.FacetMixin.cacheFilter as cacheFilter
      @borrows ejs.FacetMixin.scope as scope
      @borrows ejs.FacetMixin.nested as nested
      @borrows ejs.FacetMixin._type as _type
      @borrows ejs.FacetMixin.toJSON as toJSON
  
      @desc
      <p>A facet that return a count of the hits matching the given filter.</p>
  
      @param {String} name The name which be used to refer to this facet. For instance,
          the facet itself might utilize a field named <code>doc_authors</code>. Setting
          <code>name</code> to <code>Authors</code> would allow you to refer to the
          facet by that name, possibly simplifying some of the display logic.
  
      */
    ejs.FilterFacet = function (name) {

        var
          _common = ejs.FacetMixin(name),
          facet = _common.toJSON();

        return extend(_common, {

            /**
                  <p>Sets the filter to be used for this facet.</p>
      
                  @member ejs.FilterFacet
                  @param {Object} oFilter A valid <code>Query</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            filter: function (oFilter) {
                if (oFilter == null) {
                    return facet[name].filter;
                }

                if (!isFilter(oFilter)) {
                    throw new TypeError('Argument must be a Filter');
                }

                facet[name].filter = oFilter.toJSON();
                return this;
            }

        });
    };

    /**
      @class
      <p>The geoDistanceFacet facet provides information over a range of distances from a
      provided point. This includes the number of hits that fall within each range,
      along with aggregate information (like total).</p>
  
      <p>Facets are similar to SQL <code>GROUP BY</code> statements but perform much
         better. You can also construct several <em>"groups"</em> at once by simply
         specifying multiple facets.</p>
  
      <div class="alert-message block-message info">
          <p>
              <strong>Tip: </strong>
              For more information on faceted navigation, see
              <a href="http://en.wikipedia.org/wiki/Faceted_classification">this</a>
              Wikipedia article on Faceted Classification.
          </p>
      </div>
  
      @name ejs.GeoDistanceFacet
      @ejs facet
      @borrows ejs.FacetMixin.facetFilter as facetFilter
      @borrows ejs.FacetMixin.global as global
      @borrows ejs.FacetMixin.mode as mode
      @borrows ejs.FacetMixin.cacheFilter as cacheFilter
      @borrows ejs.FacetMixin.scope as scope
      @borrows ejs.FacetMixin.nested as nested
      @borrows ejs.FacetMixin._type as _type
      @borrows ejs.FacetMixin.toJSON as toJSON
  
      @desc
      <p>A facet which provides information over a range of distances from a provided point.</p>
  
      @param {String} name The name which be used to refer to this facet. For instance,
          the facet itself might utilize a field named <code>doc_authors</code>. Setting
          <code>name</code> to <code>Authors</code> would allow you to refer to the
          facet by that name, possibly simplifying some of the display logic.
  
      */
    ejs.GeoDistanceFacet = function (name) {

        var
          _common = ejs.FacetMixin(name),
          facet = _common.toJSON(),
          point = ejs.GeoPoint([0, 0]),
          field = 'location';

        facet[name].geo_distance = {
            location: point.toJSON(),
            ranges: []
        };

        return extend(_common, {

            /**
                  Sets the document field containing the geo-coordinate to be used 
                  to calculate the distance.  Defaults to "location".
      
                  @member ejs.GeoDistanceFacet
                  @param {String} fieldName The field name whose data will be used to construct the facet.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (fieldName) {
                var oldValue = facet[name].geo_distance[field];

                if (fieldName == null) {
                    return field;
                }

                delete facet[name].geo_distance[field];
                field = fieldName;
                facet[name].geo_distance[fieldName] = oldValue;

                return this;
            },

            /**
                  Sets the point of origin from where distances will be measured.
      
                  @member ejs.GeoDistanceFacet
                  @param {GeoPoint} p A valid GeoPoint object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            point: function (p) {
                if (p == null) {
                    return point;
                }

                if (!isGeoPoint(p)) {
                    throw new TypeError('Argument must be a GeoPoint');
                }

                point = p;
                facet[name].geo_distance[field] = p.toJSON();
                return this;
            },

            /**
                  Adds a new bounded range.
      
                  @member ejs.GeoDistanceFacet
                  @param {Number} from The lower bound of the range
                  @param {Number} to The upper bound of the range
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            addRange: function (from, to) {
                if (arguments.length === 0) {
                    return facet[name].geo_distance.ranges;
                }

                facet[name].geo_distance.ranges.push({
                    from: from,
                    to: to
                });

                return this;
            },

            /**
                  Adds a new unbounded lower limit.
      
                  @member ejs.GeoDistanceFacet
                  @param {Number} from The lower limit of the unbounded range
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            addUnboundedFrom: function (from) {
                if (from == null) {
                    return facet[name].geo_distance.ranges;
                }

                facet[name].geo_distance.ranges.push({
                    from: from
                });

                return this;
            },

            /**
                  Adds a new unbounded upper limit.
      
                  @member ejs.GeoDistanceFacet
                  @param {Number} to The upper limit of the unbounded range
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            addUnboundedTo: function (to) {
                if (to == null) {
                    return facet[name].geo_distance.ranges;
                }

                facet[name].geo_distance.ranges.push({
                    to: to
                });

                return this;
            },

            /**
                   Sets the distance unit.  Valid values are "mi" for miles or "km"
                   for kilometers. Defaults to "km".
      
                   @member ejs.GeoDistanceFacet
                   @param {Number} unit the unit of distance measure.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            unit: function (unit) {
                if (unit == null) {
                    return facet[name].geo_distance.unit;
                }

                unit = unit.toLowerCase();
                if (unit === 'mi' || unit === 'km') {
                    facet[name].geo_distance.unit = unit;
                }

                return this;
            },

            /**
                  How to compute the distance. Can either be arc (better precision) 
                  or plane (faster). Defaults to arc.
      
                  @member ejs.GeoDistanceFacet
                  @param {String} type The execution type as a string.  
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            distanceType: function (type) {
                if (type == null) {
                    return facet[name].geo_distance.distance_type;
                }

                type = type.toLowerCase();
                if (type === 'arc' || type === 'plane') {
                    facet[name].geo_distance.distance_type = type;
                }

                return this;
            },

            /**
                  If the lat/long points should be normalized to lie within their
                  respective normalized ranges.
                  
                  Normalized ranges are:
                  lon = -180 (exclusive) to 180 (inclusive) range
                  lat = -90 to 90 (both inclusive) range
      
                  @member ejs.GeoDistanceFacet
                  @param {String} trueFalse True if the coordinates should be normalized. False otherwise.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            normalize: function (trueFalse) {
                if (trueFalse == null) {
                    return facet[name].geo_distance.normalize;
                }

                facet[name].geo_distance.normalize = trueFalse;
                return this;
            },

            /**
                  Allows you to specify a different value field to aggrerate over.
      
                  @member ejs.GeoDistanceFacet
                  @param {String} fieldName The name of the field to be used.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            valueField: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].geo_distance.value_field;
                }

                facet[name].geo_distance.value_field = fieldName;
                return this;
            },

            /**
                  Allows you modify the <code>value</code> field using a script. The modified value
                  is then used to compute the statistical data.
      
                  @member ejs.GeoDistanceFacet
                  @param {String} scriptCode A valid script string to execute.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            valueScript: function (scriptCode) {
                if (scriptCode == null) {
                    return facet[name].geo_distance.value_script;
                }

                facet[name].geo_distance.value_script = scriptCode;
                return this;
            },

            /**
                  The script language being used. Currently supported values are
                  <code>javascript</code>, <code>groovy</code>, and <code>mvel</code>.
      
                  @member ejs.GeoDistanceFacet
                  @param {String} language The language of the script.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lang: function (language) {
                if (language == null) {
                    return facet[name].geo_distance.lang;
                }

                facet[name].geo_distance.lang = language;
                return this;
            },

            /**
                  Sets parameters that will be applied to the script.  Overwrites 
                  any existing params.
      
                  @member ejs.GeoDistanceFacet
                  @param {Object} p An object where the keys are the parameter name and 
                    values are the parameter value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            params: function (p) {
                if (p == null) {
                    return facet[name].geo_distance.params;
                }

                facet[name].geo_distance.params = p;
                return this;
            }

        });
    };

    /**
      @class
      <p>The histogram facet works with numeric data by building a histogram across intervals
         of the field values. Each value is <em>rounded</em> into an interval (or placed in a
         bucket), and statistics are provided per interval/bucket (count and total).</p>
  
      <p>Facets are similar to SQL <code>GROUP BY</code> statements but perform much
         better. You can also construct several <em>"groups"</em> at once by simply
         specifying multiple facets.</p>
  
      <div class="alert-message block-message info">
          <p>
              <strong>Tip: </strong>
              For more information on faceted navigation, see
              <a href="http://en.wikipedia.org/wiki/Faceted_classification">this</a>
              Wikipedia article on Faceted Classification.
          </p>
      </div>
  
      @name ejs.HistogramFacet
      @ejs facet
      @borrows ejs.FacetMixin.facetFilter as facetFilter
      @borrows ejs.FacetMixin.global as global
      @borrows ejs.FacetMixin.mode as mode
      @borrows ejs.FacetMixin.cacheFilter as cacheFilter
      @borrows ejs.FacetMixin.scope as scope
      @borrows ejs.FacetMixin.nested as nested
      @borrows ejs.FacetMixin._type as _type
      @borrows ejs.FacetMixin.toJSON as toJSON
  
      @desc
      <p>A facet which returns the N most frequent terms within a collection
         or set of collections.</p>
  
      @param {String} name The name which be used to refer to this facet. For instance,
          the facet itself might utilize a field named <code>doc_authors</code>. Setting
          <code>name</code> to <code>Authors</code> would allow you to refer to the
          facet by that name, possibly simplifying some of the display logic.
  
      */
    ejs.HistogramFacet = function (name) {

        var
          _common = ejs.FacetMixin(name),
          facet = _common.toJSON();

        facet[name].histogram = {};

        return extend(_common, {

            /**
                  Sets the field to be used to construct the this facet.
      
                  @member ejs.HistogramFacet
                  @param {String} fieldName The field name whose data will be used to construct the facet.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].histogram.field;
                }

                facet[name].histogram.field = fieldName;
                return this;
            },

            /**
                  Sets the bucket interval used to calculate the distribution.
      
                  @member ejs.HistogramFacet
                  @param {Number} numericInterval The bucket interval in which to group values.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            interval: function (numericInterval) {
                if (numericInterval == null) {
                    return facet[name].histogram.interval;
                }

                facet[name].histogram.interval = numericInterval;
                return this;
            },

            /**
                  Sets the bucket interval used to calculate the distribution based
                  on a time value such as "1d", "1w", etc.
      
                  @member ejs.HistogramFacet
                  @param {Number} timeInterval The bucket interval in which to group values.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            timeInterval: function (timeInterval) {
                if (timeInterval == null) {
                    return facet[name].histogram.time_interval;
                }

                facet[name].histogram.time_interval = timeInterval;
                return this;
            },

            /**
                  Sets the "from", "start", or lower bounds bucket.  For example if 
                  you have a value of 1023, an interval of 100, and a from value of 
                  1500, it will be placed into the 1500 bucket vs. the normal bucket 
                  of 1000.
      
                  @member ejs.HistogramFacet
                  @param {Number} from the lower bounds bucket value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            from: function (from) {
                if (from == null) {
                    return facet[name].histogram.from;
                }

                facet[name].histogram.from = from;
                return this;
            },

            /**
                  Sets the "to", "end", or upper bounds bucket.  For example if 
                  you have a value of 1023, an interval of 100, and a to value of 
                  900, it will be placed into the 900 bucket vs. the normal bucket 
                  of 1000.
      
                  @member ejs.HistogramFacet
                  @param {Number} to the upper bounds bucket value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            to: function (to) {
                if (to == null) {
                    return facet[name].histogram.to;
                }

                facet[name].histogram.to = to;
                return this;
            },

            /**
                  Allows you to specify a different value field to aggrerate over.
      
                  @member ejs.HistogramFacet
                  @param {String} fieldName The name of the field to be used.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            valueField: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].histogram.value_field;
                }

                facet[name].histogram.value_field = fieldName;
                return this;
            },

            /**
                  Allows you to specify a different key field to be used to group intervals.
      
                  @member ejs.HistogramFacet
                  @param {String} fieldName The name of the field to be used.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            keyField: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].histogram.key_field;
                }

                facet[name].histogram.key_field = fieldName;
                return this;
            },

            /**
                  Allows you modify the <code>value</code> field using a script. The modified value
                  is then used to compute the statistical data.
      
                  @member ejs.HistogramFacet
                  @param {String} scriptCode A valid script string to execute.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            valueScript: function (scriptCode) {
                if (scriptCode == null) {
                    return facet[name].histogram.value_script;
                }

                facet[name].histogram.value_script = scriptCode;
                return this;
            },

            /**
                  Allows you modify the <code>key</code> field using a script. The modified value
                  is then used to generate the interval.
      
                  @member ejs.HistogramFacet
                  @param {String} scriptCode A valid script string to execute.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            keyScript: function (scriptCode) {
                if (scriptCode == null) {
                    return facet[name].histogram.key_script;
                }

                facet[name].histogram.key_script = scriptCode;
                return this;
            },

            /**
                  The script language being used. Currently supported values are
                  <code>javascript</code>, <code>groovy</code>, and <code>mvel</code>.
      
                  @member ejs.HistogramFacet
                  @param {String} language The language of the script.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lang: function (language) {
                if (language == null) {
                    return facet[name].histogram.lang;
                }

                facet[name].histogram.lang = language;
                return this;
            },

            /**
                  Sets parameters that will be applied to the script.  Overwrites 
                  any existing params.
      
                  @member ejs.HistogramFacet
                  @param {Object} p An object where the keys are the parameter name and 
                    values are the parameter value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            params: function (p) {
                if (p == null) {
                    return facet[name].histogram.params;
                }

                facet[name].histogram.params = p;
                return this;
            },

            /**
                  Sets the type of ordering that will be performed on the date
                  buckets.  Valid values are:
                  
                  key - the default, sort by the bucket's key value
                  count - sort by the number of items in the bucket
                  total - sort by the sum/total of the items in the bucket
                  
                  @member ejs.HistogramFacet
                  @param {String} o The ordering method: key, count, or total.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            order: function (o) {
                if (o == null) {
                    return facet[name].histogram.order;
                }

                o = o.toLowerCase();
                if (o === 'key' || o === 'count' || o === 'total') {
                    facet[name].histogram.order = o;
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>The QueryFacet facet allows you to specify any valid <code>Query</code> and
      have the number of matching hits returned as the value.</p>
  
      <p>Facets are similar to SQL <code>GROUP BY</code> statements but perform much
         better. You can also construct several <em>"groups"</em> at once by simply
         specifying multiple facets.</p>
  
      <div class="alert-message block-message info">
          <p>
              <strong>Tip: </strong>
              For more information on faceted navigation, see
              <a href="http://en.wikipedia.org/wiki/Faceted_classification">this</a>
              Wikipedia article on Faceted Classification.
          </p>
      </div>
  
      @name ejs.QueryFacet
      @ejs facet
      @borrows ejs.FacetMixin.facetFilter as facetFilter
      @borrows ejs.FacetMixin.global as global
      @borrows ejs.FacetMixin.mode as mode
      @borrows ejs.FacetMixin.cacheFilter as cacheFilter
      @borrows ejs.FacetMixin.scope as scope
      @borrows ejs.FacetMixin.nested as nested
      @borrows ejs.FacetMixin._type as _type
      @borrows ejs.FacetMixin.toJSON as toJSON
  
      @desc
      <p>A facet that return a count of the hits matching the given query.</p>
  
      @param {String} name The name which be used to refer to this facet. For instance,
          the facet itself might utilize a field named <code>doc_authors</code>. Setting
          <code>name</code> to <code>Authors</code> would allow you to refer to the
          facet by that name, possibly simplifying some of the display logic.
  
      */
    ejs.QueryFacet = function (name) {

        var
          _common = ejs.FacetMixin(name),
          facet = _common.toJSON();

        return extend(_common, {

            /**
                  <p>Sets the query to be used for this facet.</p>
      
                  @member ejs.QueryFacet
                  @param {Object} oQuery A valid <code>Query</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (oQuery) {
                if (oQuery == null) {
                    return facet[name].query;
                }

                if (!isQuery(oQuery)) {
                    throw new TypeError('Argument must be a Query');
                }

                facet[name].query = oQuery.toJSON();
                return this;
            }

        });
    };

    /**
      @class
      <p>A RangeFacet allows you to specify a set of ranges and get both the number of docs (count) that
         fall within each range, and aggregated data based on the field, or another specified field.</p>
  
      <p>Facets are similar to SQL <code>GROUP BY</code> statements but perform much
         better. You can also construct several <em>"groups"</em> at once by simply
         specifying multiple facets.</p>
  
      <div class="alert-message block-message info">
          <p>
              <strong>Tip: </strong>
              For more information on faceted navigation, see
              <a href="http://en.wikipedia.org/wiki/Faceted_classification">this</a>
              Wikipedia article on Faceted Classification.
          </p>
      </div>
  
      @name ejs.RangeFacet
      @ejs facet
      @borrows ejs.FacetMixin.facetFilter as facetFilter
      @borrows ejs.FacetMixin.global as global
      @borrows ejs.FacetMixin.mode as mode
      @borrows ejs.FacetMixin.cacheFilter as cacheFilter
      @borrows ejs.FacetMixin.scope as scope
      @borrows ejs.FacetMixin.nested as nested
      @borrows ejs.FacetMixin._type as _type
      @borrows ejs.FacetMixin.toJSON as toJSON
  
      @desc
      <p>A facet which provides information over a range of numeric intervals.</p>
  
      @param {String} name The name which be used to refer to this facet. For instance,
          the facet itself might utilize a field named <code>doc_authors</code>. Setting
          <code>name</code> to <code>Authors</code> would allow you to refer to the
          facet by that name, possibly simplifying some of the display logic.
  
      */
    ejs.RangeFacet = function (name) {

        var
          _common = ejs.FacetMixin(name),
          facet = _common.toJSON();

        facet[name].range = {
            ranges: []
        };

        return extend(_common, {

            /**
                  Sets the document field to be used for the facet.
      
                  @member ejs.RangeFacet
                  @param {String} fieldName The field name whose data will be used to compute the interval.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].range.field;
                }

                facet[name].range.field = fieldName;
                return this;
            },

            /**
                  Allows you to specify an alternate key field to be used to compute the interval.
      
                  @member ejs.RangeFacet
                  @param {String} fieldName The field name whose data will be used to compute the interval.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            keyField: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].range.key_field;
                }

                facet[name].range.key_field = fieldName;
                return this;
            },

            /**
                  Allows you to specify an alternate value field to be used to compute statistical information.
      
                  @member ejs.RangeFacet
                  @param {String} fieldName The field name whose data will be used to compute statistics.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            valueField: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].range.value_field;
                }

                facet[name].range.value_field = fieldName;
                return this;
            },

            /**
                  Allows you modify the <code>value</code> field using a script. The modified value
                  is then used to compute the statistical data.
      
                  @member ejs.RangeFacet
                  @param {String} scriptCode A valid script string to execute.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            valueScript: function (scriptCode) {
                if (scriptCode == null) {
                    return facet[name].range.value_script;
                }

                facet[name].range.value_script = scriptCode;
                return this;
            },

            /**
                  Allows you modify the <code>key</code> field using a script. The modified value
                  is then used to generate the interval.
      
                  @member ejs.RangeFacet
                  @param {String} scriptCode A valid script string to execute.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            keyScript: function (scriptCode) {
                if (scriptCode == null) {
                    return facet[name].range.key_script;
                }

                facet[name].range.key_script = scriptCode;
                return this;
            },

            /**
                  The script language being used. Currently supported values are
                  <code>javascript</code>, <code>groovy</code>, and <code>mvel</code>.
      
                  @member ejs.RangeFacet
                  @param {String} language The language of the script.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lang: function (language) {
                if (language == null) {
                    return facet[name].range.lang;
                }

                facet[name].range.lang = language;
                return this;
            },

            /**
                  Sets parameters that will be applied to the script.  Overwrites 
                  any existing params.
      
                  @member ejs.RangeFacet
                  @param {Object} p An object where the keys are the parameter name and 
                    values are the parameter value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            params: function (p) {
                if (p == null) {
                    return facet[name].range.params;
                }

                facet[name].range.params = p;
                return this;
            },

            /**
                  Adds a new bounded range.
      
                  @member ejs.RangeFacet
                  @param {Number} from The lower bound of the range (can also be <code>Date</code>).
                  @param {Number} to The upper bound of the range (can also be <code>Date</code>).
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            addRange: function (from, to) {
                if (arguments.length === 0) {
                    return facet[name].range.ranges;
                }

                facet[name].range.ranges.push({
                    from: from,
                    to: to
                });

                return this;
            },

            /**
                  Adds a new unbounded lower limit.
      
                  @member ejs.RangeFacet
                  @param {Number} from The lower limit of the unbounded range (can also be <code>Date</code>).
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            addUnboundedFrom: function (from) {
                if (from == null) {
                    return facet[name].range.ranges;
                }

                facet[name].range.ranges.push({
                    from: from
                });

                return this;
            },

            /**
                  Adds a new unbounded upper limit.
      
                  @member ejs.RangeFacet
                  @param {Number} to The upper limit of the unbounded range (can also be <code>Date</code>).
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            addUnboundedTo: function (to) {
                if (to == null) {
                    return facet[name].range.ranges;
                }

                facet[name].range.ranges.push({
                    to: to
                });

                return this;
            }

        });
    };

    /**
      @class
      <p>A statistical facet allows you to compute statistical data over a numeric fields. Statistical data includes
      the count, total, sum of squares, mean (average), minimum, maximum, variance, and standard deviation.</p>
  
      <p>Facets are similar to SQL <code>GROUP BY</code> statements but perform much
         better. You can also construct several <em>"groups"</em> at once by simply
         specifying multiple facets.</p>
  
      <div class="alert-message block-message info">
          <p>
              <strong>Tip: </strong>
              For more information on faceted navigation, see
              <a href="http://en.wikipedia.org/wiki/Faceted_classification">this</a>
              Wikipedia article on Faceted Classification.
          </p>
      </div>
  
      @name ejs.StatisticalFacet
      @ejs facet
      @borrows ejs.FacetMixin.facetFilter as facetFilter
      @borrows ejs.FacetMixin.global as global
      @borrows ejs.FacetMixin.mode as mode
      @borrows ejs.FacetMixin.cacheFilter as cacheFilter
      @borrows ejs.FacetMixin.scope as scope
      @borrows ejs.FacetMixin.nested as nested
      @borrows ejs.FacetMixin._type as _type
      @borrows ejs.FacetMixin.toJSON as toJSON
  
      @desc
      <p>A facet which returns statistical information about a numeric field</p>
  
      @param {String} name The name which be used to refer to this facet. For instance,
          the facet itself might utilize a field named <code>doc_authors</code>. Setting
          <code>name</code> to <code>Authors</code> would allow you to refer to the
          facet by that name, possibly simplifying some of the display logic.
  
      */
    ejs.StatisticalFacet = function (name) {

        var
          _common = ejs.FacetMixin(name),
          facet = _common.toJSON();

        facet[name].statistical = {};

        return extend(_common, {

            /**
                  Sets the field to be used to construct the this facet.
      
                  @member ejs.StatisticalFacet
                  @param {String} fieldName The field name whose data will be used to construct the facet.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].statistical.field;
                }

                facet[name].statistical.field = fieldName;
                return this;
            },

            /**
                  Aggregate statistical info across a set of fields.
      
                  @member ejs.StatisticalFacet
                  @param {Array} aFieldName An array of field names.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fields: function (fields) {
                if (fields == null) {
                    return facet[name].statistical.fields;
                }

                if (!isArray(fields)) {
                    throw new TypeError('Argument must be an array');
                }

                facet[name].statistical.fields = fields;
                return this;
            },

            /**
                  Define a script to evaluate of which the result will be used to generate
                  the statistical information.
      
                  @member ejs.StatisticalFacet
                  @param {String} code The script code to execute.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            script: function (code) {
                if (code == null) {
                    return facet[name].statistical.script;
                }

                facet[name].statistical.script = code;
                return this;
            },

            /**
                  The script language being used. Currently supported values are
                  <code>javascript</code>, <code>groovy</code>, and <code>mvel</code>.
      
                  @member ejs.StatisticalFacet
                  @param {String} language The language of the script.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lang: function (language) {
                if (language == null) {
                    return facet[name].statistical.lang;
                }

                facet[name].statistical.lang = language;
                return this;
            },

            /**
                  Allows you to set script parameters to be used during the execution of the script.
      
                  @member ejs.StatisticalFacet
                  @param {Object} oParams An object containing key/value pairs representing param name/value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            params: function (oParams) {
                if (oParams == null) {
                    return facet[name].statistical.params;
                }

                facet[name].statistical.params = oParams;
                return this;
            }

        });
    };

    /**
      @class
      <p>A termsStatsFacet allows you to compute statistics over an aggregate key (term). Essentially this
      facet provides the functionality of what is often refered to as a <em>pivot table</em>.</p>
  
      <p>Facets are similar to SQL <code>GROUP BY</code> statements but perform much
         better. You can also construct several <em>"groups"</em> at once by simply
         specifying multiple facets.</p>
  
      <div class="alert-message block-message info">
          <p>
              <strong>Tip: </strong>
              For more information on faceted navigation, see
              <a href="http://en.wikipedia.org/wiki/Faceted_classification">this</a>
              Wikipedia article on Faceted Classification.
          </p>
      </div>
  
      @name ejs.TermStatsFacet
      @ejs facet
      @borrows ejs.FacetMixin.facetFilter as facetFilter
      @borrows ejs.FacetMixin.global as global
      @borrows ejs.FacetMixin.mode as mode
      @borrows ejs.FacetMixin.cacheFilter as cacheFilter
      @borrows ejs.FacetMixin.scope as scope
      @borrows ejs.FacetMixin.nested as nested
      @borrows ejs.FacetMixin._type as _type
      @borrows ejs.FacetMixin.toJSON as toJSON
  
      @desc
      <p>A facet which computes statistical data based on an aggregate key.</p>
  
      @param {String} name The name which be used to refer to this facet. For instance,
          the facet itself might utilize a field named <code>doc_authors</code>. Setting
          <code>name</code> to <code>Authors</code> would allow you to refer to the
          facet by that name, possibly simplifying some of the display logic.
  
      */
    ejs.TermStatsFacet = function (name) {

        var
          _common = ejs.FacetMixin(name),
          facet = _common.toJSON();

        facet[name].terms_stats = {};

        return extend(_common, {

            /**
                  Sets the field for which statistical information will be generated.
      
                  @member ejs.TermStatsFacet
                  @param {String} fieldName The field name whose data will be used to construct the facet.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            valueField: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].terms_stats.value_field;
                }

                facet[name].terms_stats.value_field = fieldName;
                return this;
            },

            /**
                  Sets the field which will be used to pivot on (group-by).
      
                  @member ejs.TermStatsFacet
                  @param {String} fieldName The field name whose data will be used to construct the facet.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            keyField: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].terms_stats.key_field;
                }

                facet[name].terms_stats.key_field = fieldName;
                return this;
            },

            /**
                  Sets a script that will provide the terms for a given document.
      
                  @member ejs.TermStatsFacet
                  @param {String} script The script code.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scriptField: function (script) {
                if (script == null) {
                    return facet[name].terms_stats.script_field;
                }

                facet[name].terms_stats.script_field = script;
                return this;
            },

            /**
                  Define a script to evaluate of which the result will be used to generate
                  the statistical information.
      
                  @member ejs.TermStatsFacet
                  @param {String} code The script code to execute.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            valueScript: function (code) {
                if (code == null) {
                    return facet[name].terms_stats.value_script;
                }

                facet[name].terms_stats.value_script = code;
                return this;
            },

            /**
                  <p>Allows you to return all terms, even if the frequency count is 0. This should not be
                     used on fields that contain a large number of unique terms because it could cause
                     <em>out-of-memory</em> errors.</p>
      
                  @member ejs.TermStatsFacet
                  @param {String} trueFalse <code>true</code> or <code>false</code>
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            allTerms: function (trueFalse) {
                if (trueFalse == null) {
                    return facet[name].terms_stats.all_terms;
                }

                facet[name].terms_stats.all_terms = trueFalse;
                return this;
            },

            /**
                  The script language being used. Currently supported values are
                  <code>javascript</code>, <code>groovy</code>, and <code>mvel</code>.
      
                  @member ejs.TermStatsFacet
                  @param {String} language The language of the script.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lang: function (language) {
                if (language == null) {
                    return facet[name].terms_stats.lang;
                }

                facet[name].terms_stats.lang = language;
                return this;
            },

            /**
                  Allows you to set script parameters to be used during the execution of the script.
      
                  @member ejs.TermStatsFacet
                  @param {Object} oParams An object containing key/value pairs representing param name/value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            params: function (oParams) {
                if (oParams == null) {
                    return facet[name].terms_stats.params;
                }

                facet[name].terms_stats.params = oParams;
                return this;
            },

            /**
                  Sets the number of facet entries that will be returned for this facet. For instance, you
                  might ask for only the top 5 aggregate keys although there might be hundreds of
                  unique keys. <strong>Higher settings could cause memory strain</strong>.
      
                  @member ejs.TermStatsFacet
                  @param {Integer} facetSize The numer of facet entries to be returned.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            size: function (facetSize) {
                if (facetSize == null) {
                    return facet[name].terms_stats.size;
                }

                facet[name].terms_stats.size = facetSize;
                return this;
            },

            /**
                  Sets the type of ordering that will be performed on the date
                  buckets.  Valid values are:
                  
                  count - default, sort by the number of items in the bucket
                  term - sort by term value.
                  reverse_count - reverse sort of the number of items in the bucket
                  reverse_term - reverse sort of the term value.
                  total - sorts by the total value of the bucket contents
                  reverse_total - reverse sort of the total value of bucket contents
                  min - the minimum value in the bucket
                  reverse_min - the reverse sort of the minimum value
                  max - the maximum value in the bucket
                  reverse_max - the reverse sort of the maximum value
                  mean - the mean value of the bucket contents
                  reverse_mean - the reverse sort of the mean value of bucket contents.
                  
                  @member ejs.TermStatsFacet
                  @param {String} o The ordering method
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            order: function (o) {
                if (o == null) {
                    return facet[name].terms_stats.order;
                }

                o = o.toLowerCase();
                if (o === 'count' || o === 'term' || o === 'reverse_count' ||
                  o === 'reverse_term' || o === 'total' || o === 'reverse_total' ||
                  o === 'min' || o === 'reverse_min' || o === 'max' ||
                  o === 'reverse_max' || o === 'mean' || o === 'reverse_mean') {

                    facet[name].terms_stats.order = o;
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>A facet which returns the N most frequent terms within a collection
         or set of collections. Term facets are useful for building constructs
         which allow users to refine search results by filtering on terms returned
         by the facet.</p>
  
      <p>Facets are similar to SQL <code>GROUP BY</code> statements but perform much
         better. You can also construct several <em>"groups"</em> at once by simply
         specifying multiple facets.</p>
  
      <p>For more information on faceted navigation, see this Wikipedia article on
         <a href="http://en.wikipedia.org/wiki/Faceted_classification">Faceted Classification</a></p<
  
      @name ejs.TermsFacet
      @ejs facet
      @borrows ejs.FacetMixin.facetFilter as facetFilter
      @borrows ejs.FacetMixin.global as global
      @borrows ejs.FacetMixin.mode as mode
      @borrows ejs.FacetMixin.cacheFilter as cacheFilter
      @borrows ejs.FacetMixin.scope as scope
      @borrows ejs.FacetMixin.nested as nested
      @borrows ejs.FacetMixin._type as _type
      @borrows ejs.FacetMixin.toJSON as toJSON
  
      @desc
      <p>A facet which returns the N most frequent terms within a collection
         or set of collections.</p>
  
      @param {String} name The name which be used to refer to this facet. For instance,
          the facet itself might utilize a field named <code>doc_authors</code>. Setting
          <code>name</code> to <code>Authors</code> would allow you to refer to the
          facet by that name, possibly simplifying some of the display logic.
  
      */
    ejs.TermsFacet = function (name) {

        var
          _common = ejs.FacetMixin(name),
          facet = _common.toJSON();

        facet[name].terms = {};

        return extend(_common, {

            /**
                  Sets the field to be used to construct the this facet.  Set to
                  _index to return a facet count of hits per _index the search was
                  executed on.
      
                  @member ejs.TermsFacet
                  @param {String} fieldName The field name whose data will be used to construct the facet.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (fieldName) {
                if (fieldName == null) {
                    return facet[name].terms.field;
                }

                facet[name].terms.field = fieldName;
                return this;
            },

            /**
                  Aggregate statistical info across a set of fields.
      
                  @member ejs.TermsFacet
                  @param {Array} aFieldName An array of field names.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fields: function (fields) {
                if (fields == null) {
                    return facet[name].terms.fields;
                }

                if (!isArray(fields)) {
                    throw new TypeError('Argument must be an array');
                }

                facet[name].terms.fields = fields;
                return this;
            },

            /**
                  Sets a script that will provide the terms for a given document.
      
                  @member ejs.TermsFacet
                  @param {String} script The script code.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scriptField: function (script) {
                if (script == null) {
                    return facet[name].terms.script_field;
                }

                facet[name].terms.script_field = script;
                return this;
            },

            /**
                  Sets the number of facet entries that will be returned for this facet. For instance, you
                  might ask for only the top 5 <code>authors</code> although there might be hundreds of
                  unique authors.
      
                  @member ejs.TermsFacet
                  @param {Integer} facetSize The numer of facet entries to be returned.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            size: function (facetSize) {
                if (facetSize == null) {
                    return facet[name].terms.size;
                }

                facet[name].terms.size = facetSize;
                return this;
            },


            /**
                  Determines how many terms the coordinating node will request from
                  each shard.
      
                  @member ejs.TermsFacet
                  @param {Integer} shardSize The numer of terms to fetch from each shard.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            shardSize: function (shardSize) {
                if (shardSize == null) {
                    return facet[name].terms.shard_size;
                }

                facet[name].terms.shard_size = shardSize;
                return this;
            },

            /**
                  Sets the type of ordering that will be performed on the date
                  buckets.  Valid values are:
      
                  count - default, sort by the number of items in the bucket
                  term - sort by term value.
                  reverse_count - reverse sort of the number of items in the bucket
                  reverse_term - reverse sort of the term value.
      
                  @member ejs.TermsFacet
                  @param {String} o The ordering method
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            order: function (o) {
                if (o == null) {
                    return facet[name].terms.order;
                }

                o = o.toLowerCase();
                if (o === 'count' || o === 'term' ||
                  o === 'reverse_count' || o === 'reverse_term') {

                    facet[name].terms.order = o;
                }

                return this;
            },

            /**
                  <p>Allows you to return all terms, even if the frequency count is 0. This should not be
                     used on fields that contain a large number of unique terms because it could cause
                     <em>out-of-memory</em> errors.</p>
      
                  @member ejs.TermsFacet
                  @param {String} trueFalse <code>true</code> or <code>false</code>
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            allTerms: function (trueFalse) {
                if (trueFalse == null) {
                    return facet[name].terms.all_terms;
                }

                facet[name].terms.all_terms = trueFalse;
                return this;
            },

            /**
                  <p>Allows you to filter out unwanted facet entries. When passed
                  a single term, it is appended to the list of currently excluded
                  terms.  If passed an array, it overwrites all existing values.</p>
      
                  @member ejs.TermsFacet
                  @param {(String|String[])} exclude A single term to exclude or an
                    array of terms to exclude.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            exclude: function (exclude) {
                if (facet[name].terms.exclude == null) {
                    facet[name].terms.exclude = [];
                }

                if (exclude == null) {
                    return facet[name].terms.exclude;
                }

                if (isString(exclude)) {
                    facet[name].terms.exclude.push(exclude);
                } else if (isArray(exclude)) {
                    facet[name].terms.exclude = exclude;
                } else {
                    throw new TypeError('Argument must be string or array');
                }

                return this;
            },

            /**
                  <p>Allows you to only include facet entries matching a specified regular expression.</p>
      
                  @member ejs.TermsFacet
                  @param {String} exp A valid regular expression.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            regex: function (exp) {
                if (exp == null) {
                    return facet[name].terms.regex;
                }

                facet[name].terms.regex = exp;
                return this;
            },

            /**
                  <p>Allows you to set the regular expression flags to be used
                  with the <code>regex</code></p>
      
                  @member ejs.TermsFacet
                  @param {String} flags A valid regex flag - see <a href="http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#field_summary">Java Pattern API</a>
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            regexFlags: function (flags) {
                if (flags == null) {
                    return facet[name].terms.regex_flags;
                }

                facet[name].terms.regex_flags = flags;
                return this;
            },

            /**
                  Allows you modify the term using a script. The modified value
                  is then used in the facet collection.
      
                  @member ejs.TermsFacet
                  @param {String} scriptCode A valid script string to execute.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            script: function (scriptCode) {
                if (scriptCode == null) {
                    return facet[name].terms.script;
                }

                facet[name].terms.script = scriptCode;
                return this;
            },

            /**
                  The script language being used. Currently supported values are
                  <code>javascript</code>, <code>groovy</code>, and <code>mvel</code>.
      
                  @member ejs.TermsFacet
                  @param {String} language The language of the script.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lang: function (language) {
                if (language == null) {
                    return facet[name].terms.lang;
                }

                facet[name].terms.lang = language;
                return this;
            },

            /**
                  Sets parameters that will be applied to the script.  Overwrites
                  any existing params.
      
                  @member ejs.TermsFacet
                  @param {Object} p An object where the keys are the parameter name and
                    values are the parameter value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            params: function (p) {
                if (p == null) {
                    return facet[name].terms.params;
                }

                facet[name].terms.params = p;
                return this;
            },

            /**
                  Sets the execution hint determines how the facet is computed.
                  Currently only supported value is "map".
      
                  @member ejs.TermsFacet
                  @param {Object} h The hint value as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            executionHint: function (h) {
                if (h == null) {
                    return facet[name].terms.execution_hint;
                }

                facet[name].terms.execution_hint = h;
                return this;
            }

        });
    };

    /**
      @class
      <p>A single-value metrics aggregation that computes the average of numeric
      values that are extracted from the aggregated documents. These values can be
      extracted either from specific numeric fields in the documents, or be
      generated by a provided script.</p>
  
      @name ejs.AvgAggregation
      @ejs aggregation
      @borrows ejs.MetricsAggregationMixin.field as field
      @borrows ejs.MetricsAggregationMixin.script as script
      @borrows ejs.MetricsAggregationMixin.lang as lang
      @borrows ejs.MetricsAggregationMixin.scriptValuesSorted as scriptValuesSorted
      @borrows ejs.MetricsAggregationMixin.params as params
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that computes the average of numeric values that are extracted
      from the aggregated documents.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.AvgAggregation = function (name) {

        var
          _common = ejs.MetricsAggregationMixin(name, 'avg'),
          agg = _common.toJSON();

        return _common;
    };

    /**
      @class
      <p>A single-value metrics aggregation that calculates an approximate count of
      distinct values. Values can be extracted either from specific fields in the
      document or generated by a script.</p>
  
      @name ejs.CardinalityAggregation
      @ejs aggregation
      @borrows ejs.MetricsAggregationMixin.field as field
      @borrows ejs.MetricsAggregationMixin.script as script
      @borrows ejs.MetricsAggregationMixin.lang as lang
      @borrows ejs.MetricsAggregationMixin.params as params
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that calculates an approximate count of distinct values.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.CardinalityAggregation = function (name) {

        var
          _common = ejs.MetricsAggregationMixin(name, 'cardinality'),
          agg = _common.toJSON();

        // not supported in cardinality aggregation
        delete _common.scriptValuesSorted;

        return extend(_common, {

            /**
            Set to false to disable rehashing of values.  You must have computed a hash
            on the client-side and stored it into your documents if you disable this.
      
            @member ejs.CardinalityAggregation
            @param {Boolean} trueFalse set to false to disable rehashing
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            rehash: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].cardinality.rehash;
                }

                agg[name].cardinality.rehash = trueFalse;
                return this;
            },

            /**
            Allows to trade memory for accuracy, and defines a unique count below which
            counts are expected to be close to accurate. Above this value, counts might
            become a bit more fuzzy. The maximum supported value is 40000, thresholds
            above this number will have the same effect as a threshold of 40000.
            Default value depends on the number of parent aggregations that multiple
            create buckets (such as terms or histograms).
      
            @member ejs.CardinalityAggregation
            @param {Long} num The threshold value
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            precisionThreshold: function (num) {
                if (num == null) {
                    return agg[name].cardinality.precision_threshold;
                }

                agg[name].cardinality.precision_threshold = num;
                return this;
            }

        });

    };

    /**
      @class
      <p>A multi-bucket aggregation similar to the histogram except it can only be
      applied on date values. Since dates are represented in elasticsearch
      internally as long values, it is possible to use the normal histogram on
      dates as well, though accuracy will be compromised. The reason for this is
      in the fact that time based intervals are not fixed (think of leap years and
      on the number of days in a month). For this reason, we need a special
      support for time based data. From a functionality perspective, this
      histogram supports the same features as the normal histogram. The main
      difference is that the interval can be specified by date/time expressions.</p>
  
      @name ejs.DateHistogramAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation similar to the histogram except it can only be applied on
      date values.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.DateHistogramAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        agg[name].date_histogram = {};

        return extend(_common, {

            /**
            <p>Sets the field to gather terms from.</p>
      
            @member ejs.DateHistogramAggregation
            @param {String} field a valid field name..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (field) {
                if (field == null) {
                    return agg[name].date_histogram.field;
                }

                agg[name].date_histogram.field = field;
                return this;
            },

            /**
            Allows you generate or modify the terms using a script.
      
            @member ejs.DateHistogramAggregation
            @param {String} scriptCode A valid script string to execute.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            script: function (scriptCode) {
                if (scriptCode == null) {
                    return agg[name].date_histogram.script;
                }

                agg[name].date_histogram.script = scriptCode;
                return this;
            },

            /**
            The script language being used.
      
            @member ejs.DateHistogramAggregation
            @param {String} language The language of the script.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            lang: function (language) {
                if (language == null) {
                    return agg[name].date_histogram.lang;
                }

                agg[name].date_histogram.lang = language;
                return this;
            },

            /**
            Set the date time zone.
      
            @member ejs.DateHistogramAggregation
            @param {String} tz the time zone.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            timeZone: function (tz) {
                if (tz == null) {
                    return agg[name].date_histogram.time_zone;
                }

                agg[name].date_histogram.time_zone = tz;
                return this;
            },

            /**
            Set the pre-rouding date time zone.
      
            @member ejs.DateHistogramAggregation
            @param {String} tz the time zone.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            preZone: function (tz) {
                if (tz == null) {
                    return agg[name].date_histogram.pre_zone;
                }

                agg[name].date_histogram.pre_zone = tz;
                return this;
            },

            /**
            Set the post-rouding date time zone.
      
            @member ejs.DateHistogramAggregation
            @param {String} tz the time zone.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            postZone: function (tz) {
                if (tz == null) {
                    return agg[name].date_histogram.post_zone;
                }

                agg[name].date_histogram.post_zone = tz;
                return this;
            },

            /**
            Set the pre-rouding offset.
      
            @member ejs.DateHistogramAggregation
            @param {String} offset the offset.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            preOffset: function (offset) {
                if (offset == null) {
                    return agg[name].date_histogram.pre_offset;
                }

                agg[name].date_histogram.pre_offset = offset;
                return this;
            },

            /**
            Set the post-rouding offset.
      
            @member ejs.DateHistogramAggregation
            @param {String} offset the offset.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            postOffset: function (offset) {
                if (offset == null) {
                    return agg[name].date_histogram.post_offset;
                }

                agg[name].date_histogram.post_offset = offset;
                return this;
            },

            /**
            Set's the range/bounds for the histogram aggregation.  Useful when you
            want to include buckets that might be outside the bounds of indexed
            documents.
      
            @member ejs.DateHistogramAggregation
            @param {(String|Long)} min The start bound / minimum bound value
            @param {(String|Long)} max The end bound / maximum bound value
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            extendedBounds: function (min, max) {
                var bounds;
                if (min == null && max == null) {
                    return agg[name].date_histogram.extended_bounds;
                }

                bounds = {};
                if (min != null) {
                    bounds.min = min;
                }

                if (max != null) {
                    bounds.max = max;
                }

                agg[name].date_histogram.extended_bounds = bounds;
                return this;
            },

            /**
            Sets the histogram interval.  Buckets are generated based on this interval
            value.
      
            @member ejs.DateHistogramAggregation
            @param {String} i The interval
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            interval: function (i) {
                if (i == null) {
                    return agg[name].date_histogram.interval;
                }

                agg[name].date_histogram.interval = i;
                return this;
            },

            /**
            Sets the format expression for the terms.  Use for number or date
            formatting
      
            @member ejs.DateHistogramAggregation
            @param {String} f the format string
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            format: function (f) {
                if (f == null) {
                    return agg[name].date_histogram.format;
                }

                agg[name].date_histogram.format = f;
                return this;
            },

            /**
            Enable the response to be returned as a keyed object where the key is the
            bucket interval.
      
            @member ejs.DateHistogramAggregation
            @param {Boolean} trueFalse to enable keyed response or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            keyed: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].date_histogram.keyed;
                }

                agg[name].date_histogram.keyed = trueFalse;
                return this;
            },

            /**
            Set to true to assume script values are sorted.
      
            @member ejs.DateHistogramAggregation
            @param {Boolean} trueFalse assume sorted values or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            scriptValuesSorted: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].date_histogram.script_values_sorted;
                }

                agg[name].date_histogram.script_values_sorted = trueFalse;
                return this;
            },

            /**
            Set to true to apply interval adjusts to day and above intervals.
      
            @member ejs.DateHistogramAggregation
            @param {Boolean} trueFalse adjust large intervals or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            preZoneAdjustLargeInterval: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].date_histogram.pre_zone_adjust_large_interval;
                }

                agg[name].date_histogram.pre_zone_adjust_large_interval = trueFalse;
                return this;
            },

            /**
            Only return terms that match more than a configured number of hits.
      
            @member ejs.DateHistogramAggregation
            @param {Integer} num The numer of minimum number of hits.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            minDocCount: function (num) {
                if (num == null) {
                    return agg[name].date_histogram.min_doc_count;
                }

                agg[name].date_histogram.min_doc_count = num;
                return this;
            },

            /**
            Sets parameters that will be applied to the script.  Overwrites
            any existing params.
      
            @member ejs.DateHistogramAggregation
            @param {Object} p An object where the keys are the parameter name and
              values are the parameter value.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            params: function (p) {
                if (p == null) {
                    return agg[name].date_histogram.params;
                }

                agg[name].date_histogram.params = p;
                return this;
            },

            /**
            Sets order for the aggregated values.
      
            @member ejs.DateHistogramAggregation
            @param {String} order The order string.
            @param {String} direction The sort direction, asc or desc.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            order: function (order, direction) {
                if (order == null) {
                    return agg[name].date_histogram.order;
                }

                if (direction == null) {
                    direction = 'desc';
                }

                direction = direction.toLowerCase();
                if (direction !== 'asc' && direction !== 'desc') {
                    direction = 'desc';
                }

                agg[name].date_histogram.order = {};
                agg[name].date_histogram.order[order] = direction;
                return this;
            }

        });
    };

    /**
      @class
      <p>A range aggregation that is dedicated for date values. The main difference
      between this aggregation and the normal range aggregation is that the from
      and to values can be expressed in Date Math expressions, and it is also
      possible to specify a date format by which the from and to response fields
      will be returned. Note that this aggregration includes the from value and
      excludes the to value for each range.</p>
  
      <p>Note that this aggregration includes the from value and excludes the to
      value for each range.</p>
  
      @name ejs.DateRangeAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that is dedicated for date value ranges.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.DateRangeAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        agg[name].date_range = {};

        return extend(_common, {

            /**
            <p>Sets the field to gather terms from.</p>
      
            @member ejs.DateRangeAggregation
            @param {String} field a valid field name..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (field) {
                if (field == null) {
                    return agg[name].date_range.field;
                }

                agg[name].date_range.field = field;
                return this;
            },

            /**
            Allows you generate or modify the terms using a script.
      
            @member ejs.DateRangeAggregation
            @param {String} scriptCode A valid script string to execute.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            script: function (scriptCode) {
                if (scriptCode == null) {
                    return agg[name].date_range.script;
                }

                agg[name].date_range.script = scriptCode;
                return this;
            },

            /**
            The script language being used.
      
            @member ejs.DateRangeAggregation
            @param {String} language The language of the script.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            lang: function (language) {
                if (language == null) {
                    return agg[name].date_range.lang;
                }

                agg[name].date_range.lang = language;
                return this;
            },

            /**
            Sets the date format expression.
      
            @member ejs.DateRangeAggregation
            @param {String} f the format string
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            format: function (f) {
                if (f == null) {
                    return agg[name].date_range.format;
                }

                agg[name].date_range.format = f;
                return this;
            },

            /**
            Adds a range to the list of exsiting range expressions.
      
            @member ejs.DateRangeAggregation
            @param {String} from The start value, use null to ignore
            @param {String} to The end value, use null to ignore.
            @param {String} key Optional key/bucket name for keyed responses.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            range: function (from, to, key) {
                var rangeObj = {};
                if (agg[name].date_range.ranges == null) {
                    agg[name].date_range.ranges = [];
                }

                if (from == null && to == null) {
                    return agg[name].date_range.ranges;
                }

                if (from != null) {
                    rangeObj.from = from;
                }

                if (to != null) {
                    rangeObj.to = to;
                }

                if (key != null) {
                    rangeObj.key = key;
                }

                agg[name].date_range.ranges.push(rangeObj);
                return this;
            },

            /**
            Enable the response to be returned as a keyed object where the key is the
            bucket interval.
      
            @member ejs.DateRangeAggregation
            @param {Boolean} trueFalse to enable keyed response or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            keyed: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].date_range.keyed;
                }

                agg[name].date_range.keyed = trueFalse;
                return this;
            },

            /**
            Set to true to assume script values are sorted.
      
            @member ejs.DateRangeAggregation
            @param {Boolean} trueFalse assume sorted values or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            scriptValuesSorted: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].date_range.script_values_sorted;
                }

                agg[name].date_range.script_values_sorted = trueFalse;
                return this;
            },

            /**
            Sets parameters that will be applied to the script.  Overwrites
            any existing params.
      
            @member ejs.DateRangeAggregation
            @param {Object} p An object where the keys are the parameter name and
              values are the parameter value.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            params: function (p) {
                if (p == null) {
                    return agg[name].date_range.params;
                }

                agg[name].date_range.params = p;
                return this;
            }

        });
    };

    /**
      @class
      <p>A multi-value metrics aggregation that computes stats over numeric values
      extracted from the aggregated documents. These values can be extracted either
      from specific numeric fields in the documents, or be generated by a provided
      script.</p>
  
      <p>The extended_stats aggregations is an extended version of the
      <code>StatsAggregation</code>, where additional metrics are added such as
      sum_of_squares, variance and std_deviation.</p>
  
      @name ejs.ExtendedStatsAggregation
      @ejs aggregation
      @borrows ejs.MetricsAggregationMixin.field as field
      @borrows ejs.MetricsAggregationMixin.script as script
      @borrows ejs.MetricsAggregationMixin.lang as lang
      @borrows ejs.MetricsAggregationMixin.scriptValuesSorted as scriptValuesSorted
      @borrows ejs.MetricsAggregationMixin.params as params
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that computes extra stats over numeric values extracted from
      the aggregated documents.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.ExtendedStatsAggregation = function (name) {

        var
          _common = ejs.MetricsAggregationMixin(name, 'extended_stats'),
          agg = _common.toJSON();

        return _common;
    };

    /**
      @class
      <p>Defines a single bucket of all the documents in the current document set
      context that match a specified filter. Often this will be used to narrow down
      the current aggregation context to a specific set of documents.</p>
  
      @name ejs.FilterAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Defines a single bucket of all the documents that match a given filter.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.FilterAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        return extend(_common, {

            /**
            <p>Sets the filter to be used for this aggregation.</p>
      
            @member ejs.FilterAggregation
            @param {Filter} oFilter A valid <code>Filter</code> object.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            filter: function (oFilter) {
                if (oFilter == null) {
                    return agg[name].filter;
                }

                if (!isFilter(oFilter)) {
                    throw new TypeError('Argument must be a Filter');
                }

                agg[name].filter = oFilter.toJSON();
                return this;
            }

        });
    };

    /**
      @class
      <p>A multi-bucket aggregation that works on geo_point fields and conceptually
      works very similar to the range aggregation. The user can define a point of
      origin and a set of distance range buckets. The aggregation evaluate the
      distance of each document value from the origin point and determines the
      buckets it belongs to based on the ranges (a document belongs to a bucket
      if the distance between the document and the origin falls within the distance
      range of the bucket).</p>
  
      @name ejs.GeoDistanceAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that works on geo_point fields and conceptually works very
      similar to the range aggregation.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.GeoDistanceAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          point = ejs.GeoPoint([0, 0]),
          agg = _common.toJSON();

        agg[name].geo_distance = {};

        return extend(_common, {

            /**
            <p>Sets the field to gather terms from.</p>
      
            @member ejs.GeoDistanceAggregation
            @param {String} field a valid field name..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (field) {
                if (field == null) {
                    return agg[name].geo_distance.field;
                }

                agg[name].geo_distance.field = field;
                return this;
            },

            /**
            Sets the distance unit.  Valid values are:
            in, yd, ft, km, NM, mm, cm, mi, and m.
      
            @member ejs.GeoDistanceAggregation
            @param {Number} unit the unit of distance measure.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            unit: function (unit) {
                if (unit == null) {
                    return agg[name].geo_distance.unit;
                }

                if (unit === 'in' || unit === 'yd' || unit === 'ft' || unit === 'km' ||
                    unit === 'NM' || unit === 'mm' || unit === 'cm' || unit === 'mi' ||
                    unit === 'm') {
                    agg[name].geo_distance.unit = unit;
                }

                return this;
            },

            /**
            How to compute the distance. Valid values are:
            plane, arc, sloppy_arc, and factor.
      
            @member ejs.GeoDistanceAggregation
            @param {String} type The execution type as a string.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            distanceType: function (type) {
                if (type == null) {
                    return agg[name].geo_distance.distance_type;
                }

                type = type.toLowerCase();
                if (type === 'plane' || type === 'arc' || type === 'sloppy_arc' ||
                    type === 'factor') {
                    agg[name].geo_distance.distance_type = type;
                }

                return this;
            },

            /**
            Sets the point of origin from where distances will be measured.
      
            @member ejs.GeoDistanceAggregation
            @param {GeoPoint} p A valid GeoPoint object
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            origin: function (p) {
                if (p == null) {
                    return point;
                }

                if (!isGeoPoint(p)) {
                    throw new TypeError('Argument must be a GeoPoint');
                }

                point = p;
                agg[name].geo_distance.origin = p.toJSON();
                return this;
            },

            /**
            Sets the point of origin from where distances will be measured. Same as
            origin.
      
            @member ejs.GeoDistanceAggregation
            @param {GeoPoint} p A valid GeoPoint object
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            point: function (p) {
                if (p == null) {
                    return point;
                }

                if (!isGeoPoint(p)) {
                    throw new TypeError('Argument must be a GeoPoint');
                }

                point = p;
                agg[name].geo_distance.point = p.toJSON();
                return this;
            },

            /**
            Sets the point of origin from where distances will be measured. Same as
            origin.
      
            @member ejs.GeoDistanceAggregation
            @param {GeoPoint} p A valid GeoPoint object
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            center: function (p) {
                if (p == null) {
                    return point;
                }

                if (!isGeoPoint(p)) {
                    throw new TypeError('Argument must be a GeoPoint');
                }

                point = p;
                agg[name].geo_distance.center = p.toJSON();
                return this;
            },

            /**
            Adds a range to the list of exsiting range expressions.
      
            @member ejs.GeoDistanceAggregation
            @param {String} from The start value, use null to ignore
            @param {String} to The end value, use null to ignore.
            @param {String} key Optional key/bucket name for keyed responses.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            range: function (from, to, key) {
                var rangeObj = {};
                if (agg[name].geo_distance.ranges == null) {
                    agg[name].geo_distance.ranges = [];
                }

                if (from == null && to == null) {
                    return agg[name].geo_distance.ranges;
                }

                if (from != null) {
                    rangeObj.from = from;
                }

                if (to != null) {
                    rangeObj.to = to;
                }

                if (key != null) {
                    rangeObj.key = key;
                }

                agg[name].geo_distance.ranges.push(rangeObj);
                return this;
            },

            /**
            Enable the response to be returned as a keyed object where the key is the
            bucket interval.
      
            @member ejs.GeoDistanceAggregation
            @param {Boolean} trueFalse to enable keyed response or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            keyed: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].geo_distance.keyed;
                }

                agg[name].geo_distance.keyed = trueFalse;
                return this;
            }

        });
    };

    /**
      @class
      <p>A multi-bucket aggregation that works on geo_point fields and groups points
      into buckets that represent cells in a grid. The resulting grid can be sparse
      and only contains cells that have matching data. Each cell is labeled using a
      geohash which is of user-definable precision.</p>
  
      @name ejs.GeoHashGridAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that works on geo_point fields and groups points into buckets
      that represent cells in a grid.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.GeoHashGridAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        agg[name].geohash_grid = {};

        return extend(_common, {

            /**
            Sets the geo field to perform calculations from.
      
            @member ejs.GeoHashGridAggregation
            @param {String} field a valid field name.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (field) {
                if (field == null) {
                    return agg[name].geohash_grid.field;
                }

                agg[name].geohash_grid.field = field;
                return this;
            },

            /**
            Sets the Geo Hash precision.  The precision value can be between 1 and 12
            where 12 is the highest precision.
      
            @member ejs.GeoHashGridAggregation
            @param {Integer} p The precision.  Integer between 1 and 12.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            precision: function (p) {
                if (p == null) {
                    return agg[name].geohash_grid.precision;
                }

                agg[name].geohash_grid.precision = p;
                return this;
            },

            /**
            Sets the number of aggregation entries that will be returned.
      
            @member ejs.GeoHashGridAggregation
            @param {Integer} size The numer of aggregation entries to be returned.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            size: function (size) {
                if (size == null) {
                    return agg[name].geohash_grid.size;
                }

                agg[name].geohash_grid.size = size;
                return this;
            },


            /**
            Determines how many geohash_grid the coordinating node will request from
            each shard.
      
            @member ejs.GeoHashGridAggregation
            @param {Integer} shardSize The numer of geohash_grid to fetch from each shard.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            shardSize: function (shardSize) {
                if (shardSize == null) {
                    return agg[name].geohash_grid.shard_size;
                }

                agg[name].geohash_grid.shard_size = shardSize;
                return this;
            }

        });
    };

    /**
      @class
      <p>Defines a single bucket of all the documents within the search execution
      context. This context is defined by the indices and the document types you’re
      searching on, but is not influenced by the search query itself.</p>
  
      @name ejs.GlobalAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Defines a single bucket of all the documents within the search context.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.GlobalAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        agg[name].global = {};

        return _common;
    };

    /**
      @class
      <p>A multi-bucket values source based aggregation that can be applied on
      numeric values extracted from the documents. It dynamically builds fixed
      size (a.k.a. interval) buckets over the values.</p>
  
      @name ejs.HistogramAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that can be applied on numeric values extracted from the
      documents.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.HistogramAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        agg[name].histogram = {};

        return extend(_common, {

            /**
            <p>Sets the field to gather terms from.</p>
      
            @member ejs.HistogramAggregation
            @param {String} field a valid field name..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (field) {
                if (field == null) {
                    return agg[name].histogram.field;
                }

                agg[name].histogram.field = field;
                return this;
            },

            /**
            Allows you generate or modify the terms using a script.
      
            @member ejs.HistogramAggregation
            @param {String} scriptCode A valid script string to execute.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            script: function (scriptCode) {
                if (scriptCode == null) {
                    return agg[name].histogram.script;
                }

                agg[name].histogram.script = scriptCode;
                return this;
            },

            /**
            The script language being used.
      
            @member ejs.HistogramAggregation
            @param {String} language The language of the script.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            lang: function (language) {
                if (language == null) {
                    return agg[name].histogram.lang;
                }

                agg[name].histogram.lang = language;
                return this;
            },

            /**
            Sets the format expression for the terms.  Use for number or date
            formatting
      
            @member ejs.HistogramAggregation
            @param {String} f the format string
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            format: function (f) {
                if (f == null) {
                    return agg[name].histogram.format;
                }

                agg[name].histogram.format = f;
                return this;
            },

            /**
            Set's the range/bounds for the histogram aggregation.  Useful when you
            want to include buckets that might be outside the bounds of indexed
            documents.
      
            @member ejs.HistogramAggregation
            @param {Long} min The start bound / minimum bound value
            @param {Long} max The end bound / maximum bound value
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            extendedBounds: function (min, max) {
                var bounds;
                if (min == null && max == null) {
                    return agg[name].histogram.extended_bounds;
                }

                bounds = {};
                if (min != null) {
                    bounds.min = min;
                }

                if (max != null) {
                    bounds.max = max;
                }

                agg[name].histogram.extended_bounds = bounds;
                return this;
            },

            /**
            Sets the histogram interval.  Buckets are generated based on this interval
            value.
      
            @member ejs.HistogramAggregation
            @param {Integer} i The interval
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            interval: function (i) {
                if (i == null) {
                    return agg[name].histogram.interval;
                }

                agg[name].histogram.interval = i;
                return this;
            },

            /**
            Only return terms that match more than a configured number of hits.
      
            @member ejs.HistogramAggregation
            @param {Integer} num The numer of minimum number of hits.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            minDocCount: function (num) {
                if (num == null) {
                    return agg[name].histogram.min_doc_count;
                }

                agg[name].histogram.min_doc_count = num;
                return this;
            },

            /**
            Enable the response to be returned as a keyed object where the key is the
            bucket interval.
      
            @member ejs.HistogramAggregation
            @param {Boolean} trueFalse to enable keyed response or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            keyed: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].histogram.keyed;
                }

                agg[name].histogram.keyed = trueFalse;
                return this;
            },

            /**
            Set to true to assume script values are sorted.
      
            @member ejs.HistogramAggregation
            @param {Boolean} trueFalse assume sorted values or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            scriptValuesSorted: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].histogram.script_values_sorted;
                }

                agg[name].histogram.script_values_sorted = trueFalse;
                return this;
            },

            /**
            Sets parameters that will be applied to the script.  Overwrites
            any existing params.
      
            @member ejs.HistogramAggregation
            @param {Object} p An object where the keys are the parameter name and
              values are the parameter value.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            params: function (p) {
                if (p == null) {
                    return agg[name].histogram.params;
                }

                agg[name].histogram.params = p;
                return this;
            },

            /**
            Sets order for the aggregated values.
      
            @member ejs.HistogramAggregation
            @param {String} order The order string.
            @param {String} direction The sort direction, asc or desc.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            order: function (order, direction) {
                if (order == null) {
                    return agg[name].histogram.order;
                }

                if (direction == null) {
                    direction = 'desc';
                }

                direction = direction.toLowerCase();
                if (direction !== 'asc' && direction !== 'desc') {
                    direction = 'desc';
                }

                agg[name].histogram.order = {};
                agg[name].histogram.order[order] = direction;
                return this;
            }

        });
    };

    /**
      @class
      <p>A dedicated range aggregation for IPv4 typed fields.</p>
  
      <p>Note that this aggregration includes the from value and excludes the to
      value for each range.</p>
  
      @name ejs.IPv4RangeAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>A dedicated range aggregation for IPv4 typed fields.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.IPv4RangeAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        agg[name].ip_range = {};

        return extend(_common, {

            /**
            <p>Sets the field to gather terms from.</p>
      
            @member ejs.IPv4RangeAggregation
            @param {String} field a valid field name..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (field) {
                if (field == null) {
                    return agg[name].ip_range.field;
                }

                agg[name].ip_range.field = field;
                return this;
            },

            /**
            Allows you generate or modify the terms using a script.
      
            @member ejs.IPv4RangeAggregation
            @param {String} scriptCode A valid script string to execute.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            script: function (scriptCode) {
                if (scriptCode == null) {
                    return agg[name].ip_range.script;
                }

                agg[name].ip_range.script = scriptCode;
                return this;
            },

            /**
            The script language being used.
      
            @member ejs.IPv4RangeAggregation
            @param {String} language The language of the script.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            lang: function (language) {
                if (language == null) {
                    return agg[name].ip_range.lang;
                }

                agg[name].ip_range.lang = language;
                return this;
            },

            /**
            Adds a range to the list of exsiting range expressions.
      
            @member ejs.IPv4RangeAggregation
            @param {String} from The start value, use null to ignore
            @param {String} to The end value, use null to ignore.
            @param {String} key Optional key/bucket name for keyed responses.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            range: function (from, to, mask, key) {
                var rangeObj = {};
                if (agg[name].ip_range.ranges == null) {
                    agg[name].ip_range.ranges = [];
                }

                if (from == null && to == null && mask == null) {
                    return agg[name].ip_range.ranges;
                }

                if (from != null) {
                    rangeObj.from = from;
                }

                if (to != null) {
                    rangeObj.to = to;
                }

                if (mask != null) {
                    rangeObj.mask = mask;
                }

                if (key != null) {
                    rangeObj.key = key;
                }

                agg[name].ip_range.ranges.push(rangeObj);
                return this;
            },

            /**
            Enable the response to be returned as a keyed object where the key is the
            bucket interval.
      
            @member ejs.IPv4RangeAggregation
            @param {Boolean} trueFalse to enable keyed response or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            keyed: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].ip_range.keyed;
                }

                agg[name].ip_range.keyed = trueFalse;
                return this;
            },

            /**
            Set to true to assume script values are sorted.
      
            @member ejs.IPv4RangeAggregation
            @param {Boolean} trueFalse assume sorted values or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            scriptValuesSorted: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].ip_range.script_values_sorted;
                }

                agg[name].ip_range.script_values_sorted = trueFalse;
                return this;
            },

            /**
            Sets parameters that will be applied to the script.  Overwrites
            any existing params.
      
            @member ejs.IPv4RangeAggregation
            @param {Object} p An object where the keys are the parameter name and
              values are the parameter value.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            params: function (p) {
                if (p == null) {
                    return agg[name].ip_range.params;
                }

                agg[name].ip_range.params = p;
                return this;
            }

        });
    };

    /**
      @class
      <p>A single-value metrics aggregation that keeps track and returns the
      maximum value among the numeric values extracted from the aggregated
      documents. These values can be extracted either from specific numeric fields
      in the documents, or be generated by a provided script.</p>
  
      @name ejs.MaxAggregation
      @ejs aggregation
      @borrows ejs.MetricsAggregationMixin.field as field
      @borrows ejs.MetricsAggregationMixin.script as script
      @borrows ejs.MetricsAggregationMixin.lang as lang
      @borrows ejs.MetricsAggregationMixin.scriptValuesSorted as scriptValuesSorted
      @borrows ejs.MetricsAggregationMixin.params as params
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that keeps track and returns the maximum value among the
      numeric values extracted from the aggregated documents.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.MaxAggregation = function (name) {

        var
          _common = ejs.MetricsAggregationMixin(name, 'max'),
          agg = _common.toJSON();

        return _common;
    };

    /**
      @class
      <p>A single-value metrics aggregation that keeps track and returns the
      minimum value among numeric values extracted from the aggregated documents.
      These values can be extracted either from specific numeric fields in the
      documents, or be generated by a provided script.</p>
  
      @name ejs.MinAggregation
      @ejs aggregation
      @borrows ejs.MetricsAggregationMixin.field as field
      @borrows ejs.MetricsAggregationMixin.script as script
      @borrows ejs.MetricsAggregationMixin.lang as lang
      @borrows ejs.MetricsAggregationMixin.scriptValuesSorted as scriptValuesSorted
      @borrows ejs.MetricsAggregationMixin.params as params
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that keeps track and returns the minimum value among numeric
      values extracted from the aggregated documents.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.MinAggregation = function (name) {

        var
          _common = ejs.MetricsAggregationMixin(name, 'min'),
          agg = _common.toJSON();

        return _common;
    };

    /**
      @class
      <p>A field data based single bucket aggregation, that creates a bucket of all
      documents in the current document set context that are missing a field value
      (effectively, missing a field or having the configured NULL value set).</p>
  
      @name ejs.MissingAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Defines a bucket of all documents that are missing a field value.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.MissingAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        agg[name].missing = {};

        return extend(_common, {

            /**
            <p>Sets the field to gather missing terms from.</p>
      
            @member ejs.MissingAggregation
            @param {String} field a valid field name..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (field) {
                if (field == null) {
                    return agg[name].missing.field;
                }

                agg[name].missing.field = field;
                return this;
            }

        });
    };

    /**
      @class
      <p>A special single bucket aggregation that enables aggregating nested
      documents.</p>
  
      @name ejs.NestedAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>A special single bucket aggregation that enables aggregating nested
      documents.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.NestedAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        agg[name].nested = {};

        return extend(_common, {

            /**
            <p>Sets the nested path.</p>
      
            @member ejs.NestedAggregation
            @param {String} path The nested path value.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            path: function (path) {
                if (path == null) {
                    return agg[name].nested.path;
                }

                agg[name].nested.path = path;
                return this;
            }

        });
    };

    /**
      @class
      <p>A multi-value metrics aggregation that calculates one or more percentiles
      over numeric values extracted from the aggregated documents. These values can
      be extracted either from specific numeric fields in the documents, or be
      generated by a provided script.</p>
  
      @name ejs.PercentilesAggregation
      @ejs aggregation
      @borrows ejs.MetricsAggregationMixin.field as field
      @borrows ejs.MetricsAggregationMixin.script as script
      @borrows ejs.MetricsAggregationMixin.lang as lang
      @borrows ejs.MetricsAggregationMixin.scriptValuesSorted as scriptValuesSorted
      @borrows ejs.MetricsAggregationMixin.params as params
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that calculates one or more percentiles over numeric values
      extracted from the aggregated documents.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.PercentilesAggregation = function (name) {

        var
          _common = ejs.MetricsAggregationMixin(name, 'percentiles'),
          agg = _common.toJSON();

        return extend(_common, {

            /**
            Enable the response to be returned as a keyed object where the key is the
            bucket interval.
      
            @member ejs.PercentilesAggregation
            @param {Boolean} trueFalse to enable keyed response or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            keyed: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].percentiles.keyed;
                }

                agg[name].percentiles.keyed = trueFalse;
                return this;
            },

            /**
            Sets the percentile bucket array.  Overwrites all existing values.
      
            @member ejs.PercentilesAggregation
            @param {Double[]} percents A double array of percentiles
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            percents: function (percentArr) {
                if (percentArr == null) {
                    return agg[name].percentiles.percents;
                }

                if (!isArray(percentArr)) {
                    throw new TypeError('Percents must be an array of doubles');
                }

                agg[name].percentiles.percents = percentArr;
                return this;
            },

            /**
            Add a single percentile to the current list of percentiles.
      
            @member ejs.PercentilesAggregation
            @param {Double} percentile A double percentile value to add
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            percent: function (percentile) {
                if (agg[name].percentiles.percents == null) {
                    agg[name].percentiles.percents = [];
                }

                if (percentile == null) {
                    return agg[name].percentiles.percents;
                }

                agg[name].percentiles.percents.push(percentile);
                return this;
            },

            /**
            Compression controls memory usage and approximation error. The compression
            value limits the maximum number of nodes to 100 * compression.  By
            increasing the compression value, you can increase the accuracy of your
            percentiles at the cost of more memory. Larger compression values also make
            the algorithm slower since the underlying tree data structure grows in
            size, resulting in more expensive operations. The default compression
            value is 100.
      
            @member ejs.PercentilesAggregation
            @param {Integer} c The compression level.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            compression: function (c) {
                if (c == null) {
                    return agg[name].percentiles.compression;
                }

                agg[name].percentiles.compression = c;
                return this;
            }

        });
    };

    /**
      @class
      <p>A multi-bucket value source based aggregation that enables the user to
      define a set of ranges - each representing a bucket. During the aggregation
      process, the values extracted from each document will be checked against each
      bucket range and "bucket" the relevant/matching document.</p>
  
      <p>Note that this aggregration includes the from value and excludes the to
      value for each range.</p>
  
      @name ejs.RangeAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that enables the user to define a set of ranges that each
      represent a bucket.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.RangeAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        agg[name].range = {};

        return extend(_common, {

            /**
            <p>Sets the field to gather terms from.</p>
      
            @member ejs.RangeAggregation
            @param {String} field a valid field name..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (field) {
                if (field == null) {
                    return agg[name].range.field;
                }

                agg[name].range.field = field;
                return this;
            },

            /**
            Allows you generate or modify the terms using a script.
      
            @member ejs.RangeAggregation
            @param {String} scriptCode A valid script string to execute.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            script: function (scriptCode) {
                if (scriptCode == null) {
                    return agg[name].range.script;
                }

                agg[name].range.script = scriptCode;
                return this;
            },

            /**
            The script language being used.
      
            @member ejs.RangeAggregation
            @param {String} language The language of the script.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            lang: function (language) {
                if (language == null) {
                    return agg[name].range.lang;
                }

                agg[name].range.lang = language;
                return this;
            },

            /**
            Adds a range to the list of exsiting range expressions.
      
            @member ejs.RangeAggregation
            @param {String} from The start value, use null to ignore
            @param {String} to The end value, use null to ignore.
            @param {String} key Optional key/bucket name for keyed responses.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            range: function (from, to, key) {
                var rangeObj = {};
                if (agg[name].range.ranges == null) {
                    agg[name].range.ranges = [];
                }

                if (from == null && to == null) {
                    return agg[name].range.ranges;
                }

                if (from != null) {
                    rangeObj.from = from;
                }

                if (to != null) {
                    rangeObj.to = to;
                }

                if (key != null) {
                    rangeObj.key = key;
                }

                agg[name].range.ranges.push(rangeObj);
                return this;
            },

            /**
            Enable the response to be returned as a keyed object where the key is the
            bucket interval.
      
            @member ejs.RangeAggregation
            @param {Boolean} trueFalse to enable keyed response or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            keyed: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].range.keyed;
                }

                agg[name].range.keyed = trueFalse;
                return this;
            },

            /**
            Set to true to assume script values are sorted.
      
            @member ejs.RangeAggregation
            @param {Boolean} trueFalse assume sorted values or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            scriptValuesSorted: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].range.script_values_sorted;
                }

                agg[name].range.script_values_sorted = trueFalse;
                return this;
            },

            /**
            Sets parameters that will be applied to the script.  Overwrites
            any existing params.
      
            @member ejs.RangeAggregation
            @param {Object} p An object where the keys are the parameter name and
              values are the parameter value.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            params: function (p) {
                if (p == null) {
                    return agg[name].range.params;
                }

                agg[name].range.params = p;
                return this;
            }

        });
    };

    /**
      @class
      <p>An aggregation that returns interesting or unusual occurrences of terms in
      a set.</p>
  
      @name ejs.SignificantTermsAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>An aggregation that returns interesting or unusual occurrences of terms in
      a set.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.SignificantTermsAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        agg[name].significant_terms = {};

        return extend(_common, {

            /**
            <p>Sets the field to gather terms from.</p>
      
            @member ejs.SignificantTermsAggregation
            @param {String} field a valid field name..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (field) {
                if (field == null) {
                    return agg[name].significant_terms.field;
                }

                agg[name].significant_terms.field = field;
                return this;
            },

            /**
            Sets the format expression for the terms.  Use for number or date
            formatting.
      
            @member ejs.SignificantTermsAggregation
            @param {String} f the format string
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            format: function (f) {
                if (f == null) {
                    return agg[name].significant_terms.format;
                }

                agg[name].significant_terms.format = f;
                return this;
            },

            /**
            <p>Allows you to allow only specific entries using a regular
            expression.  You can also optionally pass in a set of flags to apply
            to the regular expression.  Valid flags are: CASE_INSENSITIVE,
            MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL,
            COMMENTS, and UNICODE_CHAR_CLASS.  Separate multiple flags with a |
            character.</p>
      
            @member ejs.SignificantTermsAggregation
            @param {String} include A regular expression include string
            @param {String} flags Optional regular expression flags..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            include: function (include, flags) {
                if (agg[name].significant_terms.include == null) {
                    agg[name].significant_terms.include = {};
                }

                if (include == null) {
                    return agg[name].significant_terms.include;
                }

                agg[name].significant_terms.include.pattern = include;
                if (flags != null) {
                    agg[name].significant_terms.include.flags = flags;
                }

                return this;
            },

            /**
            <p>Allows you to filter out unwanted facet entries using a regular
            expression.  You can also optionally pass in a set of flags to apply
            to the regular expression.  Valid flags are: CASE_INSENSITIVE,
            MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL,
            COMMENTS, and UNICODE_CHAR_CLASS.  Separate multiple flags with a |
            character.</p>
      
            @member ejs.SignificantTermsAggregation
            @param {String} exclude A regular expression exclude string
            @param {String} flags Optional regular expression flags..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            exclude: function (exclude, flags) {
                if (agg[name].significant_terms.exclude == null) {
                    agg[name].significant_terms.exclude = {};
                }

                if (exclude == null) {
                    return agg[name].significant_terms.exclude;
                }

                agg[name].significant_terms.exclude.pattern = exclude;
                if (flags != null) {
                    agg[name].significant_terms.exclude.flags = flags;
                }

                return this;
            },

            /**
            Sets the execution hint determines how the aggregation is computed.
            Supported values are: map and ordinals.
      
            @member ejs.SignificantTermsAggregation
            @param {String} h The hint value as a string.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            executionHint: function (h) {
                if (h == null) {
                    return agg[name].significant_terms.execution_hint;
                }

                h = h.toLowerCase();
                if (h === 'map' || h === 'ordinals') {
                    agg[name].significant_terms.execution_hint = h;
                }

                return this;
            },

            /**
            Sets the number of aggregation entries that will be returned.
      
            @member ejs.SignificantTermsAggregation
            @param {Integer} size The numer of aggregation entries to be returned.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            size: function (size) {
                if (size == null) {
                    return agg[name].significant_terms.size;
                }

                agg[name].significant_terms.size = size;
                return this;
            },


            /**
            Determines how many terms the coordinating node will request from
            each shard.
      
            @member ejs.SignificantTermsAggregation
            @param {Integer} shardSize The numer of terms to fetch from each shard.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            shardSize: function (shardSize) {
                if (shardSize == null) {
                    return agg[name].significant_terms.shard_size;
                }

                agg[name].significant_terms.shard_size = shardSize;
                return this;
            },

            /**
            Only return terms that match more than a configured number of hits.
      
            @member ejs.SignificantTermsAggregation
            @param {Integer} num The numer of minimum number of hits.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            minDocCount: function (num) {
                if (num == null) {
                    return agg[name].significant_terms.min_doc_count;
                }

                agg[name].significant_terms.min_doc_count = num;
                return this;
            }

        });
    };

    /**
      @class
      <p>A multi-value metrics aggregation that computes stats over numeric values
      extracted from the aggregated documents. These values can be extracted either
      from specific numeric fields in the documents, or be generated by a provided
      script.</p>
  
      <p>The stats that are returned consist of: min, max, sum, count and avg.</p>
  
      @name ejs.StatsAggregation
      @ejs aggregation
      @borrows ejs.MetricsAggregationMixin.field as field
      @borrows ejs.MetricsAggregationMixin.script as script
      @borrows ejs.MetricsAggregationMixin.lang as lang
      @borrows ejs.MetricsAggregationMixin.scriptValuesSorted as scriptValuesSorted
      @borrows ejs.MetricsAggregationMixin.params as params
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that computes stats over numeric values extracted from the
      aggregated documents.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.StatsAggregation = function (name) {

        var
          _common = ejs.MetricsAggregationMixin(name, 'stats'),
          agg = _common.toJSON();

        return _common;
    };

    /**
      @class
      <p>A single-value metrics aggregation that sums up numeric values that are
      extracted from the aggregated documents. These values can be extracted either
      from specific numeric fields in the documents, or be generated by a
      provided script.</p>
  
      @name ejs.SumAggregation
      @ejs aggregation
      @borrows ejs.MetricsAggregationMixin.field as field
      @borrows ejs.MetricsAggregationMixin.script as script
      @borrows ejs.MetricsAggregationMixin.lang as lang
      @borrows ejs.MetricsAggregationMixin.scriptValuesSorted as scriptValuesSorted
      @borrows ejs.MetricsAggregationMixin.params as params
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that sums up numeric values that are extracted from the
      aggregated documents.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.SumAggregation = function (name) {

        var
          _common = ejs.MetricsAggregationMixin(name, 'sum'),
          agg = _common.toJSON();

        return _common;
    };

    /**
      @class
      <p>A multi-bucket value source based aggregation where buckets are dynamically
      built - one per unique value.</p>
  
      @name ejs.TermsAggregation
      @ejs aggregation
      @borrows ejs.AggregationMixin.aggregation as aggregation
      @borrows ejs.AggregationMixin.agg as agg
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Defines an aggregation of unique values/terms.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.TermsAggregation = function (name) {

        var
          _common = ejs.AggregationMixin(name),
          agg = _common.toJSON();

        agg[name].terms = {};

        return extend(_common, {

            /**
            <p>Sets the field to gather terms from.</p>
      
            @member ejs.TermsAggregation
            @param {String} field a valid field name..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (field) {
                if (field == null) {
                    return agg[name].terms.field;
                }

                agg[name].terms.field = field;
                return this;
            },

            /**
            Allows you generate or modify the terms using a script.
      
            @member ejs.TermsAggregation
            @param {String} scriptCode A valid script string to execute.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            script: function (scriptCode) {
                if (scriptCode == null) {
                    return agg[name].terms.script;
                }

                agg[name].terms.script = scriptCode;
                return this;
            },

            /**
            The script language being used.
      
            @member ejs.TermsAggregation
            @param {String} language The language of the script.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            lang: function (language) {
                if (language == null) {
                    return agg[name].terms.lang;
                }

                agg[name].terms.lang = language;
                return this;
            },

            /**
            Sets the type of the field value for use in scripts.  Current values are:
            string, double, float, long, integer, short, and byte.
      
            @member ejs.TermsAggregation
            @param {String} v The value type
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            valueType: function (v) {
                if (v == null) {
                    return agg[name].terms.value_type;
                }

                v = v.toLowerCase();
                if (v === 'string' || v === 'double' || v === 'float' || v === 'long' ||
                    v === 'integer' || v === 'short' || v === 'byte') {
                    agg[name].terms.value_type = v;
                }

                return this;
            },

            /**
            Sets the format expression for the terms.  Use for number or date
            formatting
      
            @member ejs.TermsAggregation
            @param {String} f the format string
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            format: function (f) {
                if (f == null) {
                    return agg[name].terms.format;
                }

                agg[name].terms.format = f;
                return this;
            },

            /**
            <p>Allows you to allow only specific entries using a regular
            expression.  You can also optionally pass in a set of flags to apply
            to the regular expression.  Valid flags are: CASE_INSENSITIVE,
            MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL,
            COMMENTS, and UNICODE_CHAR_CLASS.  Separate multiple flags with a |
            character.</p>
      
            @member ejs.TermsAggregation
            @param {String} include A regular expression include string
            @param {String} flags Optional regular expression flags..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            include: function (include, flags) {
                if (agg[name].terms.include == null) {
                    agg[name].terms.include = {};
                }

                if (include == null) {
                    return agg[name].terms.include;
                }

                agg[name].terms.include.pattern = include;
                if (flags != null) {
                    agg[name].terms.include.flags = flags;
                }

                return this;
            },

            /**
            <p>Allows you to filter out unwanted facet entries using a regular
            expression.  You can also optionally pass in a set of flags to apply
            to the regular expression.  Valid flags are: CASE_INSENSITIVE,
            MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL,
            COMMENTS, and UNICODE_CHAR_CLASS.  Separate multiple flags with a |
            character.</p>
      
            @member ejs.TermsAggregation
            @param {String} exclude A regular expression exclude string
            @param {String} flags Optional regular expression flags..
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            exclude: function (exclude, flags) {
                if (agg[name].terms.exclude == null) {
                    agg[name].terms.exclude = {};
                }

                if (exclude == null) {
                    return agg[name].terms.exclude;
                }

                agg[name].terms.exclude.pattern = exclude;
                if (flags != null) {
                    agg[name].terms.exclude.flags = flags;
                }

                return this;
            },

            /**
            Sets the execution hint determines how the aggregation is computed.
            Supported values are: map and ordinals.
      
            @member ejs.TermsAggregation
            @param {String} h The hint value as a string.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            executionHint: function (h) {
                if (h == null) {
                    return agg[name].terms.execution_hint;
                }

                h = h.toLowerCase();
                if (h === 'map' || h === 'ordinals') {
                    agg[name].terms.execution_hint = h;
                }

                return this;
            },

            /**
            Set to true to assume script values are unique.
      
            @member ejs.TermsAggregation
            @param {Boolean} trueFalse assume unique values or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            scriptValuesUnique: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].terms.script_values_unique;
                }

                agg[name].terms.script_values_unique = trueFalse;
                return this;
            },

            /**
            Sets the number of aggregation entries that will be returned.
      
            @member ejs.TermsAggregation
            @param {Integer} size The numer of aggregation entries to be returned.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            size: function (size) {
                if (size == null) {
                    return agg[name].terms.size;
                }

                agg[name].terms.size = size;
                return this;
            },


            /**
            Determines how many terms the coordinating node will request from
            each shard.
      
            @member ejs.TermsAggregation
            @param {Integer} shardSize The numer of terms to fetch from each shard.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            shardSize: function (shardSize) {
                if (shardSize == null) {
                    return agg[name].terms.shard_size;
                }

                agg[name].terms.shard_size = shardSize;
                return this;
            },

            /**
            Only return terms that match more than a configured number of hits.
      
            @member ejs.TermsAggregation
            @param {Integer} num The numer of minimum number of hits.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            minDocCount: function (num) {
                if (num == null) {
                    return agg[name].terms.min_doc_count;
                }

                agg[name].terms.min_doc_count = num;
                return this;
            },

            /**
            Sets parameters that will be applied to the script.  Overwrites
            any existing params.
      
            @member ejs.TermsAggregation
            @param {Object} p An object where the keys are the parameter name and
              values are the parameter value.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            params: function (p) {
                if (p == null) {
                    return agg[name].terms.params;
                }

                agg[name].terms.params = p;
                return this;
            },

            /**
            Sets order for the aggregated values.
      
            @member ejs.TermsAggregation
            @param {String} order The order string.
            @param {String} direction The sort direction, asc or desc.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            order: function (order, direction) {
                if (order == null) {
                    return agg[name].terms.order;
                }

                if (direction == null) {
                    direction = 'desc';
                }

                direction = direction.toLowerCase();
                if (direction !== 'asc' && direction !== 'desc') {
                    direction = 'desc';
                }

                agg[name].terms.order = {};
                agg[name].terms.order[order] = direction;
                return this;
            }

        });
    };

    /**
      @class
      <p>A single-value metrics aggregation that counts the number of values that
      are extracted from the aggregated documents. These values can be extracted
      either from specific fields in the documents, or be generated by a provided
      script. Typically, this aggregator will be used in conjunction with other
      single-value aggregations.</p>
  
      @name ejs.ValueCountAggregation
      @ejs aggregation
      @borrows ejs.MetricsAggregationMixin.field as field
      @borrows ejs.MetricsAggregationMixin.script as script
      @borrows ejs.MetricsAggregationMixin.lang as lang
      @borrows ejs.MetricsAggregationMixin.params as params
      @borrows ejs.AggregationMixin._type as _type
      @borrows ejs.AggregationMixin.toJSON as toJSON
  
      @desc
      <p>Aggregation that counts the number of values that are extracted from the
      aggregated documents.</p>
  
      @param {String} name The name which be used to refer to this aggregation.
  
      */
    ejs.ValueCountAggregation = function (name) {

        var
          _common = ejs.MetricsAggregationMixin(name, 'value_count'),
          agg = _common.toJSON();

        // not supported in value count aggregation
        delete _common.scriptValuesSorted;

        return extend(_common, {

            /**
            Set to true to assume script values are unique.
      
            @member ejs.ValueCountAggregation
            @param {Boolean} trueFalse assume unique values or not
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            scriptValuesUnique: function (trueFalse) {
                if (trueFalse == null) {
                    return agg[name].value_count.script_values_unique;
                }

                agg[name].value_count.script_values_unique = trueFalse;
                return this;
            }

        });

    };

    /**
      @class
      A container Filter that allows Boolean AND composition of Filters.
  
      @name ejs.AndFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      A container Filter that allows Boolean AND composition of Filters.
  
      @param {(Filter|Filter[])} f A single Filter object or an array of valid 
        Filter objects.
      */
    ejs.AndFilter = function (f) {

        var
          i,
          len,
          _common = ejs.FilterMixin('and'),
          filter = _common.toJSON();

        filter.and.filters = [];

        if (isFilter(f)) {
            filter.and.filters.push(f.toJSON());
        } else if (isArray(f)) {
            for (i = 0, len = f.length; i < len; i++) {
                if (!isFilter(f[i])) {
                    throw new TypeError('Array must contain only Filter objects');
                }

                filter.and.filters.push(f[i].toJSON());
            }
        } else {
            throw new TypeError('Argument must be a Filter or Array of Filters');
        }

        return extend(_common, {

            /**
                   Sets the filters for the filter.  If fltr is a single 
                   Filter, it is added to the current filters.  If fltr is an array
                   of Filters, then they replace all existing filters.
      
                   @member ejs.AndFilter
                   @param {(Filter|Filter[])} fltr A valid filter object or an array of filters.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            filters: function (fltr) {
                var i,
                  len;

                if (fltr == null) {
                    return filter.and.filters;
                }

                if (isFilter(fltr)) {
                    filter.and.filters.push(fltr.toJSON());
                } else if (isArray(fltr)) {
                    filter.and.filters = [];
                    for (i = 0, len = fltr.length; i < len; i++) {
                        if (!isFilter(fltr[i])) {
                            throw new TypeError('Array must contain only Filter objects');
                        }

                        filter.and.filters.push(fltr[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be a Filter or an Array of Filters');
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>A <code>BoolFilter</code> allows you to build <em>Boolean</em> filter constructs
      from individual filters. Similar in concept to Boolean query, except that 
      the clauses are other filters. Can be placed within queries that accept a 
      filter.
    
      @name ejs.BoolFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      A Filter that matches documents matching boolean combinations of other
      filters.
  
      */
    ejs.BoolFilter = function () {

        var
          _common = ejs.FilterMixin('bool'),
          filter = _common.toJSON();

        return extend(_common, {

            /**
                   Adds filter to boolean container. Given filter "must" appear in 
                   matching documents.  If passed a single Filter it is added to the
                   list of existing filters.  If passed an array of Filters, they
                   replace all existing filters.
      
                   @member ejs.BoolFilter
                   @param {(Filter|Filter[])} oFilter A valid Filter or array of
                    Filter objects.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            must: function (oFilter) {
                var i, len;

                if (filter.bool.must == null) {
                    filter.bool.must = [];
                }

                if (oFilter == null) {
                    return filter.bool.must;
                }

                if (isFilter(oFilter)) {
                    filter.bool.must.push(oFilter.toJSON());
                } else if (isArray(oFilter)) {
                    filter.bool.must = [];
                    for (i = 0, len = oFilter.length; i < len; i++) {
                        if (!isFilter(oFilter[i])) {
                            throw new TypeError('Argument must be an array of Filters');
                        }

                        filter.bool.must.push(oFilter[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be a Filter or array of Filters');
                }

                return this;
            },

            /**
                   Adds filter to boolean container. Given filter "must not" appear 
                   in matching documents. If passed a single Filter it is added to 
                   the list of existing filters.  If passed an array of Filters, 
                   they replace all existing filters.
      
                   @member ejs.BoolFilter
                   @param {(Filter|Filter[])} oFilter A valid Filter or array of
                     Filter objects.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            mustNot: function (oFilter) {
                var i, len;

                if (filter.bool.must_not == null) {
                    filter.bool.must_not = [];
                }

                if (oFilter == null) {
                    return filter.bool.must_not;
                }

                if (isFilter(oFilter)) {
                    filter.bool.must_not.push(oFilter.toJSON());
                } else if (isArray(oFilter)) {
                    filter.bool.must_not = [];
                    for (i = 0, len = oFilter.length; i < len; i++) {
                        if (!isFilter(oFilter[i])) {
                            throw new TypeError('Argument must be an array of Filters');
                        }

                        filter.bool.must_not.push(oFilter[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be a Filter or array of Filters');
                }

                return this;
            },

            /**
                   Adds filter to boolean container. Given filter "should" appear in 
                   matching documents. If passed a single Filter it is added to 
                   the list of existing filters.  If passed an array of Filters, 
                   they replace all existing filters.
      
                   @member ejs.BoolFilter
                   @param {(Filter|Filter[])} oFilter A valid Filter or array of
                      Filter objects.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            should: function (oFilter) {
                var i, len;

                if (filter.bool.should == null) {
                    filter.bool.should = [];
                }

                if (oFilter == null) {
                    return filter.bool.should;
                }

                if (isFilter(oFilter)) {
                    filter.bool.should.push(oFilter.toJSON());
                } else if (isArray(oFilter)) {
                    filter.bool.should = [];
                    for (i = 0, len = oFilter.length; i < len; i++) {
                        if (!isFilter(oFilter[i])) {
                            throw new TypeError('Argument must be an array of Filters');
                        }

                        filter.bool.should.push(oFilter[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be a Filter or array of Filters');
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>An existsFilter matches documents where the specified field is present
      and the field contains a legitimate value.</p>
  
      @name ejs.ExistsFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Filters documents where a specified field exists and contains a value.
  
      @param {String} fieldName the field name that must exists and contain a value.
      */
    ejs.ExistsFilter = function (fieldName) {

        var
          _common = ejs.FilterMixin('exists'),
          filter = _common.toJSON();

        filter.exists.field = fieldName;

        return extend(_common, {

            /**
                  Sets the field to check for missing values.
      
                  @member ejs.ExistsFilter
                  @param {String} name A name of the field.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (name) {
                if (name == null) {
                    return filter.exists.field;
                }

                filter.exists.field = name;
                return this;
            }

        });
    };

    /**
      @class
      <p>A filter that restricts matched results/docs to a geographic bounding box described by
      the specified lon and lat coordinates. The format conforms with the GeoJSON specification.</p>
  
      @name ejs.GeoBboxFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Filter results to those which are contained within the defined bounding box.
  
      @param {String} fieldName the document property/field containing the Geo Point (lon/lat).
  
      */
    ejs.GeoBboxFilter = function (fieldName) {

        var
          _common = ejs.FilterMixin('geo_bounding_box'),
          filter = _common.toJSON();

        filter.geo_bounding_box[fieldName] = {};

        return extend(_common, {

            /**
                  Sets the fields to filter against.
      
                  @member ejs.GeoBboxFilter
                  @param {String} f A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                var oldValue = filter.geo_bounding_box[fieldName];

                if (f == null) {
                    return fieldName;
                }

                delete filter.geo_bounding_box[fieldName];
                fieldName = f;
                filter.geo_bounding_box[f] = oldValue;

                return this;
            },

            /**
                   Sets the top-left coordinate of the bounding box
      
                   @member ejs.GeoBboxFilter
                   @param {GeoPoint} p A valid GeoPoint object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            topLeft: function (p) {
                if (p == null) {
                    return filter.geo_bounding_box[fieldName].top_left;
                }

                if (isGeoPoint(p)) {
                    filter.geo_bounding_box[fieldName].top_left = p.toJSON();
                } else {
                    throw new TypeError('Argument must be a GeoPoint');
                }

                return this;
            },

            /**
                   Sets the bottom-right coordinate of the bounding box
      
                   @member ejs.GeoBboxFilter
                   @param {GeoPoint} p A valid GeoPoint object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            bottomRight: function (p) {
                if (p == null) {
                    return filter.geo_bounding_box[fieldName].bottom_right;
                }

                if (isGeoPoint(p)) {
                    filter.geo_bounding_box[fieldName].bottom_right = p.toJSON();
                } else {
                    throw new TypeError('Argument must be a GeoPoint');
                }

                return this;
            },

            /**
                  Sets the type of the bounding box execution. Valid values are
                  "memory" and "indexed".  Default is memory.
      
                  @member ejs.GeoBboxFilter
                  @param {String} type The execution type as a string.  
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (type) {
                if (type == null) {
                    return filter.geo_bounding_box.type;
                }

                type = type.toLowerCase();
                if (type === 'memory' || type === 'indexed') {
                    filter.geo_bounding_box.type = type;
                }

                return this;
            },

            /**
                  If the lat/long points should be normalized to lie within their
                  respective normalized ranges.
                  
                  Normalized ranges are:
                  lon = -180 (exclusive) to 180 (inclusive) range
                  lat = -90 to 90 (both inclusive) range
      
                  @member ejs.GeoBboxFilter
                  @param {String} trueFalse True if the coordinates should be normalized. False otherwise.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            normalize: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.geo_bounding_box.normalize;
                }

                filter.geo_bounding_box.normalize = trueFalse;
                return this;
            }

        });
    };

    /**
      @class
      <p>A filter that restricts matched results/docs to a given distance from the
      point of origin. The format conforms with the GeoJSON specification.</p>
  
      @name ejs.GeoDistanceFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Filter results to those which fall within the given distance of the point of origin.
  
      @param {String} fieldName the document property/field containing the Geo Point (lon/lat).
  
      */
    ejs.GeoDistanceFilter = function (fieldName) {

        var
          _common = ejs.FilterMixin('geo_distance'),
          filter = _common.toJSON();

        filter.geo_distance[fieldName] = [0, 0];

        return extend(_common, {

            /**
                  Sets the fields to filter against.
      
                  @member ejs.GeoDistanceFilter
                  @param {String} f A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                var oldValue = filter.geo_distance[fieldName];

                if (f == null) {
                    return fieldName;
                }

                delete filter.geo_distance[fieldName];
                fieldName = f;
                filter.geo_distance[f] = oldValue;

                return this;
            },

            /**
                   Sets the numeric distance to be used.  The distance can be a 
                   numeric value, and then the unit (either mi or km can be set) 
                   controlling the unit. Or a single string with the unit as well.
      
                   @member ejs.GeoDistanceFilter
                   @param {Number} numericDistance the numeric distance
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            distance: function (numericDistance) {
                if (numericDistance == null) {
                    return filter.geo_distance.distance;
                }

                if (!isNumber(numericDistance)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.geo_distance.distance = numericDistance;
                return this;
            },

            /**
                   Sets the distance unit.  Valid values are "mi" for miles or "km"
                   for kilometers. Defaults to "km".
      
                   @member ejs.GeoDistanceFilter
                   @param {Number} unit the unit of distance measure.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            unit: function (unit) {
                if (unit == null) {
                    return filter.geo_distance.unit;
                }

                unit = unit.toLowerCase();
                if (unit === 'mi' || unit === 'km') {
                    filter.geo_distance.unit = unit;
                }

                return this;
            },

            /**
                   Sets the point of origin in which distance will be measured from
      
                   @member ejs.GeoDistanceFilter
                   @param {GeoPoint} p A valid GeoPoint object.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            point: function (p) {
                if (p == null) {
                    return filter.geo_distance[fieldName];
                }

                if (isGeoPoint(p)) {
                    filter.geo_distance[fieldName] = p.toJSON();
                } else {
                    throw new TypeError('Argument must be a GeoPoint');
                }

                return this;
            },


            /**
                  How to compute the distance. Can either be arc (better precision) 
                  or plane (faster). Defaults to arc.
      
                  @member ejs.GeoDistanceFilter
                  @param {String} type The execution type as a string.  
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            distanceType: function (type) {
                if (type == null) {
                    return filter.geo_distance.distance_type;
                }

                type = type.toLowerCase();
                if (type === 'arc' || type === 'plane') {
                    filter.geo_distance.distance_type = type;
                }

                return this;
            },

            /**
                  If the lat/long points should be normalized to lie within their
                  respective normalized ranges.
                  
                  Normalized ranges are:
                  lon = -180 (exclusive) to 180 (inclusive) range
                  lat = -90 to 90 (both inclusive) range
      
                  @member ejs.GeoDistanceFilter
                  @param {String} trueFalse True if the coordinates should be normalized. False otherwise.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            normalize: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.geo_distance.normalize;
                }

                filter.geo_distance.normalize = trueFalse;
                return this;
            },

            /**
                  Will an optimization of using first a bounding box check will be 
                  used. Defaults to memory which will do in memory checks. Can also 
                  have values of indexed to use indexed value check, or none which 
                  disables bounding box optimization.
      
                  @member ejs.GeoDistanceFilter
                  @param {String} t optimization type of memory, indexed, or none.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            optimizeBbox: function (t) {
                if (t == null) {
                    return filter.geo_distance.optimize_bbox;
                }

                t = t.toLowerCase();
                if (t === 'memory' || t === 'indexed' || t === 'none') {
                    filter.geo_distance.optimize_bbox = t;
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>A filter that restricts matched results/docs to a given distance range from the
      point of origin. The format conforms with the GeoJSON specification.</p>
  
      @name ejs.GeoDistanceRangeFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Filter results to those which fall within the given distance range of the point of origin.
  
      @param {String} fieldName the document property/field containing the Geo Point (lon/lat).
  
      */
    ejs.GeoDistanceRangeFilter = function (fieldName) {

        var
          _common = ejs.FilterMixin('geo_distance_range'),
          filter = _common.toJSON();

        filter.geo_distance_range[fieldName] = [0, 0];

        return extend(_common, {

            /**
                   Sets the fields to filter against.
       
                   @member ejs.GeoDistanceRangeFilter
                   @param {String} f A valid field name.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            field: function (f) {
                var oldValue = filter.geo_distance_range[fieldName];

                if (f == null) {
                    return fieldName;
                }

                delete filter.geo_distance_range[fieldName];
                fieldName = f;
                filter.geo_distance_range[f] = oldValue;

                return this;
            },

            /**
                   * Sets the start point of the distance range
      
                   @member ejs.GeoDistanceRangeFilter
                   @param {Number} numericDistance the numeric distance
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            from: function (numericDistance) {
                if (numericDistance == null) {
                    return filter.geo_distance_range.from;
                }

                if (!isNumber(numericDistance)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.geo_distance_range.from = numericDistance;
                return this;
            },

            /**
                   * Sets the end point of the distance range
      
                   @member ejs.GeoDistanceRangeFilter
                   @param {Number} numericDistance the numeric distance
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            to: function (numericDistance) {
                if (numericDistance == null) {
                    return filter.geo_distance_range.to;
                }

                if (!isNumber(numericDistance)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.geo_distance_range.to = numericDistance;
                return this;
            },

            /**
                  Should the first from (if set) be inclusive or not. 
                  Defaults to true
      
                  @member ejs.GeoDistanceRangeFilter
                  @param {Boolean} trueFalse true to include, false to exclude 
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            includeLower: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.geo_distance_range.include_lower;
                }

                filter.geo_distance_range.include_lower = trueFalse;
                return this;
            },

            /**
                  Should the last to (if set) be inclusive or not. Defaults to true.
      
                  @member ejs.GeoDistanceRangeFilter
                  @param {Boolean} trueFalse true to include, false to exclude 
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            includeUpper: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.geo_distance_range.include_upper;
                }

                filter.geo_distance_range.include_upper = trueFalse;
                return this;
            },

            /**
                  Greater than value.  Same as setting from to the value, and 
                  include_lower to false,
      
                  @member ejs.GeoDistanceRangeFilter
                  @param {Number} val the numeric distance
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            gt: function (val) {
                if (val == null) {
                    return filter.geo_distance_range.gt;
                }

                if (!isNumber(val)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.geo_distance_range.gt = val;
                return this;
            },

            /**
                  Greater than or equal to value.  Same as setting from to the value,
                  and include_lower to true.
      
                  @member ejs.GeoDistanceRangeFilter
                  @param {Number} val the numeric distance
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            gte: function (val) {
                if (val == null) {
                    return filter.geo_distance_range.gte;
                }

                if (!isNumber(val)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.geo_distance_range.gte = val;
                return this;
            },

            /**
                  Less than value.  Same as setting to to the value, and include_upper 
                  to false.
      
                  @member ejs.GeoDistanceRangeFilter
                  @param {Number} val the numeric distance
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lt: function (val) {
                if (val == null) {
                    return filter.geo_distance_range.lt;
                }

                if (!isNumber(val)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.geo_distance_range.lt = val;
                return this;
            },

            /**
                  Less than or equal to value.  Same as setting to to the value, 
                  and include_upper to true.
      
                  @member ejs.GeoDistanceRangeFilter
                  @param {Number} val the numeric distance
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lte: function (val) {
                if (val == null) {
                    return filter.geo_distance_range.lte;
                }

                if (!isNumber(val)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.geo_distance_range.lte = val;
                return this;
            },

            /**
                   Sets the distance unit.  Valid values are "mi" for miles or "km"
                   for kilometers. Defaults to "km".
      
                   @member ejs.GeoDistanceRangeFilter
                   @param {Number} unit the unit of distance measure.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            unit: function (unit) {
                if (unit == null) {
                    return filter.geo_distance_range.unit;
                }

                unit = unit.toLowerCase();
                if (unit === 'mi' || unit === 'km') {
                    filter.geo_distance_range.unit = unit;
                }

                return this;
            },

            /**
                   Sets the point of origin in which distance will be measured from
      
                   @member ejs.GeoDistanceRangeFilter
                   @param {GeoPoint} p A valid GeoPoint object.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            point: function (p) {
                if (p == null) {
                    return filter.geo_distance_range[fieldName];
                }

                if (isGeoPoint(p)) {
                    filter.geo_distance_range[fieldName] = p.toJSON();
                } else {
                    throw new TypeError('Argument must be a GeoPoint');
                }

                return this;
            },


            /**
                  How to compute the distance. Can either be arc (better precision) 
                  or plane (faster). Defaults to arc.
      
                  @member ejs.GeoDistanceRangeFilter
                  @param {String} type The execution type as a string.  
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            distanceType: function (type) {
                if (type == null) {
                    return filter.geo_distance_range.distance_type;
                }

                type = type.toLowerCase();
                if (type === 'arc' || type === 'plane') {
                    filter.geo_distance_range.distance_type = type;
                }

                return this;
            },

            /**
                  If the lat/long points should be normalized to lie within their
                  respective normalized ranges.
                  
                  Normalized ranges are:
                  lon = -180 (exclusive) to 180 (inclusive) range
                  lat = -90 to 90 (both inclusive) range
      
                  @member ejs.GeoDistanceRangeFilter
                  @param {String} trueFalse True if the coordinates should be normalized. False otherwise.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            normalize: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.geo_distance_range.normalize;
                }

                filter.geo_distance_range.normalize = trueFalse;
                return this;
            },

            /**
                  Will an optimization of using first a bounding box check will be 
                  used. Defaults to memory which will do in memory checks. Can also 
                  have values of indexed to use indexed value check, or none which 
                  disables bounding box optimization.
      
                  @member ejs.GeoDistanceRangeFilter
                  @param {String} t optimization type of memory, indexed, or none.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            optimizeBbox: function (t) {
                if (t == null) {
                    return filter.geo_distance_range.optimize_bbox;
                }

                t = t.toLowerCase();
                if (t === 'memory' || t === 'indexed' || t === 'none') {
                    filter.geo_distance_range.optimize_bbox = t;
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>A filter for locating documents that fall within a polygon of points. Simply provide a lon/lat
      for each document as a Geo Point type. The format conforms with the GeoJSON specification.</p>
  
      @name ejs.GeoPolygonFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Filter results to those which are contained within the polygon of points.
  
      @param {String} fieldName the document property/field containing the Geo Point (lon/lat).
      */
    ejs.GeoPolygonFilter = function (fieldName) {

        var
          _common = ejs.FilterMixin('geo_polygon'),
          filter = _common.toJSON();

        filter.geo_polygon[fieldName] = {
            points: []
        };

        return extend(_common, {

            /**
                 Sets the fields to filter against.
      
                 @member ejs.GeoPolygonFilter
                 @param {String} f A valid field name.
                 @returns {Object} returns <code>this</code> so that calls can be chained.
                 */
            field: function (f) {
                var oldValue = filter.geo_polygon[fieldName];

                if (f == null) {
                    return fieldName;
                }

                delete filter.geo_polygon[fieldName];
                fieldName = f;
                filter.geo_polygon[f] = oldValue;

                return this;
            },

            /**
                   Sets a series of points that represent a polygon.  If passed a 
                   single <code>GeoPoint</code> object, it is added to the current 
                   list of points.  If passed an array of <code>GeoPoint</code> 
                   objects it replaces all current values. 
      
                   @member ejs.GeoPolygonFilter
                   @param {Array} pointsArray the array of points that represent the polygon
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            points: function (p) {
                var i, len;

                if (p == null) {
                    return filter.geo_polygon[fieldName].points;
                }

                if (isGeoPoint(p)) {
                    filter.geo_polygon[fieldName].points.push(p.toJSON());
                } else if (isArray(p)) {
                    filter.geo_polygon[fieldName].points = [];
                    for (i = 0, len = p.length; i < len; i++) {
                        if (!isGeoPoint(p[i])) {
                            throw new TypeError('Argument must be Array of GeoPoints');
                        }

                        filter.geo_polygon[fieldName].points.push(p[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be a GeoPoint or Array of GeoPoints');
                }

                return this;
            },

            /**
                  If the lat/long points should be normalized to lie within their
                  respective normalized ranges.
                  
                  Normalized ranges are:
                  lon = -180 (exclusive) to 180 (inclusive) range
                  lat = -90 to 90 (both inclusive) range
      
                  @member ejs.GeoPolygonFilter
                  @param {String} trueFalse True if the coordinates should be normalized. False otherwise.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            normalize: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.geo_polygon.normalize;
                }

                filter.geo_polygon.normalize = trueFalse;
                return this;
            }

        });
    };

    /**
      @class
      <p>Efficient filtering of documents containing shapes indexed using the 
      geo_shape type.</p>
  
      <p>Much like the geo_shape type, the geo_shape filter uses a grid square 
      representation of the filter shape to find those documents which have shapes 
      that relate to the filter shape in a specified way. In order to do this, the 
      field being queried must be of geo_shape type. The filter will use the same 
      PrefixTree configuration as defined for the field.</p>
  
      @name ejs.GeoShapeFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      A Filter to find documents with a geo_shapes matching a specific shape.
  
      */
    ejs.GeoShapeFilter = function (field) {

        var
          _common = ejs.FilterMixin('geo_shape'),
          filter = _common.toJSON();

        filter.geo_shape[field] = {};

        return extend(_common, {

            /**
                  Sets the field to filter against.
      
                  @member ejs.GeoShapeFilter
                  @param {String} f A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                var oldValue = filter.geo_shape[field];

                if (f == null) {
                    return field;
                }

                delete filter.geo_shape[field];
                field = f;
                filter.geo_shape[f] = oldValue;

                return this;
            },

            /**
                  Sets the shape
      
                  @member ejs.GeoShapeFilter
                  @param {String} shape A valid <code>Shape</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            shape: function (shape) {
                if (shape == null) {
                    return filter.geo_shape[field].shape;
                }

                if (filter.geo_shape[field].indexed_shape != null) {
                    delete filter.geo_shape[field].indexed_shape;
                }

                filter.geo_shape[field].shape = shape.toJSON();
                return this;
            },

            /**
                  Sets the indexed shape.  Use this if you already have shape definitions
                  already indexed.
      
                  @member ejs.GeoShapeFilter
                  @param {String} indexedShape A valid <code>IndexedShape</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            indexedShape: function (indexedShape) {
                if (indexedShape == null) {
                    return filter.geo_shape[field].indexed_shape;
                }

                if (filter.geo_shape[field].shape != null) {
                    delete filter.geo_shape[field].shape;
                }

                filter.geo_shape[field].indexed_shape = indexedShape.toJSON();
                return this;
            },

            /**
                  Sets the shape relation type.  A relationship between a Query Shape 
                  and indexed Shapes that will be used to determine if a Document 
                  should be matched or not.  Valid values are:  intersects, disjoint,
                  and within.
      
                  @member ejs.GeoShapeFilter
                  @param {String} indexedShape A valid <code>IndexedShape</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            relation: function (relation) {
                if (relation == null) {
                    return filter.geo_shape[field].relation;
                }

                relation = relation.toLowerCase();
                if (relation === 'intersects' || relation === 'disjoint' || relation === 'within') {
                    filter.geo_shape[field].relation = relation;
                }

                return this;
            },

            /**
                  <p>Sets the spatial strategy.</p>  
                  <p>Valid values are:</p>
                  
                  <dl>
                      <dd><code>recursive</code> - default, recursively traverse nodes in
                        the spatial prefix tree.  This strategy has support for 
                        searching non-point shapes.</dd>
                      <dd><code>term</code> - uses a large TermsFilter on each node
                        in the spatial prefix tree.  It only supports the search of 
                        indexed Point shapes.</dd>
                  </dl>
      
                  <p>This is an advanced setting, use with care.</p>
                  
                  @since elasticsearch 0.90
                  @member ejs.GeoShapeFilter
                  @param {String} strategy The strategy as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            strategy: function (strategy) {
                if (strategy == null) {
                    return filter.geo_shape[field].strategy;
                }

                strategy = strategy.toLowerCase();
                if (strategy === 'recursive' || strategy === 'term') {
                    filter.geo_shape[field].strategy = strategy;
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>The has_child filter results in parent documents that have child docs 
      matching the query being returned.</p>
  
      @name ejs.HasChildFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Returns results that have child documents matching the filter.
  
      @param {Object} qry A valid query object.
      @param {String} type The child type
      */
    ejs.HasChildFilter = function (qry, type) {

        if (!isQuery(qry)) {
            throw new TypeError('No Query object found');
        }

        var
          _common = ejs.FilterMixin('has_child'),
          filter = _common.toJSON();

        filter.has_child.query = qry.toJSON();
        filter.has_child.type = type;

        return extend(_common, {

            /**
                  Sets the query
      
                  @member ejs.HasChildFilter
                  @param {Query} q A valid Query object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (q) {
                if (q == null) {
                    return filter.has_child.query;
                }

                if (!isQuery(q)) {
                    throw new TypeError('Argument must be a Query object');
                }

                filter.has_child.query = q.toJSON();
                return this;
            },

            /**
                  Sets the filter
      
                  @since elasticsearch 0.90
                  @member ejs.HasChildFilter
                  @param {Query} f A valid Filter object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            filter: function (f) {
                if (f == null) {
                    return filter.has_child.filter;
                }

                if (!isFilter(f)) {
                    throw new TypeError('Argument must be a Filter object');
                }

                filter.has_child.filter = f.toJSON();
                return this;
            },

            /**
                  Sets the child document type to search against
      
                  @member ejs.HasChildFilter
                  @param {String} t A valid type name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (t) {
                if (t == null) {
                    return filter.has_child.type;
                }

                filter.has_child.type = t;
                return this;
            },

            /**
                  Sets the cutoff value to short circuit processing.
      
                  @member ejs.HasChildFilter
                  @param {Integer} cutoff A positive <code>integer</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            shortCircuitCutoff: function (cutoff) {
                if (cutoff == null) {
                    return filter.has_child.short_circuit_cutoff;
                }

                filter.has_child.short_circuit_cutoff = cutoff;
                return this;
            },

            /**
                  Sets the scope of the filter.  A scope allows to run facets on the 
                  same scope name that will work against the child documents. 
      
                  @deprecated since elasticsearch 0.90
                  @member ejs.HasChildFilter
                  @param {String} s The scope name as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scope: function (s) {
                return this;
            }

        });
    };

    /**
      @class
      <p>The has_parent results in child documents that have parent docs matching 
      the query being returned.</p>
  
      @name ejs.HasParentFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Returns results that have parent documents matching the filter.
  
      @param {Object} qry A valid query object.
      @param {String} parentType The child type
      */
    ejs.HasParentFilter = function (qry, parentType) {

        if (!isQuery(qry)) {
            throw new TypeError('No Query object found');
        }

        var
          _common = ejs.FilterMixin('has_parent'),
          filter = _common.toJSON();

        filter.has_parent.query = qry.toJSON();
        filter.has_parent.parent_type = parentType;

        return extend(_common, {

            /**
                  Sets the query
      
                  @member ejs.HasParentFilter
                  @param {Object} q A valid Query object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (q) {
                if (q == null) {
                    return filter.has_parent.query;
                }

                if (!isQuery(q)) {
                    throw new TypeError('Argument must be a Query object');
                }

                filter.has_parent.query = q.toJSON();
                return this;
            },

            /**
                  Sets the filter
      
                  @since elasticsearch 0.90
                  @member ejs.HasParentFilter
                  @param {Object} f A valid Filter object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            filter: function (f) {
                if (f == null) {
                    return filter.has_parent.filter;
                }

                if (!isFilter(f)) {
                    throw new TypeError('Argument must be a Filter object');
                }

                filter.has_parent.filter = f.toJSON();
                return this;
            },

            /**
                  Sets the child document type to search against
      
                  @member ejs.HasParentFilter
                  @param {String} t A valid type name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            parentType: function (t) {
                if (t == null) {
                    return filter.has_parent.parent_type;
                }

                filter.has_parent.parent_type = t;
                return this;
            },

            /**
                  Sets the scope of the filter.  A scope allows to run facets on the 
                  same scope name that will work against the parent documents. 
      
                  @deprecated since elasticsearch 0.90
                  @member ejs.HasParentFilter
                  @param {String} s The scope name as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scope: function (s) {
                return this;
            }

        });
    };

    /**
      @class
      <p>Filters documents that only have the provided ids. Note, this filter 
      does not require the _id field to be indexed since it works using the 
      _uid field.</p>
  
      @name ejs.IdsFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Matches documents with the specified id(s).
  
      @param {(String|String[])} ids A single document id or a list of document ids.
      */
    ejs.IdsFilter = function (ids) {

        var
          _common = ejs.FilterMixin('ids'),
          filter = _common.toJSON();

        if (isString(ids)) {
            filter.ids.values = [ids];
        } else if (isArray(ids)) {
            filter.ids.values = ids;
        } else {
            throw new TypeError('Argument must be a string or an array');
        }

        return extend(_common, {

            /**
                  Sets the values array or adds a new value. if val is a string, it
                  is added to the list of existing document ids.  If val is an
                  array it is set as the document values and replaces any existing values.
      
                  @member ejs.IdsFilter
                  @param {(String|String[])} val An single document id or an array of document ids.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            values: function (val) {
                if (val == null) {
                    return filter.ids.values;
                }

                if (isString(val)) {
                    filter.ids.values.push(val);
                } else if (isArray(val)) {
                    filter.ids.values = val;
                } else {
                    throw new TypeError('Argument must be a string or an array');
                }

                return this;
            },

            /**
                  Sets the type as a single type or an array of types.  If type is a
                  string, it is added to the list of existing types.  If type is an
                  array, it is set as the types and overwrites an existing types. This
                  parameter is optional.
      
                  @member ejs.IdsFilter
                  @param {(String|String[])} type A type or a list of types
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (type) {
                if (filter.ids.type == null) {
                    filter.ids.type = [];
                }

                if (type == null) {
                    return filter.ids.type;
                }

                if (isString(type)) {
                    filter.ids.type.push(type);
                } else if (isArray(type)) {
                    filter.ids.type = type;
                } else {
                    throw new TypeError('Argument must be a string or an array');
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>The indices filter can be used when executed across multiple indices, 
      allowing to have a filter that executes only when executed on an index that 
      matches a specific list of indices, and another filter that executes when it 
      is executed on an index that does not match the listed indices.</p>
  
      @name ejs.IndicesFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      A configurable filter that is dependent on the index name.
  
      @param {Object} fltr A valid filter object.
      @param {(String|String[])} indices a single index name or an array of index 
        names.
      */
    ejs.IndicesFilter = function (fltr, indices) {

        if (!isFilter(fltr)) {
            throw new TypeError('Argument must be a Filter');
        }

        var
          _common = ejs.FilterMixin('indices'),
          filter = _common.toJSON();

        filter.indices.filter = fltr.toJSON();

        if (isString(indices)) {
            filter.indices.indices = [indices];
        } else if (isArray(indices)) {
            filter.indices.indices = indices;
        } else {
            throw new TypeError('Argument must be a string or array');
        }

        return extend(_common, {

            /**
                  Sets the indicies the filter should match.  When passed a string,
                  the index name is added to the current list of indices.  When passed
                  an array, it overwites all current indices.
      
                  @member ejs.IndicesFilter
                  @param {(String|String[])} i A single index name or an array of index names.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            indices: function (i) {
                if (i == null) {
                    return filter.indices.indices;
                }

                if (isString(i)) {
                    filter.indices.indices.push(i);
                } else if (isArray(i)) {
                    filter.indices.indices = i;
                } else {
                    throw new TypeError('Argument must be a string or array');
                }

                return this;
            },

            /**
                  Sets the filter to be used when executing on one of the indicies 
                  specified.
      
                  @member ejs.IndicesFilter
                  @param {Object} f A valid Filter object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            filter: function (f) {
                if (f == null) {
                    return filter.indices.filter;
                }

                if (!isFilter(f)) {
                    throw new TypeError('Argument must be a Filter');
                }

                filter.indices.filter = f.toJSON();
                return this;
            },

            /**
                  Sets the filter to be used on an index that does not match an index
                  name in the indices list.  Can also be set to "none" to not match any
                  documents or "all" to match all documents.
      
                  @member ejs.IndicesFilter
                  @param {(Filter|String)} f A valid Filter object or "none" or "all"
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            noMatchFilter: function (f) {
                if (f == null) {
                    return filter.indices.no_match_filter;
                }

                if (isString(f)) {
                    f = f.toLowerCase();
                    if (f === 'none' || f === 'all') {
                        filter.indices.no_match_filter = f;
                    }
                } else if (isFilter(f)) {
                    filter.indices.no_match_filter = f.toJSON();
                } else {
                    throw new TypeError('Argument must be string or Filter');
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>A limit filter limits the number of documents (per shard) to execute on.</p>
  
      @name ejs.LimitFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Limits the number of documents to execute on.
  
      @param {Integer} limit The number of documents to execute on.
      */
    ejs.LimitFilter = function (limit) {

        var
          _common = ejs.FilterMixin('limit'),
          filter = _common.toJSON();

        filter.limit.value = limit;

        return extend(_common, {

            /**
                  Sets the limit value.
      
                  @member ejs.LimitFilter
                  @param {Integer} val An The number of documents to execute on.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            value: function (val) {
                if (val == null) {
                    return filter.limit.value;
                }

                if (!isNumber(val)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.limit.value = val;
                return this;
            }

        });
    };

    /**
      @class
      <p>This filter can be used to match on all the documents
      in a given set of collections and/or types.</p>
  
      @name ejs.MatchAllFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      <p>A filter that matches on all documents</p>
  
       */
    ejs.MatchAllFilter = function () {
        return ejs.FilterMixin('match_all');
    };

    /**
      @class
      <p>An missingFilter matches documents where the specified field contains no legitimate value.</p>
  
      @name ejs.MissingFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Filters documents where a specific field has no value present.
  
      @param {String} fieldName the field name to check for missing values.
      */
    ejs.MissingFilter = function (fieldName) {


        var
          _common = ejs.FilterMixin('missing'),
          filter = _common.toJSON();

        filter.missing.field = fieldName;

        return extend(_common, {

            /**
                  Sets the field to check for missing values.
      
                  @member ejs.MissingFilter
                  @param {String} name A name of the field.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (name) {
                if (name == null) {
                    return filter.missing.field;
                }

                filter.missing.field = name;
                return this;
            },

            /**
                  Checks if the field doesn't exist.
      
                  @member ejs.MissingFilter
                  @param {Boolean} trueFalse True to check if the field doesn't exist.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            existence: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.missing.existence;
                }

                filter.missing.existence = trueFalse;
                return this;
            },

            /**
                  Checks if the field has null values.
      
                  @member ejs.MissingFilter
                  @param {Boolean} trueFalse True to check if the field has nulls.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            nullValue: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.missing.null_value;
                }

                filter.missing.null_value = trueFalse;
                return this;
            }

        });
    };

    /**
      @class
      <p>Nested filters allow you to search against content within objects that are
         embedded inside of other objects. It is similar to <code>XPath</code> 
         expressions in <code>XML</code> both conceptually and syntactically.</p>
  
      <p>
      The filter is executed against the nested objects / docs as if they were 
      indexed as separate docs and resulting in the root 
      parent doc (or parent nested mapping).</p>
    
      @name ejs.NestedFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      <p>Constructs a filter that is capable of executing a filter against objects
         nested within a document.</p>
  
      @param {String} path The nested object path.
  
       */
    ejs.NestedFilter = function (path) {

        var
          _common = ejs.FilterMixin('nested'),
          filter = _common.toJSON();

        filter.nested.path = path;

        return extend(_common, {

            /**
                   Sets the root context for the nested filter.
                   @member ejs.NestedFilter
                   @param {String} p The path defining the root for the nested filter.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            path: function (p) {
                if (p == null) {
                    return filter.nested.path;
                }

                filter.nested.path = p;
                return this;
            },

            /**
                   Sets the nested query to be executed.
                   @member ejs.NestedFilter
                   @param {Query} oQuery A valid Query object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            query: function (oQuery) {
                if (oQuery == null) {
                    return filter.nested.query;
                }

                if (!isQuery(oQuery)) {
                    throw new TypeError('Argument must be a Query object');
                }

                filter.nested.query = oQuery.toJSON();
                return this;
            },


            /**
                   Sets the nested filter to be executed.
                   @member ejs.NestedFilter
                   @param {Object} oFilter A valid Filter object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            filter: function (oFilter) {
                if (oFilter == null) {
                    return filter.nested.filter;
                }

                if (!isFilter(oFilter)) {
                    throw new TypeError('Argument must be a Filter object');
                }

                filter.nested.filter = oFilter.toJSON();
                return this;
            },

            /**
                  Sets the boost value of the nested <code>Query</code>.
      
                  @member ejs.NestedFilter
                  @param {Double} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return filter.nested.boost;
                }

                filter.nested.boost = boost;
                return this;
            },

            /**
                  If the nested query should be "joined" with the parent document.
                  Defaults to false.
      
                  @member ejs.NestedFilter
                  @param {Boolean} trueFalse If the query should be joined or not.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            join: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.nested.join;
                }

                filter.nested.join = trueFalse;
                return this;
            },

            /**
                  Sets the scope of the filter.  A scope allows to run facets on the 
                  same scope name that will work against the nested documents. 
      
                  @deprecated since elasticsearch 0.90
                  @member ejs.NestedFilter
                  @param {String} s The scope name as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scope: function (s) {
                return this;
            }

        });
    };

    /**
      @class
      <p>A container Filter that excludes the documents matched by the
      contained filter.</p>
  
      @name ejs.NotFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Container filter that excludes the matched documents of the contained filter.
  
      @param {Object} oFilter a valid Filter object such as a termFilter, etc.
      */
    ejs.NotFilter = function (oFilter) {

        if (!isFilter(oFilter)) {
            throw new TypeError('Argument must be a Filter');
        }

        var
          _common = ejs.FilterMixin('not'),
          filter = _common.toJSON();

        filter.not = oFilter.toJSON();

        return extend(_common, {

            /**
                   Sets the filter
      
                   @member ejs.NotFilter
                   @param {Object} fltr A valid filter object such as a termFilter, etc.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            filter: function (fltr) {
                if (fltr == null) {
                    return filter.not;
                }

                if (!isFilter(fltr)) {
                    throw new TypeError('Argument must be a Filter');
                }

                filter.not = fltr.toJSON();
                return this;
            }

        });
    };

    /**
      @class
      <p>Filters documents with fields that have values within a certain numeric 
      range. Similar to range filter, except that it works only with numeric 
      values, and the filter execution works differently.</p>
      
      <p>The numeric range filter works by loading all the relevant field values 
      into memory, and checking for the relevant docs if they satisfy the range 
      requirements. This requires more memory since the numeric range data are 
      loaded to memory, but can provide a significant increase in performance.</p> 
      
      <p>Note, if the relevant field values have already been loaded to memory, 
      for example because it was used in facets or was sorted on, then this 
      filter should be used.</p>
  
      @name ejs.NumericRangeFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      A Filter that only accepts numeric values within a specified range.
  
      @param {String} fieldName The name of the field to filter on.
      */
    ejs.NumericRangeFilter = function (fieldName) {

        var
          _common = ejs.FilterMixin('numeric_range'),
          filter = _common.toJSON();

        filter.numeric_range[fieldName] = {};

        return extend(_common, {

            /**
                   Returns the field name used to create this object.
      
                   @member ejs.NumericRangeFilter
                   @param {String} field the field name
                   @returns {Object} returns <code>this</code> so that calls can be 
                    chained. Returns {String}, field name when field is not specified.
                   */
            field: function (field) {
                var oldValue = filter.numeric_range[fieldName];

                if (field == null) {
                    return fieldName;
                }

                delete filter.numeric_range[fieldName];
                fieldName = field;
                filter.numeric_range[fieldName] = oldValue;

                return this;
            },

            /**
                   Sets the endpoint for the current range.
      
                   @member ejs.NumericRangeFilter
                   @param {Number} startPoint A numeric value representing the start of the range
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            from: function (from) {
                if (from == null) {
                    return filter.numeric_range[fieldName].from;
                }

                if (!isNumber(from)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.numeric_range[fieldName].from = from;
                return this;
            },

            /**
                   Sets the endpoint for the current range.
      
                   @member ejs.NumericRangeFilter
                   @param {Number} endPoint A numeric value representing the end of the range
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            to: function (to) {
                if (to == null) {
                    return filter.numeric_range[fieldName].to;
                }

                if (!isNumber(to)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.numeric_range[fieldName].to = to;
                return this;
            },

            /**
                  Should the first from (if set) be inclusive or not. 
                  Defaults to true
      
                  @member ejs.NumericRangeFilter
                  @param {Boolean} trueFalse true to include, false to exclude 
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            includeLower: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.numeric_range[fieldName].include_lower;
                }

                filter.numeric_range[fieldName].include_lower = trueFalse;
                return this;
            },

            /**
                  Should the last to (if set) be inclusive or not. Defaults to true.
      
                  @member ejs.NumericRangeFilter
                  @param {Boolean} trueFalse true to include, false to exclude 
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            includeUpper: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.numeric_range[fieldName].include_upper;
                }

                filter.numeric_range[fieldName].include_upper = trueFalse;
                return this;
            },

            /**
                  Greater than value.  Same as setting from to the value, and 
                  include_lower to false,
      
                  @member ejs.NumericRangeFilter
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            gt: function (val) {
                if (val == null) {
                    return filter.numeric_range[fieldName].gt;
                }

                if (!isNumber(val)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.numeric_range[fieldName].gt = val;
                return this;
            },

            /**
                  Greater than or equal to value.  Same as setting from to the value,
                  and include_lower to true.
      
                  @member ejs.NumericRangeFilter
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            gte: function (val) {
                if (val == null) {
                    return filter.numeric_range[fieldName].gte;
                }

                if (!isNumber(val)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.numeric_range[fieldName].gte = val;
                return this;
            },

            /**
                  Less than value.  Same as setting to to the value, and include_upper 
                  to false.
      
                  @member ejs.NumericRangeFilter
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lt: function (val) {
                if (val == null) {
                    return filter.numeric_range[fieldName].lt;
                }

                if (!isNumber(val)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.numeric_range[fieldName].lt = val;
                return this;
            },

            /**
                  Less than or equal to value.  Same as setting to to the value, 
                  and include_upper to true.
      
                  @member ejs.NumericRangeFilter
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lte: function (val) {
                if (val == null) {
                    return filter.numeric_range[fieldName].lte;
                }

                if (!isNumber(val)) {
                    throw new TypeError('Argument must be a numeric value');
                }

                filter.numeric_range[fieldName].lte = val;
                return this;
            }

        });
    };

    /**
      @class
      A container filter that allows Boolean OR composition of filters.
  
      @name ejs.OrFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      A container Filter that allows Boolean OR composition of filters.
  
      @param {(Filter|Filter[])} filters A valid Filter or array of Filters.
      */
    ejs.OrFilter = function (filters) {

        var
          i,
          len,
          _common = ejs.FilterMixin('or'),
          filter = _common.toJSON();

        filter.or.filters = [];

        if (isFilter(filters)) {
            filter.or.filters.push(filters.toJSON());
        } else if (isArray(filters)) {
            for (i = 0, len = filters.length; i < len; i++) {
                if (!isFilter(filters[i])) {
                    throw new TypeError('Argument must be array of Filters');
                }

                filter.or.filters.push(filters[i].toJSON());
            }
        } else {
            throw new TypeError('Argument must be a Filter or array of Filters');
        }

        return extend(_common, {

            /**
                   Updates the filters.  If passed a single Filter it is added to 
                   the existing filters.  If passed an array of Filters, they 
                   replace all existing Filters.
      
                   @member ejs.OrFilter
                   @param {(Filter|Filter[])} fltr A Filter or array of Filters
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            filters: function (fltr) {
                var i, len;

                if (fltr == null) {
                    return filter.or.filters;
                }

                if (isFilter(fltr)) {
                    filter.or.filters.push(fltr.toJSON());
                } else if (isArray(fltr)) {
                    filter.or.filters = [];
                    for (i = 0, len = fltr.length; i < len; i++) {
                        if (!isFilter(fltr[i])) {
                            throw new TypeError('Argument must be an array of Filters');
                        }

                        filter.or.filters.push(fltr[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be a Filter or array of Filters');
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>Filters documents that have fields containing terms with a specified prefix (not analyzed). Similar
      to phrase query, except that it acts as a filter. Can be placed within queries that accept a filter.</p>
  
      @name ejs.PrefixFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Filters documents that have fields containing terms with a specified prefix.
  
      @param {String} fieldName the field name to be used during matching.
      @param {String} prefix the prefix value.
      */
    ejs.PrefixFilter = function (fieldName, prefix) {

        var
          _common = ejs.FilterMixin('prefix'),
          filter = _common.toJSON();

        filter.prefix[fieldName] = prefix;

        return extend(_common, {

            /**
                   Returns the field name used to create this object.
      
                   @member ejs.PrefixFilter
                   @param {String} field the field name
                   @returns {Object} returns <code>this</code> so that calls can be 
                    chained. Returns {String}, field name when field is not specified.
                   */
            field: function (field) {
                var oldValue = filter.prefix[fieldName];

                if (field == null) {
                    return fieldName;
                }

                delete filter.prefix[fieldName];
                fieldName = field;
                filter.prefix[fieldName] = oldValue;

                return this;
            },

            /**
                   Sets the prefix to search for.
      
                   @member ejs.PrefixFilter
                   @param {String} value the prefix value to match
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            prefix: function (value) {
                if (value == null) {
                    return filter.prefix[fieldName];
                }

                filter.prefix[fieldName] = value;
                return this;
            }

        });
    };

    /**
      @class
      <p>Wraps any query to be used as a filter. Can be placed within queries 
      that accept a filter.</p>
  
      <p>The result of the filter is not cached by default.  Set the cache 
      parameter to true to cache the result of the filter. This is handy when the 
      same query is used on several (many) other queries.</p> 
    
      <p>Note, the process of caching the first execution is higher when not 
      caching (since it needs to satisfy different queries).</p>
    
      @name ejs.QueryFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Filters documents matching the wrapped query.
  
      @param {Object} qry A valid query object.
      */
    ejs.QueryFilter = function (qry) {

        if (!isQuery(qry)) {
            throw new TypeError('Argument must be a Query');
        }

        var
          _common = ejs.FilterMixin('fquery'),
          filter = _common.toJSON();

        filter.fquery.query = qry.toJSON();

        return extend(_common, {

            /**
                  Sets the query
      
                  @member ejs.QueryFilter
                  @param {Object} q A valid Query object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (q) {
                if (q == null) {
                    return filter.fquery.query;
                }

                if (!isQuery(q)) {
                    throw new TypeError('Argument must be a Query');
                }

                filter.fquery.query = q.toJSON();
                return this;
            }

        });
    };

    /**
      @class
      <p>Matches documents with fields that have terms within a certain range.</p>
  
      @name ejs.RangeFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Filters documents with fields that have terms within a certain range.
  
      @param {String} field A valid field name.
      */
    ejs.RangeFilter = function (field) {

        var
          _common = ejs.FilterMixin('range'),
          filter = _common.toJSON();

        filter.range[field] = {};

        return extend(_common, {

            /**
                   The field to run the filter against.
      
                   @member ejs.RangeFilter
                   @param {String} f A single field name.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            field: function (f) {
                var oldValue = filter.range[field];

                if (f == null) {
                    return field;
                }

                delete filter.range[field];
                field = f;
                filter.range[f] = oldValue;

                return this;
            },

            /**
                  The lower bound. Defaults to start from the first.
      
                  @member ejs.RangeFilter
                  @param {*} f the lower bound value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            from: function (f) {
                if (f == null) {
                    return filter.range[field].from;
                }

                filter.range[field].from = f;
                return this;
            },

            /**
                  The upper bound. Defaults to unbounded.
      
                  @member ejs.RangeFilter
                  @param {*} t the upper bound value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            to: function (t) {
                if (t == null) {
                    return filter.range[field].to;
                }

                filter.range[field].to = t;
                return this;
            },

            /**
                  Should the first from (if set) be inclusive or not. 
                  Defaults to true
      
                  @member ejs.RangeFilter
                  @param {Boolean} trueFalse true to include, false to exclude 
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            includeLower: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.range[field].include_lower;
                }

                filter.range[field].include_lower = trueFalse;
                return this;
            },

            /**
                  Should the last to (if set) be inclusive or not. Defaults to true.
      
                  @member ejs.RangeFilter
                  @param {Boolean} trueFalse true to include, false to exclude 
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            includeUpper: function (trueFalse) {
                if (trueFalse == null) {
                    return filter.range[field].include_upper;
                }

                filter.range[field].include_upper = trueFalse;
                return this;
            },

            /**
                  Greater than value.  Same as setting from to the value, and 
                  include_lower to false,
      
                  @member ejs.RangeFilter
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            gt: function (val) {
                if (val == null) {
                    return filter.range[field].gt;
                }

                filter.range[field].gt = val;
                return this;
            },

            /**
                  Greater than or equal to value.  Same as setting from to the value,
                  and include_lower to true.
      
                  @member ejs.RangeFilter
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            gte: function (val) {
                if (val == null) {
                    return filter.range[field].gte;
                }

                filter.range[field].gte = val;
                return this;
            },

            /**
                  Less than value.  Same as setting to to the value, and include_upper 
                  to false.
      
                  @member ejs.RangeFilter
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lt: function (val) {
                if (val == null) {
                    return filter.range[field].lt;
                }

                filter.range[field].lt = val;
                return this;
            },

            /**
                  Less than or equal to value.  Same as setting to to the value, 
                  and include_upper to true.
      
                  @member ejs.RangeFilter
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lte: function (val) {
                if (val == null) {
                    return filter.range[field].lte;
                }

                filter.range[field].lte = val;
                return this;
            }

        });
    };

    /**
      @class
      <p>Filters documents that have a field value matching a regular expression. 
      Based on Lucene 4.0 RegexpFilter which uses automaton to efficiently iterate 
      over index terms.</p>
  
      @name ejs.RegexpFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Matches documents that have fields matching a regular expression.
  
      @param {String} field A valid field name.
      @param {String} value A regex pattern.
      */
    ejs.RegexpFilter = function (field, value) {

        var
        _common = ejs.FilterMixin('regexp'),
        filter = _common.toJSON();

        filter.regexp[field] = {
            value: value
        };

        return extend(_common, {

            /**
                   The field to run the filter against.
      
                   @member ejs.RegexpFilter
                   @param {String} f A single field name.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            field: function (f) {
                var oldValue = filter.regexp[field];

                if (f == null) {
                    return field;
                }

                delete filter.regexp[field];
                field = f;
                filter.regexp[f] = oldValue;

                return this;
            },

            /**
                  The regexp value.
      
                  @member ejs.RegexpFilter
                  @param {String} p A string regexp
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            value: function (p) {
                if (p == null) {
                    return filter.regexp[field].value;
                }

                filter.regexp[field].value = p;
                return this;
            },

            /**
                  The regex flags to use.  Valid flags are:
              
                  INTERSECTION - Support for intersection notation
                  COMPLEMENT - Support for complement notation
                  EMPTY - Support for the empty language symbol: #
                  ANYSTRING - Support for the any string symbol: @
                  INTERVAL - Support for numerical interval notation: <n-m>
                  NONE - Disable support for all syntax options
                  ALL - Enables support for all syntax options
              
                  Use multiple flags by separating with a "|" character.  Example:
              
                  INTERSECTION|COMPLEMENT|EMPTY
      
                  @member ejs.RegexpFilter
                  @param {String} f The flags as a string, separate multiple flags with "|".
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            flags: function (f) {
                if (f == null) {
                    return filter.regexp[field].flags;
                }

                filter.regexp[field].flags = f;
                return this;
            },

            /**
                  The regex flags to use as a numeric value.  Advanced use only,
                  it is probably better to stick with the <code>flags</code> option.
              
                  @member ejs.RegexpFilter
                  @param {String} v The flags as a numeric value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            flagsValue: function (v) {
                if (v == null) {
                    return filter.regexp[field].flags_value;
                }

                filter.regexp[field].flags_value = v;
                return this;
            }

        });
    };

    /**
      @class
      <p>A filter allowing to define scripts as filters</p>
  
      @name ejs.ScriptFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      A filter allowing to define scripts as filters.
  
      @param {String} script The script as a string.
      */
    ejs.ScriptFilter = function (script) {

        var
          _common = ejs.FilterMixin('script'),
          filter = _common.toJSON();

        filter.script.script = script;

        return extend(_common, {

            /**
                  Sets the script.
      
                  @member ejs.ScriptFilter
                  @param {String} s The script as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            script: function (s) {
                if (s == null) {
                    return filter.script.script;
                }

                filter.script.script = s;
                return this;
            },

            /**
                  Sets parameters that will be applied to the script.  Overwrites 
                  any existing params.
      
                  @member ejs.ScriptFilter
                  @param {Object} p An object where the keys are the parameter name and 
                    values are the parameter value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            params: function (p) {
                if (p == null) {
                    return filter.script.params;
                }

                filter.script.params = p;
                return this;
            },

            /**
                  Sets the script language.
      
                  @member ejs.ScriptFilter
                  @param {String} lang The script language, default mvel.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lang: function (lang) {
                if (lang == null) {
                    return filter.script.lang;
                }

                filter.script.lang = lang;
                return this;
            }

        });
    };

    /**
      @class
      <p>Constructs a filter for docs matching any of the terms added to this
      object. Unlike a RangeFilter this can be used for filtering on multiple
      terms that are not necessarily in a sequence.</p>
  
      @name ejs.TermFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Constructs a filter for docs matching the term added to this object.
  
      @param {string} fieldName The document field/fieldName to execute the filter against.
      @param {string} term The literal term used to filter the results.
      */
    ejs.TermFilter = function (fieldName, term) {

        var
          _common = ejs.FilterMixin('term'),
          filter = _common.toJSON();

        filter.term[fieldName] = term;

        return extend(_common, {

            /**
                   Provides access to the filter fieldName used to construct the 
                   termFilter object.
                   
                   @member ejs.TermFilter
                   @param {String} f the fieldName term
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                    When k is not specified, Returns {String}, the filter fieldName used to construct 
                    the termFilter object.
                   */
            field: function (f) {
                var oldValue = filter.term[fieldName];

                if (f == null) {
                    return fieldName;
                }

                delete filter.term[fieldName];
                fieldName = f;
                filter.term[fieldName] = oldValue;

                return this;
            },

            /**
                   Provides access to the filter term used to construct the 
                   termFilter object.
                   
                   @member ejs.TermFilter
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                    When k is not specified, Returns {String}, the filter term used 
                    to construct the termFilter object.
                   */
            term: function (v) {
                if (v == null) {
                    return filter.term[fieldName];
                }

                filter.term[fieldName] = v;
                return this;
            }

        });
    };

    /**
      @class
      <p>Filters documents that have fields that match any of the provided 
      terms (not analyzed)</p>
  
      @name ejs.TermsFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      A Filter that matches documents containing provided terms. 
  
      @param {String} field the document field/key to filter against
      @param {(String|String[])} terms a single term or an array of terms.
      */
    ejs.TermsFilter = function (field, terms) {

        var
          _common = ejs.FilterMixin('terms'),
          filter = _common.toJSON(),

          // make sure we are setup for a list of terms
          setupTerms = function () {
              if (!isArray(filter.terms[field])) {
                  filter.terms[field] = [];
              }
          },

          // make sure we are setup for a terms lookup
          setupLookup = function () {
              if (isArray(filter.terms[field])) {
                  filter.terms[field] = {};
              }
          };

        if (isArray(terms)) {
            filter.terms[field] = terms;
        } else {
            filter.terms[field] = [terms];
        }

        return extend(_common, {

            /**
                  Sets the fields to filter against.
      
                  @member ejs.TermsFilter
                  @param {String} f A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                var oldValue = filter.terms[field];

                if (f == null) {
                    return field;
                }

                delete filter.terms[field];
                field = f;
                filter.terms[f] = oldValue;

                return this;
            },

            /**
                  Sets the terms.  If t is a String, it is added to the existing
                  list of terms.  If t is an array, the list of terms replaces the
                  existing terms.
      
                  @member ejs.TermsFilter
                  @param {(String|String[])} t A single term or an array or terms.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            terms: function (t) {
                setupTerms();
                if (t == null) {
                    return filter.terms[field];
                }

                if (isArray(t)) {
                    filter.terms[field] = t;
                } else {
                    filter.terms[field].push(t);
                }

                return this;
            },

            /**
                  Sets the index the document containing the terms is in when 
                  performing a terms lookup.  Defaults to the index currently 
                  being searched.
      
                  @since elasticsearch 0.90
                  @member ejs.TermsFilter
                  @param {String} idx A valid index name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            index: function (idx) {
                setupLookup();
                if (idx == null) {
                    return filter.terms[field].index;
                }

                filter.terms[field].index = idx;
                return this;
            },

            /**
                  Sets the type the document containing the terms when performing a 
                  terms lookup.
      
                  @since elasticsearch 0.90
                  @member ejs.TermsFilter
                  @param {String} type A valid type name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (type) {
                setupLookup();
                if (type == null) {
                    return filter.terms[field].type;
                }

                filter.terms[field].type = type;
                return this;
            },


            /**
                  Sets the document id of the document containing the terms to use
                  when performing a terms lookup.
      
                  @since elasticsearch 0.90
                  @member ejs.TermsFilter
                  @param {String} id A valid index name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            id: function (id) {
                setupLookup();
                if (id == null) {
                    return filter.terms[field].id;
                }

                filter.terms[field].id = id;
                return this;
            },

            /**
                  Sets the path/field name where the terms in the source document
                  are located when performing a terms lookup.
      
                  @since elasticsearch 0.90
                  @member ejs.TermsFilter
                  @param {String} path A valid index name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            path: function (path) {
                setupLookup();
                if (path == null) {
                    return filter.terms[field].path;
                }

                filter.terms[field].path = path;
                return this;
            },

            /**
                  Sets the routing value for the source document when performing a 
                  terms lookup.
      
                  @since elasticsearch 0.90.2
                  @member ejs.TermsFilter
                  @param {String} path A valid index name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            routing: function (r) {
                setupLookup();
                if (r == null) {
                    return filter.terms[field].routing;
                }

                filter.terms[field].routing = r;
                return this;
            },

            /**
                  Enable or disable caching of the lookup
      
                  @member ejs.TermsFilter
                  @param {Boolean} trueFalse True to cache the lookup, false otherwise.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            cacheLookup: function (trueFalse) {
                setupLookup();
                if (trueFalse == null) {
                    return filter.terms[field].cache;
                }

                filter.terms[field].cache = trueFalse;
                return this;
            },

            /**
                  Sets the way terms filter executes is by iterating over the terms 
                  provided and finding matches docs (loading into a bitset) and 
                  caching it.  Valid values are: plain, bool, bool_nocache, and, 
                  and_nocache, or, or_nocache.  Defaults to plain.
      
                  @member ejs.TermsFilter
                  @param {String} e A valid execution method.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            execution: function (e) {
                if (e == null) {
                    return filter.terms.execution;
                }

                e = e.toLowerCase();
                if (e === 'plain' || e === 'bool' || e === 'bool_nocache' ||
                  e === 'and' || e === 'and_nocache' || e === 'or' || e === 'or_nocache') {
                    filter.terms.execution = e;
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>A Filter that filters results by a specified index type.</p>
  
      @name ejs.TypeFilter
      @ejs filter
      @borrows ejs.FilterMixin.name as name
      @borrows ejs.FilterMixin.cache as cache
      @borrows ejs.FilterMixin.cacheKey as cacheKey
      @borrows ejs.FilterMixin._type as _type
      @borrows ejs.FilterMixin.toJSON as toJSON
  
      @desc
      Filter results by a specified index type.
  
      @param {String} type the index type to filter on.
      */
    ejs.TypeFilter = function (type) {

        var
        _common = ejs.FilterMixin('type'),
        filter = _common.toJSON();

        filter.type.value = type;

        return extend(_common, {

            /**
                   Sets the type
      
                   @member ejs.TypeFilter
                   @param {String} type the index type to filter on
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            type: function (type) {
                if (type == null) {
                    return filter.type.value;
                }

                filter.type.value = type;
                return this;
            }

        });
    };

    /**
      @class
      <p>A <code>boolQuery</code> allows you to build <em>Boolean</em> query constructs
      from individual term or phrase queries. For example you might want to search
      for documents containing the terms <code>javascript</code> and <code>python</code>.</p>
  
      @name ejs.BoolQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      A Query that matches documents matching boolean combinations of other
      queries, e.g. <code>termQuerys, phraseQuerys</code> or other <code>boolQuerys</code>.
  
      */
    ejs.BoolQuery = function () {

        var
          _common = ejs.QueryMixin('bool'),
          query = _common.toJSON();

        return extend(_common, {

            /**
                   Adds query to boolean container. Given query "must" appear in matching documents.
      
                   @member ejs.BoolQuery
                   @param {Object} oQuery A valid <code>Query</code> object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            must: function (oQuery) {
                var i, len;

                if (query.bool.must == null) {
                    query.bool.must = [];
                }

                if (oQuery == null) {
                    return query.bool.must;
                }

                if (isQuery(oQuery)) {
                    query.bool.must.push(oQuery.toJSON());
                } else if (isArray(oQuery)) {
                    query.bool.must = [];
                    for (i = 0, len = oQuery.length; i < len; i++) {
                        if (!isQuery(oQuery[i])) {
                            throw new TypeError('Argument must be an array of Queries');
                        }

                        query.bool.must.push(oQuery[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be a Query or array of Queries');
                }

                return this;
            },

            /**
                   Adds query to boolean container. Given query "must not" appear in matching documents.
      
                   @member ejs.BoolQuery
                   @param {Object} oQuery A valid query object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            mustNot: function (oQuery) {
                var i, len;

                if (query.bool.must_not == null) {
                    query.bool.must_not = [];
                }

                if (oQuery == null) {
                    return query.bool.must_not;
                }

                if (isQuery(oQuery)) {
                    query.bool.must_not.push(oQuery.toJSON());
                } else if (isArray(oQuery)) {
                    query.bool.must_not = [];
                    for (i = 0, len = oQuery.length; i < len; i++) {
                        if (!isQuery(oQuery[i])) {
                            throw new TypeError('Argument must be an array of Queries');
                        }

                        query.bool.must_not.push(oQuery[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be a Query or array of Queries');
                }

                return this;
            },

            /**
                   Adds query to boolean container. Given query "should" appear in matching documents.
      
                   @member ejs.BoolQuery
                   @param {Object} oQuery A valid query object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            should: function (oQuery) {
                var i, len;

                if (query.bool.should == null) {
                    query.bool.should = [];
                }

                if (oQuery == null) {
                    return query.bool.should;
                }

                if (isQuery(oQuery)) {
                    query.bool.should.push(oQuery.toJSON());
                } else if (isArray(oQuery)) {
                    query.bool.should = [];
                    for (i = 0, len = oQuery.length; i < len; i++) {
                        if (!isQuery(oQuery[i])) {
                            throw new TypeError('Argument must be an array of Queries');
                        }

                        query.bool.should.push(oQuery[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be a Query or array of Queries');
                }

                return this;
            },

            /**
                  Sets if the <code>Query</code> should be enhanced with a
                  <code>MatchAllQuery</code> in order to act as a pure exclude when
                  only negative (mustNot) clauses exist. Default: true.
      
                  @member ejs.BoolQuery
                  @param {String} trueFalse A <code>true/false</code value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            adjustPureNegative: function (trueFalse) {
                if (trueFalse == null) {
                    return query.bool.adjust_pure_negative;
                }

                query.bool.adjust_pure_negative = trueFalse;
                return this;
            },

            /**
                  Enables or disables similarity coordinate scoring of documents
                  matching the <code>Query</code>. Default: false.
      
                  @member ejs.BoolQuery
                  @param {String} trueFalse A <code>true/false</code value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            disableCoord: function (trueFalse) {
                if (trueFalse == null) {
                    return query.bool.disable_coord;
                }

                query.bool.disable_coord = trueFalse;
                return this;
            },

            /**
                  <p>Sets the number of optional clauses that must match.</p>
            
                  <p>By default no optional clauses are necessary for a match
                  (unless there are no required clauses).  If this method is used,
                  then the specified number of clauses is required.</p>
      
                  <p>Use of this method is totally independent of specifying that
                  any specific clauses are required (or prohibited).  This number will
                  only be compared against the number of matching optional clauses.</p>
         
                  @member ejs.BoolQuery
                  @param {Integer} minMatch A positive <code>integer</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minimumNumberShouldMatch: function (minMatch) {
                if (minMatch == null) {
                    return query.bool.minimum_number_should_match;
                }

                query.bool.minimum_number_should_match = minMatch;
                return this;
            }

        });
    };

    /**
      @class
      <p>The boosting query can be used to effectively demote results that match 
      a given query. Unlike the “NOT” clause in bool query, this still selects 
      documents that contain undesirable terms, but reduces their overall 
      score.</p>
  
      @name ejs.BoostingQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      <p>Constructs a query that can demote search results.  A negative boost.</p>
  
      @param {Object} positiveQry Valid query object used to select all matching docs.
      @param {Object} negativeQry Valid query object to match the undesirable docs 
        returned within the positiveQry result set.
      @param {Double} negativeBoost A double value where 0 < n < 1.
       */
    ejs.BoostingQuery = function (positiveQry, negativeQry, negativeBoost) {

        if (!isQuery(positiveQry) || !isQuery(negativeQry)) {
            throw new TypeError('Arguments must be Queries');
        }

        var
          _common = ejs.QueryMixin('boosting'),
          query = _common.toJSON();

        query.boosting.positive = positiveQry.toJSON();
        query.boosting.negative = negativeQry.toJSON();
        query.boosting.negative_boost = negativeBoost;

        return extend(_common, {

            /**
                   Sets the "master" query that determines which results are returned.
      
                   @member ejs.BoostingQuery
                   @param {Object} oQuery A valid <code>Query</code> object
                   @returns {Object} returns <code>this</code> so that calls can be 
                    chained. Returns {Object} current positive query if oQuery is
                    not specified.
                   */
            positive: function (oQuery) {
                if (oQuery == null) {
                    return query.boosting.positive;
                }

                if (!isQuery(oQuery)) {
                    throw new TypeError('Argument must be a Query');
                }

                query.boosting.positive = oQuery.toJSON();
                return this;
            },

            /**
                   Sets the query used to match documents in the <code>positive</code>
                   query that will be negatively boosted.
      
                   @member ejs.BoostingQuery
                   @param {Object} oQuery A valid <code>Query</code> object
                   @returns {Object} returns <code>this</code> so that calls can be 
                    chained. Returns {Object} current negative query if oQuery is
                    not specified.
                   */
            negative: function (oQuery) {
                if (oQuery == null) {
                    return query.boosting.negative;
                }

                if (!isQuery(oQuery)) {
                    throw new TypeError('Argument must be a Query');
                }

                query.boosting.negative = oQuery.toJSON();
                return this;
            },

            /**
                  Sets the negative boost value.
      
                  @member ejs.BoostingQuery
                  @param {Double} boost A positive <code>double</code> value where 0 < n < 1.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            negativeBoost: function (negBoost) {
                if (negBoost == null) {
                    return query.boosting.negative_boost;
                }

                query.boosting.negative_boost = negBoost;
                return this;
            }

        });
    };

    /**
      @class
      <p>A query that executes high-frequency terms in a optional sub-query to 
      prevent slow queries due to "common" terms like stopwords.</p>
    
      <p>This query basically builds two queries out of the terms in the query 
      string where low-frequency terms are added to a required boolean clause and 
      high-frequency terms are added to an optional boolean clause. The optional 
      clause is only executed if the required "low-frequency' clause matches.</p>
    
      <p><code>CommonTermsQuery</code> has several advantages over stopword 
      filtering at index or query time since a term can be "classified" based on 
      the actual document frequency in the index and can prevent slow queries even 
      across domains without specialized stopword files.</p>
    
      @name ejs.CommonTermsQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
    
      @desc
      A query that executes high-frequency terms in a optional sub-query.
  
      @param {String} field the document field/key to query against
      @param {String} qstr the query string
      */
    ejs.CommonTermsQuery = function (field, qstr) {

        var
          _common = ejs.QueryMixin('common'),
          query = _common.toJSON();

        // support for full Builder functionality where no constructor is used
        // use dummy field until one is set
        if (field == null) {
            field = 'no_field_set';
        }

        query.common[field] = {};

        // only set the query is one is passed in
        if (qstr != null) {
            query.common[field].query = qstr;
        }

        return extend(_common, {

            /**
                  Sets the field to query against.
      
                  @member ejs.CommonTermsQuery
                  @param {String} f A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                var oldValue = query.common[field];

                if (f == null) {
                    return field;
                }

                delete query.common[field];
                field = f;
                query.common[f] = oldValue;

                return this;
            },

            /**
                  Sets the query string.
      
                  @member ejs.CommonTermsQuery
                  @param {String} qstr The query string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (qstr) {
                if (qstr == null) {
                    return query.common[field].query;
                }

                query.common[field].query = qstr;
                return this;
            },

            /**
                  Sets the analyzer name used to analyze the <code>Query</code> object.
      
                  @member ejs.CommonTermsQuery
                  @param {String} analyzer A valid analyzer name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            analyzer: function (analyzer) {
                if (analyzer == null) {
                    return query.common[field].analyzer;
                }

                query.common[field].analyzer = analyzer;
                return this;
            },

            /**
                  Enables or disables similarity coordinate scoring of documents
                  commoning the <code>Query</code>. Default: false.
      
                  @member ejs.CommonTermsQuery
                  @param {String} trueFalse A <code>true/false</code value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            disableCoord: function (trueFalse) {
                if (trueFalse == null) {
                    return query.common[field].disable_coord;
                }

                query.common[field].disable_coord = trueFalse;
                return this;
            },

            /**
                  Sets the maximum threshold/frequency to be considered a low 
                  frequency term.  Set to a value between 0 and 1.
      
                  @member ejs.CommonTermsQuery
                  @param {Number} freq A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            cutoffFrequency: function (freq) {
                if (freq == null) {
                    return query.common[field].cutoff_frequency;
                }

                query.common[field].cutoff_frequency = freq;
                return this;
            },

            /**
                  Sets the boolean operator to be used for high frequency terms.
                  Default: AND
      
                  @member ejs.CommonTermsQuery
                  @param {String} op Any of "and" or "or", no quote characters.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            highFreqOperator: function (op) {
                if (op == null) {
                    return query.common[field].high_freq_operator;
                }

                op = op.toLowerCase();
                if (op === 'and' || op === 'or') {
                    query.common[field].high_freq_operator = op;
                }

                return this;
            },

            /**
                  Sets the boolean operator to be used for low frequency terms.
                  Default: AND
                
                  @member ejs.CommonTermsQuery
                  @param {String} op Any of "and" or "or", no quote characters.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lowFreqOperator: function (op) {
                if (op == null) {
                    return query.common[field].low_freq_operator;
                }

                op = op.toLowerCase();
                if (op === 'and' || op === 'or') {
                    query.common[field].low_freq_operator = op;
                }

                return this;
            },

            /**
                  Sets the minimum number of low freq matches that need to match in 
                  a document before that document is returned in the results.
      
                  @member ejs.CommonTermsQuery
                  @param {Integer} min A positive integer.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minimumShouldMatch: function (min) {
                if (min == null) {
                    return query.common[field].minimum_should_match.low_freq;
                }

                if (query.common[field].minimum_should_match == null) {
                    query.common[field].minimum_should_match = {};
                }

                query.common[field].minimum_should_match.low_freq = min;
                return this;
            },

            /**
                  Sets the minimum number of low freq matches that need to match in 
                  a document before that document is returned in the results.
      
                  @member ejs.CommonTermsQuery
                  @param {Integer} min A positive integer.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minimumShouldMatchLowFreq: function (min) {
                return this.minimumShouldMatch(min);
            },

            /**
                  Sets the minimum number of high freq matches that need to match in 
                  a document before that document is returned in the results.
      
                  @member ejs.CommonTermsQuery
                  @param {Integer} min A positive integer.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minimumShouldMatchHighFreq: function (min) {
                if (min == null) {
                    return query.common[field].minimum_should_match.high_freq;
                }

                if (query.common[field].minimum_should_match == null) {
                    query.common[field].minimum_should_match = {};
                }

                query.common[field].minimum_should_match.high_freq = min;
                return this;
            },

            /**
                  Sets the boost value for documents commoning the <code>Query</code>.
      
                  @member ejs.CommonTermsQuery
                  @param {Number} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.common[field].boost;
                }

                query.common[field].boost = boost;
                return this;
            }

        });
    };

    /**
      @class
      <p>A constant score query wraps another <code>Query</code> or
      <code>Filter</code> and returns a constant score for each
      result that is equal to the query boost.</p>
  
      <p>Note that lucene's query normalization (queryNorm) attempts
      to make scores between different queries comparable.  It does not
      change the relevance of your query, but it might confuse you when
      you look at the score of your documents and they are not equal to
      the query boost value as expected.  The scores were normalized by
      queryNorm, but maintain the same relevance.</p>
  
      @name ejs.ConstantScoreQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      <p>Constructs a query where each documents returned by the internal
      query or filter have a constant score equal to the boost factor.</p>
  
       */
    ejs.ConstantScoreQuery = function () {

        var
          _common = ejs.QueryMixin('constant_score'),
          query = _common.toJSON();

        return extend(_common, {
            /**
                   Adds the query to apply a constant score to.
      
                   @member ejs.ConstantScoreQuery
                   @param {Object} oQuery A valid <code>Query</code> object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            query: function (oQuery) {
                if (oQuery == null) {
                    return query.constant_score.query;
                }

                if (!isQuery(oQuery)) {
                    throw new TypeError('Argument must be a Query');
                }

                query.constant_score.query = oQuery.toJSON();
                return this;
            },

            /**
                   Adds the filter to apply a constant score to.
      
                   @member ejs.ConstantScoreQuery
                   @param {Object} oFilter A valid <code>Filter</code> object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            filter: function (oFilter) {
                if (oFilter == null) {
                    return query.constant_score.filter;
                }

                if (!isFilter(oFilter)) {
                    throw new TypeError('Argument must be a Filter');
                }

                query.constant_score.filter = oFilter.toJSON();
                return this;
            },

            /**
                  Enables caching of the filter.
      
                  @member ejs.ConstantScoreQuery
                  @param {Boolean} trueFalse A boolean value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            cache: function (trueFalse) {
                if (trueFalse == null) {
                    return query.constant_score._cache;
                }

                query.constant_score._cache = trueFalse;
                return this;
            },

            /**
                  Set the cache key.
      
                  @member ejs.ConstantScoreQuery
                  @param {String} k A string cache key.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            cacheKey: function (k) {
                if (k == null) {
                    return query.constant_score._cache_key;
                }

                query.constant_score._cache_key = k;
                return this;
            }

        });
    };

    /**
      @class
      A query that generates the union of documents produced by its subqueries, and
      that scores each document with the maximum score for that document as produced
      by any subquery, plus a tie breaking increment for any additional matching
      subqueries.
  
      @name ejs.DisMaxQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      A query that generates the union of documents produced by its subqueries such
      as <code>termQuerys, phraseQuerys</code>, <code>boolQuerys</code>, etc.
  
      */
    ejs.DisMaxQuery = function () {

        var
          _common = ejs.QueryMixin('dis_max'),
          query = _common.toJSON();

        return extend(_common, {

            /**
                  Updates the queries.  If passed a single Query, it is added to the
                  list of existing queries.  If passed an array of Queries, it 
                  replaces all existing values.
      
                  @member ejs.DisMaxQuery
                  @param {(Query|Query[])} qs A single Query or an array of Queries
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            queries: function (qs) {
                var i, len;

                if (qs == null) {
                    return query.dis_max.queries;
                }

                if (query.dis_max.queries == null) {
                    query.dis_max.queries = [];
                }

                if (isQuery(qs)) {
                    query.dis_max.queries.push(qs.toJSON());
                } else if (isArray(qs)) {
                    query.dis_max.queries = [];
                    for (i = 0, len = qs.length; i < len; i++) {
                        if (!isQuery(qs[i])) {
                            throw new TypeError('Argument must be array of Queries');
                        }

                        query.dis_max.queries.push(qs[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be a Query or array of Queries');
                }

                return this;
            },

            /**
                  <p>The tie breaker value.</p>  
      
                  <p>The tie breaker capability allows results that include the same term in multiple 
                  fields to be judged better than results that include this term in only the best of those 
                  multiple fields, without confusing this with the better case of two different terms in 
                  the multiple fields.</p>  
      
                  <p>Default: 0.0.</p>
      
                  @member ejs.DisMaxQuery
                  @param {Double} tieBreaker A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            tieBreaker: function (tieBreaker) {
                if (tieBreaker == null) {
                    return query.dis_max.tie_breaker;
                }

                query.dis_max.tie_breaker = tieBreaker;
                return this;
            }

        });
    };


    /**
      @class
      <p>Wrapper to allow SpanQuery objects participate in composite single-field 
      SpanQueries by 'lying' about their search field. That is, the masked 
      SpanQuery will function as normal, but when asked for the field it 
      queries against, it will return the value specified as the masked field vs.
      the real field used in the wrapped span query.</p>
  
      @name ejs.FieldMaskingSpanQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Wraps a SpanQuery and hides the real field being searched across.
  
      @param {Query} spanQry A valid SpanQuery
      @param {Integer} field the maximum field position in a match.
    
      */
    ejs.FieldMaskingSpanQuery = function (spanQry, field) {

        if (!isQuery(spanQry)) {
            throw new TypeError('Argument must be a SpanQuery');
        }

        var
          _common = ejs.QueryMixin('field_masking_span'),
          query = _common.toJSON();

        query.field_masking_span.query = spanQry.toJSON();
        query.field_masking_span.field = field;

        return extend(_common, {

            /**
                  Sets the span query to wrap.
      
                  @member ejs.FieldMaskingSpanQuery
                  @param {Query} spanQuery Any valid span type query.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (spanQuery) {
                if (spanQuery == null) {
                    return query.field_masking_span.query;
                }

                if (!isQuery(spanQuery)) {
                    throw new TypeError('Argument must be a SpanQuery');
                }

                query.field_masking_span.query = spanQuery.toJSON();
                return this;
            },

            /**
                  Sets the value of the "masked" field.  
      
                  @member ejs.FieldMaskingSpanQuery
                  @param {String} f A field name the wrapped span query should use
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                if (f == null) {
                    return query.field_masking_span.field;
                }

                query.field_masking_span.field = f;
                return this;
            }

        });
    };

    /**
      @class
      <p>Filter queries allow you to restrict the results returned by a query. There are
      several different types of filters that can be applied
      (see <a href="/jsdocs/ejs.filter.html">filter</a> module). A <code>filterQuery</code>
      takes a <code>Query</code> and a <code>Filter</code> object as arguments and constructs
      a new <code>Query</code> that is then used for the search.</p>
  
      @name ejs.FilteredQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      <p>A query that applies a filter to the results of another query.</p>
  
      @param {Object} someQuery a valid <code>Query</code> object
      @param {Object} someFilter a valid <code>Filter</code> object.  This parameter
        is optional.
  
       */
    ejs.FilteredQuery = function (someQuery, someFilter) {

        if (!isQuery(someQuery)) {
            throw new TypeError('Argument must be a Query');
        }

        if (someFilter != null && !isFilter(someFilter)) {
            throw new TypeError('Argument must be a Filter');
        }

        var
          _common = ejs.QueryMixin('filtered'),
          query = _common.toJSON();

        query.filtered.query = someQuery.toJSON();

        if (someFilter != null) {
            query.filtered.filter = someFilter.toJSON();
        }

        return extend(_common, {

            /**
                   <p>Adds the query to apply a constant score to.</p>
      
                   @member ejs.FilteredQuery
                   @param {Object} oQuery A valid <code>Query</code> object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            query: function (oQuery) {
                if (oQuery == null) {
                    return query.filtered.query;
                }

                if (!isQuery(oQuery)) {
                    throw new TypeError('Argument must be a Query');
                }

                query.filtered.query = oQuery.toJSON();
                return this;
            },

            /**
                   <p>Adds the filter to apply a constant score to.</p>
      
                   @member ejs.FilteredQuery
                   @param {Object} oFilter A valid <code>Filter</code> object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            filter: function (oFilter) {
                if (oFilter == null) {
                    return query.filtered.filter;
                }

                if (!isFilter(oFilter)) {
                    throw new TypeError('Argument must be a Filter');
                }

                query.filtered.filter = oFilter.toJSON();
                return this;
            },

            /**
                  <p>Sets the filter strategy.</p>  
      
                  <p>The strategy defines how the filter is applied during document collection.  
                  Valid values are:</p>
                  
                  <dl>
                      <dd><code>query_first</code> - advance query scorer first then filter</dd>
                      <dd><code>random_access_random</code> - random access filter</dd>
                      <dd><code>leap_frog</code> - query scorer and filter "leap-frog", query goes first</dd>
                      <dd><code>leap_frog_filter_first</code> - same as <code>leap_frog</code>, but filter goes first</dd>
                      <dd><code>random_access_N</code> - replace <code>N</code> with integer, same as random access 
                       except you can specify a custom threshold</dd>
                  </dl>
      
                  <p>This is an advanced setting, use with care.</p>
                  
                  @member ejs.FilteredQuery
                  @param {String} strategy The strategy as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            strategy: function (strategy) {
                if (strategy == null) {
                    return query.filtered.strategy;
                }

                strategy = strategy.toLowerCase();
                if (strategy === 'query_first' || strategy === 'random_access_always' ||
                  strategy === 'leap_frog' || strategy === 'leap_frog_filter_first' ||
                  strategy.indexOf('random_access_') === 0) {

                    query.filtered.strategy = strategy;
                }

                return this;
            },

            /**
                  <p>Enables caching of the filter.</p>
      
                  @member ejs.FilteredQuery
                  @param {Boolean} trueFalse A boolean value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            cache: function (trueFalse) {
                if (trueFalse == null) {
                    return query.filtered._cache;
                }

                query.filtered._cache = trueFalse;
                return this;
            },

            /**
                  <p>Set the cache key.</p>
      
                  @member ejs.FilteredQuery
                  @param {String} k A string cache key.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            cacheKey: function (k) {
                if (k == null) {
                    return query.filtered._cache_key;
                }

                query.filtered._cache_key = k;
                return this;
            }

        });
    };

    /**
      @class
      <p>The function_score allows you to modify the score of documents that are
      retrieved by a query. This can be useful if, for example, a score function is
      computationally expensive and it is sufficient to compute the score on a
      filtered set of documents.</p>
  
      @name ejs.FunctionScoreQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      <p>A query that allows you to modify the score of matching documents.</p>
  
       */
    ejs.FunctionScoreQuery = function () {

        var
          _common = ejs.QueryMixin('function_score'),
          query = _common.toJSON();

        return extend(_common, {

            /**
            Set the source query.
      
            @member ejs.FunctionScoreQuery
            @param {Query} oQuery A valid <code>Query</code> object
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            query: function (oQuery) {
                if (oQuery == null) {
                    return query.function_score.query;
                }

                if (!isQuery(oQuery)) {
                    throw new TypeError('Argument must be a Query');
                }

                query.function_score.query = oQuery.toJSON();
                return this;
            },

            /**
            Set the source filter.
      
            @member ejs.FunctionScoreQuery
            @param {Filter} oFilter A valid <code>Filter</code> object
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            filter: function (oFilter) {
                if (oFilter == null) {
                    return query.function_score.filter;
                }

                if (!isFilter(oFilter)) {
                    throw new TypeError('Argument must be a Filter');
                }

                query.function_score.filter = oFilter.toJSON();
                return this;
            },

            /**
            Set the scoring mode which specifies how the computed scores are combined.
            Valid values are: avg, max, min, sum, multiply, and first.
      
            @member ejs.FunctionScoreQuery
            @param {String} mode A scoring mode.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            scoreMode: function (mode) {
                if (mode == null) {
                    return query.function_score.score_mode;
                }

                mode = mode.toLowerCase();
                if (mode === 'avg' || mode === 'max' || mode === 'min' ||
                      mode === 'sum' || mode === 'multiply' || mode === 'first') {
                    query.function_score.score_mode = mode;
                }

                return this;
            },

            /**
            Set the setermines how the new calculated score is combined with the
            score from the original query. Valid values are: multiply, replace, sum,
            avg, max, and min.
      
            @member ejs.FunctionScoreQuery
            @param {String} mode A boosting mode.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            boostMode: function (mode) {
                if (mode == null) {
                    return query.function_score.boost_mode;
                }

                mode = mode.toLowerCase();
                if (mode === 'multiply' || mode === 'replace' || mode === 'sum' ||
                      mode === 'avg' || mode === 'max' || mode === 'min') {
                    query.function_score.boost_mode = mode;
                }

                return this;
            },

            /**
            Sets the boost value for all documents matching the query.
      
            @member ejs.FunctionScoreQuery
            @param {Float} boost A positive <code>float</code> value.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            boost: function (boost) {
                if (boost == null) {
                    return query.function_score.boost;
                }

                query.function_score.boost = boost;
                return this;
            },

            /**
            Add a single score function to the list of existing functions.
      
            @member ejs.FunctionScoreQuery
            @param {ScoreFunction} func A valid <code>ScoreFunction</code> object.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            function: function (func) {
                if (query.function_score.functions == null) {
                    query.function_score.functions = [];
                }

                if (func == null) {
                    return query.function_score.functions;
                }

                if (!isScoreFunction(func)) {
                    throw new TypeError('Argument must be a ScoreFunction');
                }

                query.function_score.functions.push(func.toJSON());
                return this;
            },

            /**
            Sets the score functions.  Replaces any existing score functions.
      
            @member ejs.FunctionScoreQuery
            @param {ScoreFunction[]} funcs A array of <code>ScoreFunctions</code>.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            functions: function (funcs) {
                var i, len;

                if (funcs == null) {
                    return query.function_score.functions;
                }

                if (!isArray(funcs)) {
                    throw new TypeError('Argument must be an array of ScoreFunctions');
                }

                query.function_score.functions = [];
                for (i = 0, len = funcs.length; i < len; i++) {
                    if (!isScoreFunction(funcs[i])) {
                        throw new TypeError('Argument must be an array of ScoreFunctions');
                    }

                    query.function_score.functions.push(funcs[i].toJSON());
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>The fuzzy_like_this_field query is the same as the fuzzy_like_this 
      query, except that it runs against a single field. It provides nicer query 
      DSL over the generic fuzzy_like_this query, and support typed fields 
      query (automatically wraps typed fields with type filter to match only on 
      the specific type).</p>
  
      <p>Fuzzifies ALL terms provided as strings and then picks the best n 
      differentiating terms. In effect this mixes the behaviour of FuzzyQuery and 
      MoreLikeThis but with special consideration of fuzzy scoring factors. This 
      generally produces good results for queries where users may provide details 
      in a number of fields and have no knowledge of boolean query syntax and 
      also want a degree of fuzzy matching and a fast query.</p>
  
      <p>For each source term the fuzzy variants are held in a BooleanQuery with 
      no coord factor (because we are not looking for matches on multiple variants 
      in any one doc). Additionally, a specialized TermQuery is used for variants 
      and does not use that variant term’s IDF because this would favour rarer 
      terms eg misspellings. Instead, all variants use the same IDF 
      ranking (the one for the source query term) and this is factored into the 
      variant’s boost. If the source query term does not exist in the index the 
      average IDF of the variants is used.</p>
  
      @name ejs.FuzzyLikeThisFieldQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      <p>Constructs a query where each documents returned are “like” provided text</p>
  
      @param {String} field The field to run the query against.
      @param {String} likeText The text to find documents like it.
      */
    ejs.FuzzyLikeThisFieldQuery = function (field, likeText) {

        var
          _common = ejs.QueryMixin('flt_field'),
          query = _common.toJSON();

        query.flt_field[field] = {
            like_text: likeText
        };

        return extend(_common, {

            /**
                   The field to run the query against.
      
                   @member ejs.FuzzyLikeThisFieldQuery
                   @param {String} f A single field name.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            field: function (f) {
                var oldValue = query.flt_field[field];

                if (f == null) {
                    return field;
                }

                delete query.flt_field[field];
                field = f;
                query.flt_field[f] = oldValue;

                return this;
            },

            /**
                  The text to find documents like
      
                  @member ejs.FuzzyLikeThisFieldQuery
                  @param {String} s A text string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            likeText: function (txt) {
                if (txt == null) {
                    return query.flt_field[field].like_text;
                }

                query.flt_field[field].like_text = txt;
                return this;
            },

            /**
                  Should term frequency be ignored. Defaults to false.
      
                  @member ejs.FuzzyLikeThisFieldQuery
                  @param {Boolean} trueFalse A boolean value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            ignoreTf: function (trueFalse) {
                if (trueFalse == null) {
                    return query.flt_field[field].ignore_tf;
                }

                query.flt_field[field].ignore_tf = trueFalse;
                return this;
            },

            /**
                  The maximum number of query terms that will be included in any 
                  generated query. Defaults to 25.
      
                  @member ejs.FuzzyLikeThisFieldQuery
                  @param {Integer} max A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxQueryTerms: function (max) {
                if (max == null) {
                    return query.flt_field[field].max_query_terms;
                }

                query.flt_field[field].max_query_terms = max;
                return this;
            },

            /**
                  The minimum similarity of the term variants. Defaults to 0.5.
      
                  @member ejs.FuzzyLikeThisFieldQuery
                  @param {Double} min A positive double value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minSimilarity: function (min) {
                if (min == null) {
                    return query.flt_field[field].min_similarity;
                }

                query.flt_field[field].min_similarity = min;
                return this;
            },

            /**
                  Length of required common prefix on variant terms. Defaults to 0..
      
                  @member ejs.FuzzyLikeThisFieldQuery
                  @param {Integer} len A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            prefixLength: function (len) {
                if (len == null) {
                    return query.flt_field[field].prefix_length;
                }

                query.flt_field[field].prefix_length = len;
                return this;
            },

            /**
                  The analyzer that will be used to analyze the text. Defaults to the 
                  analyzer associated with the field.
      
                  @member ejs.FuzzyLikeThisFieldQuery
                  @param {String} analyzerName The name of the analyzer.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            analyzer: function (analyzerName) {
                if (analyzerName == null) {
                    return query.flt_field[field].analyzer;
                }

                query.flt_field[field].analyzer = analyzerName;
                return this;
            },

            /**
                  Should the <code>Query</code> fail when an unsupported field
                  is specified. Defaults to true.
      
                  @member ejs.FuzzyLikeThisFieldQuery
                  @param {Boolean} trueFalse A boolean value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            failOnUnsupportedField: function (trueFalse) {
                if (trueFalse == null) {
                    return query.flt_field[field].fail_on_unsupported_field;
                }

                query.flt_field[field].fail_on_unsupported_field = trueFalse;
                return this;
            },

            /**
                  Sets the boost value of the <code>Query</code>.
      
                  @member ejs.FuzzyLikeThisFieldQuery
                  @param {Double} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.flt_field[field].boost;
                }

                query.flt_field[field].boost = boost;
                return this;
            }

        });
    };

    /**
      @class
      <p>Fuzzy like this query find documents that are “like” provided text by 
      running it against one or more fields.</p>
  
      <p>Fuzzifies ALL terms provided as strings and then picks the best n 
      differentiating terms. In effect this mixes the behaviour of FuzzyQuery and 
      MoreLikeThis but with special consideration of fuzzy scoring factors. This 
      generally produces good results for queries where users may provide details 
      in a number of fields and have no knowledge of boolean query syntax and 
      also want a degree of fuzzy matching and a fast query.</p>
    
      <p>For each source term the fuzzy variants are held in a BooleanQuery with 
      no coord factor (because we are not looking for matches on multiple variants 
      in any one doc). Additionally, a specialized TermQuery is used for variants 
      and does not use that variant term’s IDF because this would favour rarer 
      terms eg misspellings. Instead, all variants use the same IDF 
      ranking (the one for the source query term) and this is factored into the 
      variant’s boost. If the source query term does not exist in the index the 
      average IDF of the variants is used.</p>
  
      @name ejs.FuzzyLikeThisQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      <p>Constructs a query where each documents returned are “like” provided text</p>
  
      @param {String} likeText The text to find documents like it.
      */
    ejs.FuzzyLikeThisQuery = function (likeText) {

        var
          _common = ejs.QueryMixin('flt'),
          query = _common.toJSON();

        query.flt.like_text = likeText;

        return extend(_common, {

            /**
                   The fields to run the query against.  If you call with a single field,
                   it is added to the existing list of fields.  If called with an array
                   of field names, it replaces any existing values with the new array.
      
                   @member ejs.FuzzyLikeThisQuery
                   @param {(String|String[])} f A single field name or a list of field names.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            fields: function (f) {
                if (query.flt.fields == null) {
                    query.flt.fields = [];
                }

                if (f == null) {
                    return query.flt.fields;
                }

                if (isString(f)) {
                    query.flt.fields.push(f);
                } else if (isArray(f)) {
                    query.flt.fields = f;
                } else {
                    throw new TypeError('Argument must be a string or array');
                }

                return this;
            },

            /**
                  The text to find documents like
      
                  @member ejs.FuzzyLikeThisQuery
                  @param {String} s A text string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            likeText: function (txt) {
                if (txt == null) {
                    return query.flt.like_text;
                }

                query.flt.like_text = txt;
                return this;
            },

            /**
                  Should term frequency be ignored. Defaults to false.
      
                  @member ejs.FuzzyLikeThisQuery
                  @param {Boolean} trueFalse A boolean value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            ignoreTf: function (trueFalse) {
                if (trueFalse == null) {
                    return query.flt.ignore_tf;
                }

                query.flt.ignore_tf = trueFalse;
                return this;
            },

            /**
                  The maximum number of query terms that will be included in any 
                  generated query. Defaults to 25.
      
                  @member ejs.FuzzyLikeThisQuery
                  @param {Integer} max A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxQueryTerms: function (max) {
                if (max == null) {
                    return query.flt.max_query_terms;
                }

                query.flt.max_query_terms = max;
                return this;
            },

            /**
                  The minimum similarity of the term variants. Defaults to 0.5.
      
                  @member ejs.FuzzyLikeThisQuery
                  @param {Double} min A positive double value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minSimilarity: function (min) {
                if (min == null) {
                    return query.flt.min_similarity;
                }

                query.flt.min_similarity = min;
                return this;
            },

            /**
                  Length of required common prefix on variant terms. Defaults to 0..
      
                  @member ejs.FuzzyLikeThisQuery
                  @param {Integer} len A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            prefixLength: function (len) {
                if (len == null) {
                    return query.flt.prefix_length;
                }

                query.flt.prefix_length = len;
                return this;
            },

            /**
                  The analyzer that will be used to analyze the text. Defaults to the 
                  analyzer associated with the field.
      
                  @member ejs.FuzzyLikeThisQuery
                  @param {String} analyzerName The name of the analyzer.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            analyzer: function (analyzerName) {
                if (analyzerName == null) {
                    return query.flt.analyzer;
                }

                query.flt.analyzer = analyzerName;
                return this;
            },

            /**
                  Should the <code>Query</code> fail when an unsupported field
                  is specified. Defaults to true.
      
                  @member ejs.FuzzyLikeThisQuery
                  @param {Boolean} trueFalse A boolean value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            failOnUnsupportedField: function (trueFalse) {
                if (trueFalse == null) {
                    return query.flt.fail_on_unsupported_field;
                }

                query.flt.fail_on_unsupported_field = trueFalse;
                return this;
            }

        });
    };

    /**
      @class
      <p>A fuzzy search query based on the Damerau-Levenshtein (optimal string 
      alignment) algorithm, though you can explicitly choose classic Levenshtein 
      by passing false to the transpositions parameter./p>
    
      <p>fuzzy query on a numeric field will result in a range query “around” 
      the value using the min_similarity value. As an example, if you perform a
      fuzzy query against a field value of "12" with a min similarity setting
      of "2", the query will search for values between "10" and "14".</p>
  
      @name ejs.FuzzyQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      <p>Constructs a query where each documents returned are “like” provided text</p>
      
      @param {String} field The field to run the fuzzy query against.
      @param {String} value The value to fuzzify.
      
       */
    ejs.FuzzyQuery = function (field, value) {

        var
          _common = ejs.QueryMixin('fuzzy'),
          query = _common.toJSON();

        query.fuzzy[field] = {
            value: value
        };

        return extend(_common, {

            /**
                   <p>The field to run the query against.</p>
      
                   @member ejs.FuzzyQuery
                   @param {String} f A single field name.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            field: function (f) {
                var oldValue = query.fuzzy[field];

                if (f == null) {
                    return field;
                }

                delete query.fuzzy[field];
                field = f;
                query.fuzzy[f] = oldValue;

                return this;
            },

            /**
                  <p>The query text to fuzzify.</p>
      
                  @member ejs.FuzzyQuery
                  @param {String} s A text string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            value: function (txt) {
                if (txt == null) {
                    return query.fuzzy[field].value;
                }

                query.fuzzy[field].value = txt;
                return this;
            },

            /**
                  <p>Set to false to use classic Levenshtein edit distance.</p>
      
                  @member ejs.FuzzyQuery
                  @param {Boolean} trueFalse A boolean value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            transpositions: function (trueFalse) {
                if (trueFalse == null) {
                    return query.fuzzy[field].transpositions;
                }

                query.fuzzy[field].transpositions = trueFalse;
                return this;
            },

            /**
                  <p>The maximum number of query terms that will be included in any 
                  generated query. Defaults to <code>50</code>.<p>
      
                  @member ejs.FuzzyQuery
                  @param {Integer} max A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxExpansions: function (max) {
                if (max == null) {
                    return query.fuzzy[field].max_expansions;
                }

                query.fuzzy[field].max_expansions = max;
                return this;
            },

            /**
                  <p>The minimum similarity of the term variants. Defaults to <code>0.5</code>.</p>
      
                  @member ejs.FuzzyQuery
                  @param {Double} min A positive double value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minSimilarity: function (min) {
                if (min == null) {
                    return query.fuzzy[field].min_similarity;
                }

                query.fuzzy[field].min_similarity = min;
                return this;
            },

            /**
                  <p>Length of required common prefix on variant terms. Defaults to <code>0</code>.</p>
      
                  @member ejs.FuzzyQuery
                  @param {Integer} len A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            prefixLength: function (len) {
                if (len == null) {
                    return query.fuzzy[field].prefix_length;
                }

                query.fuzzy[field].prefix_length = len;
                return this;
            },

            /**
                  <p>Sets rewrite method.  Valid values are:</p> 
                  
                  <dl>
                      <dd><code>constant_score_auto</code> - tries to pick the best constant-score rewrite 
                       method based on term and document counts from the query</dd>
                    
                      <dd><code>scoring_boolean</code> - translates each term into boolean should and 
                       keeps the scores as computed by the query</dd>
                    
                      <dd><code>constant_score_boolean</code> - same as scoring_boolean, expect no scores
                       are computed.</dd>
                    
                      <dd><code>constant_score_filter</code> - first creates a private Filter, by visiting 
                       each term in sequence and marking all docs for that term</dd>
                    
                      <dd><code>top_terms_boost_N</code> - first translates each term into boolean should
                       and scores are only computed as the boost using the top <code>N</code>
                       scoring terms.  Replace <code>N</code> with an integer value.</dd>
                    
                      <dd><code>top_terms_N</code> - first translates each term into boolean should
                       and keeps the scores as computed by the query. Only the top <code>N</code>
                       scoring terms are used.  Replace <code>N</code> with an integer value.</dd>
                  </dl>
                  
                  <p>Default is <code>constant_score_auto</code>.</p>
      
                  <p>This is an advanced option, use with care.</p>
      
                  @member ejs.FuzzyQuery
                  @param {String} m The rewrite method as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            rewrite: function (m) {
                if (m == null) {
                    return query.fuzzy[field].rewrite;
                }

                m = m.toLowerCase();
                if (m === 'constant_score_auto' || m === 'scoring_boolean' ||
                  m === 'constant_score_boolean' || m === 'constant_score_filter' ||
                  m.indexOf('top_terms_boost_') === 0 ||
                  m.indexOf('top_terms_') === 0) {

                    query.fuzzy[field].rewrite = m;
                }

                return this;
            },


            /**
                  <p>Sets the boost value of the <code>Query</code>.</p>
      
                  @member ejs.FuzzyQuery
                  @param {Double} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.fuzzy[field].boost;
                }

                query.fuzzy[field].boost = boost;
                return this;
            }

        });
    };

    /**
      @class
      <p>Efficient querying of documents containing shapes indexed using the 
      geo_shape type.</p>
  
      <p>Much like the geo_shape type, the geo_shape query uses a grid square 
      representation of the query shape to find those documents which have shapes 
      that relate to the query shape in a specified way. In order to do this, the 
      field being queried must be of geo_shape type. The query will use the same 
      PrefixTree configuration as defined for the field.</p>
    
      @name ejs.GeoShapeQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      A Query to find documents with a geo_shapes matching a specific shape.
  
      */
    ejs.GeoShapeQuery = function (field) {

        var
          _common = ejs.QueryMixin('geo_shape'),
          query = _common.toJSON();

        query.geo_shape[field] = {};

        return extend(_common, {

            /**
                  Sets the field to query against.
      
                  @member ejs.GeoShapeQuery
                  @param {String} f A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                var oldValue = query.geo_shape[field];

                if (f == null) {
                    return field;
                }

                delete query.geo_shape[field];
                field = f;
                query.geo_shape[f] = oldValue;

                return this;
            },

            /**
                  Sets the shape
      
                  @member ejs.GeoShapeQuery
                  @param {String} shape A valid <code>Shape</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            shape: function (shape) {
                if (shape == null) {
                    return query.geo_shape[field].shape;
                }

                if (query.geo_shape[field].indexed_shape != null) {
                    delete query.geo_shape[field].indexed_shape;
                }

                query.geo_shape[field].shape = shape.toJSON();
                return this;
            },

            /**
                  Sets the indexed shape.  Use this if you already have shape definitions
                  already indexed.
      
                  @member ejs.GeoShapeQuery
                  @param {String} indexedShape A valid <code>IndexedShape</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            indexedShape: function (indexedShape) {
                if (indexedShape == null) {
                    return query.geo_shape[field].indexed_shape;
                }

                if (query.geo_shape[field].shape != null) {
                    delete query.geo_shape[field].shape;
                }

                query.geo_shape[field].indexed_shape = indexedShape.toJSON();
                return this;
            },

            /**
                  Sets the shape relation type.  A relationship between a Query Shape 
                  and indexed Shapes that will be used to determine if a Document 
                  should be matched or not.  Valid values are:  intersects, disjoint,
                  and within.
      
                  @member ejs.GeoShapeQuery
                  @param {String} indexedShape A valid <code>IndexedShape</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            relation: function (relation) {
                if (relation == null) {
                    return query.geo_shape[field].relation;
                }

                relation = relation.toLowerCase();
                if (relation === 'intersects' || relation === 'disjoint' || relation === 'within') {
                    query.geo_shape[field].relation = relation;
                }

                return this;
            },

            /**
                  <p>Sets the spatial strategy.</p>  
                  <p>Valid values are:</p>
                  
                  <dl>
                      <dd><code>recursive</code> - default, recursively traverse nodes in
                        the spatial prefix tree.  This strategy has support for 
                        searching non-point shapes.</dd>
                      <dd><code>term</code> - uses a large TermsFilter on each node
                        in the spatial prefix tree.  It only supports the search of 
                        indexed Point shapes.</dd>
                  </dl>
      
                  <p>This is an advanced setting, use with care.</p>
                  
                  @since elasticsearch 0.90
                  @member ejs.GeoShapeQuery
                  @param {String} strategy The strategy as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            strategy: function (strategy) {
                if (strategy == null) {
                    return query.geo_shape[field].strategy;
                }

                strategy = strategy.toLowerCase();
                if (strategy === 'recursive' || strategy === 'term') {
                    query.geo_shape[field].strategy = strategy;
                }

                return this;
            },

            /**
                  Sets the boost value for documents matching the <code>Query</code>.
      
                  @member ejs.GeoShapeQuery
                  @param {Number} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.geo_shape[field].boost;
                }

                query.geo_shape[field].boost = boost;
                return this;
            }

        });
    };

    /**
      @class
      <p>The has_child query works the same as the has_child filter, 
      by automatically wrapping the filter with a constant_score. Results in 
      parent documents that have child docs matching the query being returned.</p>
    
      @name ejs.HasChildQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Returns results that have child documents matching the query.
  
      @param {Object} qry A valid query object.
      @param {String} type The child type
      */
    ejs.HasChildQuery = function (qry, type) {

        if (!isQuery(qry)) {
            throw new TypeError('Argument must be a valid Query');
        }

        var
          _common = ejs.QueryMixin('has_child'),
          query = _common.toJSON();

        query.has_child.query = qry.toJSON();
        query.has_child.type = type;

        return extend(_common, {

            /**
                  Sets the query
      
                  @member ejs.HasChildQuery
                  @param {Object} q A valid Query object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (q) {
                if (q == null) {
                    return query.has_child.query;
                }

                if (!isQuery(q)) {
                    throw new TypeError('Argument must be a valid Query');
                }

                query.has_child.query = q.toJSON();
                return this;
            },

            /**
                  Sets the child document type to search against
      
                  @member ejs.HasChildQuery
                  @param {String} t A valid type name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (t) {
                if (t == null) {
                    return query.has_child.type;
                }

                query.has_child.type = t;
                return this;
            },

            /**
                  Sets the scope of the query.  A scope allows to run facets on the 
                  same scope name that will work against the child documents. 
      
                  @deprecated since elasticsearch 0.90
                  @member ejs.HasChildQuery
                  @param {String} s The scope name as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scope: function (s) {
                return this;
            },

            /**
                  Sets the scoring method.  Valid values are:
                  
                  none - the default, no scoring
                  max - the highest score of all matched child documents is used
                  sum - the sum the all the matched child documents is used
                  avg - the average of all matched child documents is used
      
                  @deprecated since elasticsearch 0.90.1, use scoreMode
                  
                  @member ejs.HasChildQuery
                  @param {String} s The score type as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scoreType: function (s) {
                if (s == null) {
                    return query.has_child.score_type;
                }

                s = s.toLowerCase();
                if (s === 'none' || s === 'max' || s === 'sum' || s === 'avg') {
                    query.has_child.score_type = s;
                }

                return this;
            },

            /**
                  Sets the scoring method.  Valid values are:
                  
                  none - the default, no scoring
                  max - the highest score of all matched child documents is used
                  sum - the sum the all the matched child documents is used
                  avg - the average of all matched child documents is used
      
                  @member ejs.HasChildQuery
                  @param {String} s The score type as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scoreMode: function (s) {
                if (s == null) {
                    return query.has_child.score_mode;
                }

                s = s.toLowerCase();
                if (s === 'none' || s === 'max' || s === 'sum' || s === 'avg') {
                    query.has_child.score_mode = s;
                }

                return this;
            },

            /**
                  Sets the cutoff value to short circuit processing.
      
                  @member ejs.HasChildQuery
                  @param {Integer} cutoff A positive <code>integer</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            shortCircuitCutoff: function (cutoff) {
                if (cutoff == null) {
                    return query.has_child.short_circuit_cutoff;
                }

                query.has_child.short_circuit_cutoff = cutoff;
                return this;
            }

        });
    };

    /**
      @class
      <p>The has_parent query works the same as the has_parent filter, by 
      automatically wrapping the filter with a constant_score. Results in 
      child documents that have parent docs matching the query being returned.</p>
  
      @name ejs.HasParentQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Returns results that have parent documents matching the query.
  
      @param {Object} qry A valid query object.
      @param {String} parentType The child type
      */
    ejs.HasParentQuery = function (qry, parentType) {

        if (!isQuery(qry)) {
            throw new TypeError('Argument must be a Query');
        }

        var
          _common = ejs.QueryMixin('has_parent'),
          query = _common.toJSON();

        query.has_parent.query = qry.toJSON();
        query.has_parent.parent_type = parentType;

        return extend(_common, {

            /**
                  Sets the query
      
                  @member ejs.HasParentQuery
                  @param {Object} q A valid Query object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (q) {
                if (q == null) {
                    return query.has_parent.query;
                }

                if (!isQuery(q)) {
                    throw new TypeError('Argument must be a Query');
                }

                query.has_parent.query = q.toJSON();
                return this;
            },

            /**
                  Sets the child document type to search against
      
                  @member ejs.HasParentQuery
                  @param {String} t A valid type name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            parentType: function (t) {
                if (t == null) {
                    return query.has_parent.parent_type;
                }

                query.has_parent.parent_type = t;
                return this;
            },

            /**
                  Sets the scope of the query.  A scope allows to run facets on the 
                  same scope name that will work against the parent documents. 
      
                  @deprecated since elasticsearch 0.90
                  @member ejs.HasParentQuery
                  @param {String} s The scope name as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scope: function (s) {
                return this;
            },

            /**
                  Sets the scoring method.  Valid values are:
                  
                  none - the default, no scoring
                  score - the score of the parent is used in all child documents.
      
                  @deprecated since elasticsearch 0.90.1 use scoreMode
                  
                  @member ejs.HasParentQuery
                  @param {String} s The score type as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scoreType: function (s) {
                if (s == null) {
                    return query.has_parent.score_type;
                }

                s = s.toLowerCase();
                if (s === 'none' || s === 'score') {
                    query.has_parent.score_type = s;
                }

                return this;
            },

            /**
                  Sets the scoring method.  Valid values are:
                  
                  none - the default, no scoring
                  score - the score of the parent is used in all child documents.
                  
                  @member ejs.HasParentQuery
                  @param {String} s The score type as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scoreMode: function (s) {
                if (s == null) {
                    return query.has_parent.score_mode;
                }

                s = s.toLowerCase();
                if (s === 'none' || s === 'score') {
                    query.has_parent.score_mode = s;
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>Filters documents that only have the provided ids. Note, this filter 
      does not require the _id field to be indexed since it works using the 
      _uid field.</p>
  
      @name ejs.IdsQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Matches documents with the specified id(s).
  
      @param {(String|String[])} ids A single document id or a list of document ids.
      */
    ejs.IdsQuery = function (ids) {

        var
          _common = ejs.QueryMixin('ids'),
          query = _common.toJSON();

        if (isString(ids)) {
            query.ids.values = [ids];
        } else if (isArray(ids)) {
            query.ids.values = ids;
        } else {
            throw new TypeError('Argument must be string or array');
        }

        return extend(_common, {

            /**
                  Sets the values array or adds a new value. if val is a string, it
                  is added to the list of existing document ids.  If val is an
                  array it is set as the document values and replaces any existing values.
      
                  @member ejs.IdsQuery
                  @param {(String|String[])} val An single document id or an array of document ids.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            values: function (val) {
                if (val == null) {
                    return query.ids.values;
                }

                if (isString(val)) {
                    query.ids.values.push(val);
                } else if (isArray(val)) {
                    query.ids.values = val;
                } else {
                    throw new TypeError('Argument must be string or array');
                }

                return this;
            },

            /**
                  Sets the type as a single type or an array of types.  If type is a
                  string, it is added to the list of existing types.  If type is an
                  array, it is set as the types and overwrites an existing types. This
                  parameter is optional.
      
                  @member ejs.IdsQuery
                  @param {(String|String[])} type A type or a list of types
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (type) {
                if (query.ids.type == null) {
                    query.ids.type = [];
                }

                if (type == null) {
                    return query.ids.type;
                }

                if (isString(type)) {
                    query.ids.type.push(type);
                } else if (isArray(type)) {
                    query.ids.type = type;
                } else {
                    throw new TypeError('Argument must be string or array');
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>The indices query can be used when executed across multiple indices, 
      allowing to have a query that executes only when executed on an index that 
      matches a specific list of indices, and another query that executes when it 
      is executed on an index that does not match the listed indices.</p>
  
      @name ejs.IndicesQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      A configurable query that is dependent on the index name.
  
      @param {Query} qry A valid query object.
      @param {(String|String[])} indices a single index name or an array of index 
        names.
      */
    ejs.IndicesQuery = function (qry, indices) {

        if (!isQuery(qry)) {
            throw new TypeError('Argument must be a Query');
        }

        var
          _common = ejs.QueryMixin('indices'),
          query = _common.toJSON();

        query.indices.query = qry.toJSON();

        if (isString(indices)) {
            query.indices.indices = [indices];
        } else if (isArray(indices)) {
            query.indices.indices = indices;
        } else {
            throw new TypeError('Argument must be a string or array');
        }

        return extend(_common, {

            /**
                  Sets the indicies the query should match.  When passed a string,
                  the index name is added to the current list of indices.  When passed
                  an array, it overwites all current indices.
      
                  @member ejs.IndicesQuery
                  @param {(String|String[])} i A single index name or an array of index names.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            indices: function (i) {
                if (i == null) {
                    return query.indices.indices;
                }

                if (isString(i)) {
                    query.indices.indices.push(i);
                } else if (isArray(i)) {
                    query.indices.indices = i;
                } else {
                    throw new TypeError('Argument must be a string or array');
                }

                return this;
            },

            /**
                  Sets the query to be executed against the indices specified.
      
                  @member ejs.IndicesQuery
                  @param {Query} q A valid Query object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (q) {
                if (q == null) {
                    return query.indices.query;
                }

                if (!isQuery(q)) {
                    throw new TypeError('Argument must be a Query');
                }

                query.indices.query = q.toJSON();
                return this;
            },

            /**
                  Sets the query to be used on an index that does not match an index
                  name in the indices list.  Can also be set to "none" to not match any
                  documents or "all" to match all documents.
      
                  @member ejs.IndicesQuery
                  @param {(Query|String)} q A valid Query object or "none" or "all"
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            noMatchQuery: function (q) {
                if (q == null) {
                    return query.indices.no_match_query;
                }

                if (isString(q)) {
                    q = q.toLowerCase();
                    if (q === 'none' || q === 'all') {
                        query.indices.no_match_query = q;
                    }
                } else if (isQuery(q)) {
                    query.indices.no_match_query = q.toJSON();
                } else {
                    throw new TypeError('Argument must be string or Query');
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>This query can be used to match all the documents
      in a given set of collections and/or types.</p>
  
      @name ejs.MatchAllQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      <p>A query that returns all documents.</p>
  
       */
    ejs.MatchAllQuery = function () {
        return ejs.QueryMixin('match_all');
    };

    /**
      @class
      A <code>MatchQuery</code> is a type of <code>Query</code> that accepts 
      text/numerics/dates, analyzes it, generates a query based on the
      <code>MatchQuery</code> type.
    
      @name ejs.MatchQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      A Query that appects text, analyzes it, generates internal query based
      on the MatchQuery type.
  
      @param {String} field the document field/field to query against
      @param {String} qstr the query string
      */
    ejs.MatchQuery = function (field, qstr) {

        var
          _common = ejs.QueryMixin('match'),
          query = _common.toJSON();

        query.match[field] = {
            query: qstr
        };

        return extend(_common, {

            /**
                  Sets the query string for the <code>Query</code>.
      
                  @member ejs.MatchQuery
                  @param {String} qstr The query string to search for.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (qstr) {
                if (qstr == null) {
                    return query.match[field].query;
                }

                query.match[field].query = qstr;
                return this;
            },

            /**
                  Sets the type of the <code>MatchQuery</code>.  Valid values are
                  boolean, phrase, and phrase_prefix.
      
                  @member ejs.MatchQuery
                  @param {String} type Any of boolean, phrase, phrase_prefix.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (type) {
                if (type == null) {
                    return query.match[field].type;
                }

                type = type.toLowerCase();
                if (type === 'boolean' || type === 'phrase' || type === 'phrase_prefix') {
                    query.match[field].type = type;
                }

                return this;
            },

            /**
                  Sets the fuzziness value for the <code>Query</code>.
      
                  @member ejs.MatchQuery
                  @param {Double} fuzz A <code>double</code> value between 0.0 and 1.0.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fuzziness: function (fuzz) {
                if (fuzz == null) {
                    return query.match[field].fuzziness;
                }

                query.match[field].fuzziness = fuzz;
                return this;
            },

            /**
                  Sets the maximum threshold/frequency to be considered a low 
                  frequency term in a <code>CommonTermsQuery</code>.  
                  Set to a value between 0 and 1.
      
                  @member ejs.MatchQuery
                  @param {Number} freq A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            cutoffFrequency: function (freq) {
                if (freq == null) {
                    return query.match[field].cutoff_frequency;
                }

                query.match[field].cutoff_frequency = freq;
                return this;
            },

            /**
                  Sets the prefix length for a fuzzy prefix <code>MatchQuery</code>.
      
                  @member ejs.MatchQuery
                  @param {Integer} l A positive <code>integer</code> length value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            prefixLength: function (l) {
                if (l == null) {
                    return query.match[field].prefix_length;
                }

                query.match[field].prefix_length = l;
                return this;
            },

            /**
                  Sets the max expansions of a fuzzy <code>MatchQuery</code>.
      
                  @member ejs.MatchQuery
                  @param {Integer} e A positive <code>integer</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxExpansions: function (e) {
                if (e == null) {
                    return query.match[field].max_expansions;
                }

                query.match[field].max_expansions = e;
                return this;
            },

            /**
                  Sets default operator of the <code>Query</code>.  Default: or.
      
                  @member ejs.MatchQuery
                  @param {String} op Any of "and" or "or", no quote characters.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            operator: function (op) {
                if (op == null) {
                    return query.match[field].operator;
                }

                op = op.toLowerCase();
                if (op === 'and' || op === 'or') {
                    query.match[field].operator = op;
                }

                return this;
            },

            /**
                  Sets the default slop for phrases. If zero, then exact phrase matches
                  are required.  Default: 0.
      
                  @member ejs.MatchQuery
                  @param {Integer} slop A positive <code>integer</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            slop: function (slop) {
                if (slop == null) {
                    return query.match[field].slop;
                }

                query.match[field].slop = slop;
                return this;
            },

            /**
                  Sets the analyzer name used to analyze the <code>Query</code> object.
      
                  @member ejs.MatchQuery
                  @param {String} analyzer A valid analyzer name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            analyzer: function (analyzer) {
                if (analyzer == null) {
                    return query.match[field].analyzer;
                }

                query.match[field].analyzer = analyzer;
                return this;
            },

            /**
                  Sets a percent value controlling how many "should" clauses in the
                  resulting <code>Query</code> should match.
      
                  @member ejs.MatchQuery
                  @param {Integer} minMatch An <code>integer</code> between 0 and 100.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minimumShouldMatch: function (minMatch) {
                if (minMatch == null) {
                    return query.match[field].minimum_should_match;
                }

                query.match[field].minimum_should_match = minMatch;
                return this;
            },

            /**
                  Sets rewrite method.  Valid values are: 
                  
                  constant_score_auto - tries to pick the best constant-score rewrite 
                    method based on term and document counts from the query
                    
                  scoring_boolean - translates each term into boolean should and 
                    keeps the scores as computed by the query
                    
                  constant_score_boolean - same as scoring_boolean, expect no scores
                    are computed.
                    
                  constant_score_filter - first creates a private Filter, by visiting 
                    each term in sequence and marking all docs for that term
                    
                  top_terms_boost_N - first translates each term into boolean should
                    and scores are only computed as the boost using the top N
                    scoring terms.  Replace N with an integer value.
                    
                  top_terms_N -   first translates each term into boolean should
                      and keeps the scores as computed by the query. Only the top N
                      scoring terms are used.  Replace N with an integer value.
                  
                  Default is constant_score_auto.
      
                  This is an advanced option, use with care.
      
                  @member ejs.MatchQuery
                  @param {String} m The rewrite method as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            rewrite: function (m) {
                if (m == null) {
                    return query.match[field].rewrite;
                }

                m = m.toLowerCase();
                if (m === 'constant_score_auto' || m === 'scoring_boolean' ||
                  m === 'constant_score_boolean' || m === 'constant_score_filter' ||
                  m.indexOf('top_terms_boost_') === 0 ||
                  m.indexOf('top_terms_') === 0) {

                    query.match[field].rewrite = m;
                }

                return this;
            },

            /**
                  Sets fuzzy rewrite method.  Valid values are: 
                  
                  constant_score_auto - tries to pick the best constant-score rewrite 
                    method based on term and document counts from the query
                    
                  scoring_boolean - translates each term into boolean should and 
                    keeps the scores as computed by the query
                    
                  constant_score_boolean - same as scoring_boolean, expect no scores
                    are computed.
                    
                  constant_score_filter - first creates a private Filter, by visiting 
                    each term in sequence and marking all docs for that term
                    
                  top_terms_boost_N - first translates each term into boolean should
                    and scores are only computed as the boost using the top N
                    scoring terms.  Replace N with an integer value.
                    
                  top_terms_N -   first translates each term into boolean should
                      and keeps the scores as computed by the query. Only the top N
                      scoring terms are used.  Replace N with an integer value.
                  
                  Default is constant_score_auto.
      
                  This is an advanced option, use with care.
                  
                  @member ejs.MatchQuery
                  @param {String} m The rewrite method as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fuzzyRewrite: function (m) {
                if (m == null) {
                    return query.match[field].fuzzy_rewrite;
                }

                m = m.toLowerCase();
                if (m === 'constant_score_auto' || m === 'scoring_boolean' ||
                  m === 'constant_score_boolean' || m === 'constant_score_filter' ||
                  m.indexOf('top_terms_boost_') === 0 ||
                  m.indexOf('top_terms_') === 0) {

                    query.match[field].fuzzy_rewrite = m;
                }

                return this;
            },

            /**
                  Set to false to use classic Levenshtein edit distance in the 
                  fuzzy query.
      
                  @member ejs.MatchQuery
                  @param {Boolean} trueFalse A boolean value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fuzzyTranspositions: function (trueFalse) {
                if (trueFalse == null) {
                    return query.match[field].fuzzy_transpositions;
                }

                query.match[field].fuzzy_transpositions = trueFalse;
                return this;
            },

            /**
                  Enables lenient parsing of the query string.
      
                  @member ejs.MatchQuery
                  @param {Boolean} trueFalse A boolean value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lenient: function (trueFalse) {
                if (trueFalse == null) {
                    return query.match[field].lenient;
                }

                query.match[field].lenient = trueFalse;
                return this;
            },

            /**
                  Sets what happens when no terms match.  Valid values are
                  "all" or "none".  
      
                  @member ejs.MatchQuery
                  @param {String} q A no match action, "all" or "none".
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            zeroTermsQuery: function (q) {
                if (q == null) {
                    return query.match[field].zero_terms_query;
                }

                q = q.toLowerCase();
                if (q === 'all' || q === 'none') {
                    query.match[field].zero_terms_query = q;
                }

                return this;
            },

            /**
                  Sets the boost value for documents matching the <code>Query</code>.
      
                  @member ejs.MatchQuery
                  @param {Number} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.match[field].boost;
                }

                query.match[field].boost = boost;
                return this;
            },

        });
    };

    /**
      @class
      <p>The more_like_this_field query is the same as the more_like_this query, 
      except it runs against a single field.</p>
  
      @name ejs.MoreLikeThisFieldQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      <p>Constructs a query where each documents returned are “like” provided text</p>
  
      @param {String} field The field to run the query against.
      @param {String} likeText The text to find documents like it.
  
       */
    ejs.MoreLikeThisFieldQuery = function (field, likeText) {

        var
          _common = ejs.QueryMixin('mlt_field'),
          query = _common.toJSON();

        query.mlt_field[field] = {
            like_text: likeText
        };

        return extend(_common, {

            /**
                   The field to run the query against.
      
                   @member ejs.MoreLikeThisFieldQuery
                   @param {String} f A single field name.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            field: function (f) {
                var oldValue = query.mlt_field[field];

                if (f == null) {
                    return field;
                }

                delete query.mlt_field[field];
                field = f;
                query.mlt_field[f] = oldValue;

                return this;
            },

            /**
                  The text to find documents like
      
                  @member ejs.MoreLikeThisFieldQuery
                  @param {String} s A text string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            likeText: function (txt) {
                if (txt == null) {
                    return query.mlt_field[field].like_text;
                }

                query.mlt_field[field].like_text = txt;
                return this;
            },

            /**
                  The percentage of terms to match on (float value). 
                  Defaults to 0.3 (30 percent).
      
                  @member ejs.MoreLikeThisFieldQuery
                  @param {Double} percent A double value between 0 and 1.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            percentTermsToMatch: function (percent) {
                if (percent == null) {
                    return query.mlt_field[field].percent_terms_to_match;
                }

                query.mlt_field[field].percent_terms_to_match = percent;
                return this;
            },

            /**
                  The frequency below which terms will be ignored in the source doc. 
                  The default frequency is 2.
      
                  @member ejs.MoreLikeThisFieldQuery
                  @param {Integer} freq A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minTermFreq: function (freq) {
                if (freq == null) {
                    return query.mlt_field[field].min_term_freq;
                }

                query.mlt_field[field].min_term_freq = freq;
                return this;
            },

            /**
                  The maximum number of query terms that will be included in any 
                  generated query. Defaults to 25.
      
                  @member ejs.MoreLikeThisFieldQuery
                  @param {Integer} max A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxQueryTerms: function (max) {
                if (max == null) {
                    return query.mlt_field[field].max_query_terms;
                }

                query.mlt_field[field].max_query_terms = max;
                return this;
            },

            /**
                  An array of stop words. Any word in this set is considered 
                  “uninteresting” and ignored. Even if your Analyzer allows stopwords, 
                  you might want to tell the MoreLikeThis code to ignore them, as for 
                  the purposes of document similarity it seems reasonable to assume 
                  that “a stop word is never interesting”.
              
                  @member ejs.MoreLikeThisFieldQuery
                  @param {Array} stopWords An array of string stopwords
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            stopWords: function (stopWords) {
                if (stopWords == null) {
                    return query.mlt_field[field].stop_words;
                }

                query.mlt_field[field].stop_words = stopWords;
                return this;
            },

            /**
                  The frequency at which words will be ignored which do not occur in 
                  at least this many docs. Defaults to 5.
      
                  @member ejs.MoreLikeThisFieldQuery
                  @param {Integer} min A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minDocFreq: function (min) {
                if (min == null) {
                    return query.mlt_field[field].min_doc_freq;
                }

                query.mlt_field[field].min_doc_freq = min;
                return this;
            },

            /**
                  The maximum frequency in which words may still appear. Words that 
                  appear in more than this many docs will be ignored. 
                  Defaults to unbounded.
      
                  @member ejs.MoreLikeThisFieldQuery
                  @param {Integer} max A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxDocFreq: function (max) {
                if (max == null) {
                    return query.mlt_field[field].max_doc_freq;
                }

                query.mlt_field[field].max_doc_freq = max;
                return this;
            },

            /**
                  The minimum word length below which words will be ignored. 
                  Defaults to 0.
              
                  @member ejs.MoreLikeThisFieldQuery
                  @param {Integer} len A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minWordLen: function (len) {
                if (len == null) {
                    return query.mlt_field[field].min_word_len;
                }

                query.mlt_field[field].min_word_len = len;
                return this;
            },

            /**
                  The maximum word length above which words will be ignored. 
                  Defaults to unbounded (0).
              
                  @member ejs.MoreLikeThisFieldQuery
                  @param {Integer} len A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxWordLen: function (len) {
                if (len == null) {
                    return query.mlt_field[field].max_word_len;
                }

                query.mlt_field[field].max_word_len = len;
                return this;
            },

            /**
                  The analyzer that will be used to analyze the text. Defaults to the 
                  analyzer associated with the field.
      
                  @member ejs.MoreLikeThisFieldQuery
                  @param {String} analyzerName The name of the analyzer.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            analyzer: function (analyzerName) {
                if (analyzerName == null) {
                    return query.mlt_field[field].analyzer;
                }

                query.mlt_field[field].analyzer = analyzerName;
                return this;
            },

            /**
                  Sets the boost factor to use when boosting terms. 
                  Defaults to 1.
      
                  @member ejs.MoreLikeThisFieldQuery
                  @param {Double} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boostTerms: function (boost) {
                if (boost == null) {
                    return query.mlt_field[field].boost_terms;
                }

                query.mlt_field[field].boost_terms = boost;
                return this;
            },

            /**
                  Should the <code>Query</code> fail when an unsupported field
                  is specified. Defaults to true.
      
                  @member ejs.MoreLikeThisFieldQuery
                  @param {Boolean} trueFalse A boolean value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            failOnUnsupportedField: function (trueFalse) {
                if (trueFalse == null) {
                    return query.mlt_field[field].fail_on_unsupported_field;
                }

                query.mlt_field[field].fail_on_unsupported_field = trueFalse;
                return this;
            },

            /**
                  Sets the boost value of the <code>Query</code>.
      
                  @member ejs.MoreLikeThisFieldQuery
                  @param {Double} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.mlt_field[field].boost;
                }

                query.mlt_field[field].boost = boost;
                return this;
            }

        });
    };

    /**
      @class
      <p>More like this query find documents that are “like” provided text by 
      running it against one or more fields.</p>
  
      @name ejs.MoreLikeThisQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      <p>Constructs a query where each documents returned are “like” provided text</p>
  
      @param {(String|String[])} fields A single field or array of fields to run against.
      @param {String} likeText The text to find documents like it.
    
       */
    ejs.MoreLikeThisQuery = function (fields, likeText) {

        var
          _common = ejs.QueryMixin('mlt'),
          query = _common.toJSON();

        query.mlt.like_text = likeText;
        query.mlt.fields = [];

        if (isString(fields)) {
            query.mlt.fields.push(fields);
        } else if (isArray(fields)) {
            query.mlt.fields = fields;
        } else {
            throw new TypeError('Argument must be string or array');
        }

        return extend(_common, {

            /**
                   The fields to run the query against.  If you call with a single field,
                   it is added to the existing list of fields.  If called with an array
                   of field names, it replaces any existing values with the new array.
      
                   @member ejs.MoreLikeThisQuery
                   @param {(String|String[])} f A single field name or a list of field names.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            fields: function (f) {
                if (f == null) {
                    return query.mlt.fields;
                }

                if (isString(f)) {
                    query.mlt.fields.push(f);
                } else if (isArray(f)) {
                    query.mlt.fields = f;
                } else {
                    throw new TypeError('Argument must be a string or array');
                }

                return this;
            },

            /**
                  The text to find documents like
      
                  @member ejs.MoreLikeThisQuery
                  @param {String} s A text string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            likeText: function (txt) {
                if (txt == null) {
                    return query.mlt.like_text;
                }

                query.mlt.like_text = txt;
                return this;
            },

            /**
                  The percentage of terms to match on (float value). 
                  Defaults to 0.3 (30 percent).
      
                  @member ejs.MoreLikeThisQuery
                  @param {Double} percent A double value between 0 and 1.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            percentTermsToMatch: function (percent) {
                if (percent == null) {
                    return query.mlt.percent_terms_to_match;
                }

                query.mlt.percent_terms_to_match = percent;
                return this;
            },

            /**
                  The frequency below which terms will be ignored in the source doc. 
                  The default frequency is 2.
      
                  @member ejs.MoreLikeThisQuery
                  @param {Integer} freq A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minTermFreq: function (freq) {
                if (freq == null) {
                    return query.mlt.min_term_freq;
                }

                query.mlt.min_term_freq = freq;
                return this;
            },

            /**
                  The maximum number of query terms that will be included in any 
                  generated query. Defaults to 25.
      
                  @member ejs.MoreLikeThisQuery
                  @param {Integer} max A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxQueryTerms: function (max) {
                if (max == null) {
                    return query.mlt.max_query_terms;
                }

                query.mlt.max_query_terms = max;
                return this;
            },

            /**
                  An array of stop words. Any word in this set is considered 
                  “uninteresting” and ignored. Even if your Analyzer allows stopwords, 
                  you might want to tell the MoreLikeThis code to ignore them, as for 
                  the purposes of document similarity it seems reasonable to assume 
                  that “a stop word is never interesting”.
                
                  @member ejs.MoreLikeThisQuery
                  @param {Array} stopWords An array of string stopwords
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            stopWords: function (stopWords) {
                if (stopWords == null) {
                    return query.mlt.stop_words;
                }

                query.mlt.stop_words = stopWords;
                return this;
            },

            /**
                  The frequency at which words will be ignored which do not occur in 
                  at least this many docs. Defaults to 5.
      
                  @member ejs.MoreLikeThisQuery
                  @param {Integer} min A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minDocFreq: function (min) {
                if (min == null) {
                    return query.mlt.min_doc_freq;
                }

                query.mlt.min_doc_freq = min;
                return this;
            },

            /**
                  The maximum frequency in which words may still appear. Words that 
                  appear in more than this many docs will be ignored. 
                  Defaults to unbounded.
      
                  @member ejs.MoreLikeThisQuery
                  @param {Integer} max A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxDocFreq: function (max) {
                if (max == null) {
                    return query.mlt.max_doc_freq;
                }

                query.mlt.max_doc_freq = max;
                return this;
            },

            /**
                  The minimum word length below which words will be ignored. 
                  Defaults to 0.
                
                  @member ejs.MoreLikeThisQuery
                  @param {Integer} len A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minWordLen: function (len) {
                if (len == null) {
                    return query.mlt.min_word_len;
                }

                query.mlt.min_word_len = len;
                return this;
            },

            /**
                  The maximum word length above which words will be ignored. 
                  Defaults to unbounded (0).
                
                  @member ejs.MoreLikeThisQuery
                  @param {Integer} len A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxWordLen: function (len) {
                if (len == null) {
                    return query.mlt.max_word_len;
                }

                query.mlt.max_word_len = len;
                return this;
            },

            /**
                  The analyzer that will be used to analyze the text. Defaults to the 
                  analyzer associated with the field.
      
                  @member ejs.MoreLikeThisQuery
                  @param {String} analyzerName The name of the analyzer.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            analyzer: function (analyzerName) {
                if (analyzerName == null) {
                    return query.mlt.analyzer;
                }

                query.mlt.analyzer = analyzerName;
                return this;
            },

            /**
                  Sets the boost factor to use when boosting terms. 
                  Defaults to 1.
      
                  @member ejs.MoreLikeThisQuery
                  @param {Double} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boostTerms: function (boost) {
                if (boost == null) {
                    return query.mlt.boost_terms;
                }

                query.mlt.boost_terms = boost;
                return this;
            },

            /**
                  Should the <code>Query</code> fail when an unsupported field
                  is specified. Defaults to true.
      
                  @member ejs.MoreLikeThisQuery
                  @param {Boolean} trueFalse A boolean value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            failOnUnsupportedField: function (trueFalse) {
                if (trueFalse == null) {
                    return query.mlt.fail_on_unsupported_field;
                }

                query.mlt.fail_on_unsupported_field = trueFalse;
                return this;
            }

        });
    };

    /**
      @class
      A <code>MultiMatchQuery</code> query builds further on top of the 
      <code>MatchQuery</code> by allowing multiple fields to be specified. 
      The idea here is to allow to more easily build a concise match type query 
      over multiple fields instead of using a relatively more expressive query 
      by using multiple match queries within a bool query.
    
      @name ejs.MultiMatchQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      A Query that allow to more easily build a MatchQuery 
      over multiple fields
  
      @param {(String|String[])} fields the single field or array of fields to search across
      @param {String} qstr the query string
      */
    ejs.MultiMatchQuery = function (fields, qstr) {

        var
          _common = ejs.QueryMixin('multi_match'),
          query = _common.toJSON();

        query.multi_match.query = qstr;
        query.multi_match.fields = [];

        if (isString(fields)) {
            query.multi_match.fields.push(fields);
        } else if (isArray(fields)) {
            query.multi_match.fields = fields;
        } else {
            throw new TypeError('Argument must be string or array');
        }

        return extend(_common, {

            /**
                  Sets the fields to search across.  If passed a single value it is
                  added to the existing list of fields.  If passed an array of 
                  values, they overwite all existing values.
      
                  @member ejs.MultiMatchQuery
                  @param {(String|String[])} f A single field or list of fields names to 
                    search across.
                  @returns {Object} returns <code>this</code> so that calls can be 
                    chained. Returns {Array} current value if `f` not specified.
                  */
            fields: function (f) {
                if (f == null) {
                    return query.multi_match.fields;
                }

                if (isString(f)) {
                    query.multi_match.fields.push(f);
                } else if (isArray(f)) {
                    query.multi_match.fields = f;
                } else {
                    throw new TypeError('Argument must be string or array');
                }

                return this;
            },

            /**
                  Sets whether or not queries against multiple fields should be combined using Lucene's
                  <a href="http://lucene.apache.org/java/3_0_0/api/core/org/apache/lucene/search/DisjunctionMaxQuery.html">
                  DisjunctionMaxQuery</a>
      
                  @member ejs.MultiMatchQuery
                  @param {String} trueFalse A <code>true/false</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            useDisMax: function (trueFalse) {
                if (trueFalse == null) {
                    return query.multi_match.use_dis_max;
                }

                query.multi_match.use_dis_max = trueFalse;
                return this;
            },

            /**
                  The tie breaker value.  The tie breaker capability allows results
                  that include the same term in multiple fields to be judged better than
                  results that include this term in only the best of those multiple
                  fields, without confusing this with the better case of two different
                  terms in the multiple fields.  Default: 0.0.
      
                  @member ejs.MultiMatchQuery
                  @param {Double} tieBreaker A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            tieBreaker: function (tieBreaker) {
                if (tieBreaker == null) {
                    return query.multi_match.tie_breaker;
                }

                query.multi_match.tie_breaker = tieBreaker;
                return this;
            },

            /**
                  Sets the maximum threshold/frequency to be considered a low 
                  frequency term in a <code>CommonTermsQuery</code>.  
                  Set to a value between 0 and 1.
      
                  @member ejs.MultiMatchQuery
                  @param {Number} freq A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            cutoffFrequency: function (freq) {
                if (freq == null) {
                    return query.multi_match.cutoff_frequency;
                }

                query.multi_match.cutoff_frequency = freq;
                return this;
            },

            /**
                  Sets a percent value controlling how many "should" clauses in the
                  resulting <code>Query</code> should match.
      
                  @member ejs.MultiMatchQuery
                  @param {Integer} minMatch An <code>integer</code> between 0 and 100.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minimumShouldMatch: function (minMatch) {
                if (minMatch == null) {
                    return query.multi_match.minimum_should_match;
                }

                query.multi_match.minimum_should_match = minMatch;
                return this;
            },

            /**
                  Sets rewrite method.  Valid values are: 
                  
                  constant_score_auto - tries to pick the best constant-score rewrite 
                    method based on term and document counts from the query
                    
                  scoring_boolean - translates each term into boolean should and 
                    keeps the scores as computed by the query
                    
                  constant_score_boolean - same as scoring_boolean, expect no scores
                    are computed.
                    
                  constant_score_filter - first creates a private Filter, by visiting 
                    each term in sequence and marking all docs for that term
                    
                  top_terms_boost_N - first translates each term into boolean should
                    and scores are only computed as the boost using the top N
                    scoring terms.  Replace N with an integer value.
                    
                  top_terms_N -   first translates each term into boolean should
                      and keeps the scores as computed by the query. Only the top N
                      scoring terms are used.  Replace N with an integer value.
                  
                  Default is constant_score_auto.
      
                  This is an advanced option, use with care.
      
                  @member ejs.MultiMatchQuery
                  @param {String} m The rewrite method as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            rewrite: function (m) {
                if (m == null) {
                    return query.multi_match.rewrite;
                }

                m = m.toLowerCase();
                if (m === 'constant_score_auto' || m === 'scoring_boolean' ||
                  m === 'constant_score_boolean' || m === 'constant_score_filter' ||
                  m.indexOf('top_terms_boost_') === 0 ||
                  m.indexOf('top_terms_') === 0) {

                    query.multi_match.rewrite = m;
                }

                return this;
            },

            /**
                  Sets fuzzy rewrite method.  Valid values are: 
                  
                  constant_score_auto - tries to pick the best constant-score rewrite 
                    method based on term and document counts from the query
                    
                  scoring_boolean - translates each term into boolean should and 
                    keeps the scores as computed by the query
                    
                  constant_score_boolean - same as scoring_boolean, expect no scores
                    are computed.
                    
                  constant_score_filter - first creates a private Filter, by visiting 
                    each term in sequence and marking all docs for that term
                    
                  top_terms_boost_N - first translates each term into boolean should
                    and scores are only computed as the boost using the top N
                    scoring terms.  Replace N with an integer value.
                    
                  top_terms_N -   first translates each term into boolean should
                      and keeps the scores as computed by the query. Only the top N
                      scoring terms are used.  Replace N with an integer value.
                  
                  Default is constant_score_auto.
      
                  This is an advanced option, use with care.
                  
                  @member ejs.MultiMatchQuery
                  @param {String} m The rewrite method as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fuzzyRewrite: function (m) {
                if (m == null) {
                    return query.multi_match.fuzzy_rewrite;
                }

                m = m.toLowerCase();
                if (m === 'constant_score_auto' || m === 'scoring_boolean' ||
                  m === 'constant_score_boolean' || m === 'constant_score_filter' ||
                  m.indexOf('top_terms_boost_') === 0 ||
                  m.indexOf('top_terms_') === 0) {

                    query.multi_match.fuzzy_rewrite = m;
                }

                return this;
            },

            /**
                  Enables lenient parsing of the query string.
      
                  @member ejs.MultiMatchQuery
                  @param {Boolean} trueFalse A boolean value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lenient: function (trueFalse) {
                if (trueFalse == null) {
                    return query.multi_match.lenient;
                }

                query.multi_match.lenient = trueFalse;
                return this;
            },

            /**
                  Sets the query string for the <code>Query</code>.
      
                  @member ejs.MultiMatchQuery
                  @param {String} qstr The query string to search for.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (qstr) {
                if (qstr == null) {
                    return query.multi_match.query;
                }

                query.multi_match.query = qstr;
                return this;
            },

            /**
                  Sets the type of the <code>MultiMatchQuery</code>.  Valid values are
                  boolean, phrase, and phrase_prefix or phrasePrefix.
      
                  @member ejs.MultiMatchQuery
                  @param {String} type Any of boolean, phrase, phrase_prefix or phrasePrefix.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (type) {
                if (type == null) {
                    return query.multi_match.type;
                }

                type = type.toLowerCase();
                if (type === 'boolean' || type === 'phrase' || type === 'phrase_prefix') {
                    query.multi_match.type = type;
                }

                return this;
            },

            /**
                  Sets the fuzziness value for the <code>Query</code>.
      
                  @member ejs.MultiMatchQuery
                  @param {Double} fuzz A <code>double</code> value between 0.0 and 1.0.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fuzziness: function (fuzz) {
                if (fuzz == null) {
                    return query.multi_match.fuzziness;
                }

                query.multi_match.fuzziness = fuzz;
                return this;
            },

            /**
                  Sets the prefix length for a fuzzy prefix <code>Query</code>.
      
                  @member ejs.MultiMatchQuery
                  @param {Integer} l A positive <code>integer</code> length value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            prefixLength: function (l) {
                if (l == null) {
                    return query.multi_match.prefix_length;
                }

                query.multi_match.prefix_length = l;
                return this;
            },

            /**
                  Sets the max expansions of a fuzzy <code>Query</code>.
      
                  @member ejs.MultiMatchQuery
                  @param {Integer} e A positive <code>integer</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxExpansions: function (e) {
                if (e == null) {
                    return query.multi_match.max_expansions;
                }

                query.multi_match.max_expansions = e;
                return this;
            },

            /**
                  Sets default operator of the <code>Query</code>.  Default: or.
      
                  @member ejs.MultiMatchQuery
                  @param {String} op Any of "and" or "or", no quote characters.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            operator: function (op) {
                if (op == null) {
                    return query.multi_match.operator;
                }

                op = op.toLowerCase();
                if (op === 'and' || op === 'or') {
                    query.multi_match.operator = op;
                }

                return this;
            },

            /**
                  Sets the default slop for phrases. If zero, then exact phrase matches
                  are required.  Default: 0.
      
                  @member ejs.MultiMatchQuery
                  @param {Integer} slop A positive <code>integer</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            slop: function (slop) {
                if (slop == null) {
                    return query.multi_match.slop;
                }

                query.multi_match.slop = slop;
                return this;
            },

            /**
                  Sets the analyzer name used to analyze the <code>Query</code> object.
      
                  @member ejs.MultiMatchQuery
                  @param {String} analyzer A valid analyzer name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            analyzer: function (analyzer) {
                if (analyzer == null) {
                    return query.multi_match.analyzer;
                }

                query.multi_match.analyzer = analyzer;
                return this;
            },

            /**
                  Sets what happens when no terms match.  Valid values are
                  "all" or "none".  
      
                  @member ejs.MultiMatchQuery
                  @param {String} q A no match action, "all" or "none".
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            zeroTermsQuery: function (q) {
                if (q == null) {
                    return query.multi_match.zero_terms_query;
                }

                q = q.toLowerCase();
                if (q === 'all' || q === 'none') {
                    query.multi_match.zero_terms_query = q;
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>Nested queries allow you to search against content within objects that are
         embedded inside of other objects. It is similar to <code>XPath</code> expressions
         in <code>XML</code> both conceptually and syntactically.</p>
  
      <p>The query is executed against the nested objects / docs as if they were 
      indexed as separate docs and resulting in the rootparent doc (or parent 
      nested mapping).</p>
      
      @name ejs.NestedQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      <p>Constructs a query that is capable of executing a search against objects
         nested within a document.</p>
  
      @param {String} path The nested object path.
  
       */
    ejs.NestedQuery = function (path) {

        var
          _common = ejs.QueryMixin('nested'),
          query = _common.toJSON();

        query.nested.path = path;

        return extend(_common, {

            /**
                   Sets the root context for the nested query.
                   
                   @member ejs.NestedQuery
                   @param {String} path The path defining the root context for the nested query.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            path: function (path) {
                if (path == null) {
                    return query.nested.path;
                }

                query.nested.path = path;
                return this;
            },

            /**
                   Sets the nested query to be executed.
                   
                   @member ejs.NestedQuery
                   @param {Object} oQuery A valid Query object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            query: function (oQuery) {
                if (oQuery == null) {
                    return query.nested.query;
                }

                if (!isQuery(oQuery)) {
                    throw new TypeError('Argument must be a Query');
                }

                query.nested.query = oQuery.toJSON();
                return this;
            },


            /**
                   Sets the nested filter to be executed.
                   
                   @member ejs.NestedQuery
                   @param {Object} oFilter A valid Filter object
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            filter: function (oFilter) {
                if (oFilter == null) {
                    return query.nested.filter;
                }

                if (!isFilter(oFilter)) {
                    throw new TypeError('Argument must be a Filter');
                }

                query.nested.filter = oFilter.toJSON();
                return this;
            },

            /**
                   Sets how the inner (nested) matches affect scoring on the parent document.
                   
                   @member ejs.NestedQuery
                   @param {String} mode The mode of scoring to be used for nested matches.
                                   Options are avg, total, max, none - defaults to avg
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            scoreMode: function (mode) {
                if (mode == null) {
                    return query.nested.score_mode;
                }

                mode = mode.toLowerCase();
                if (mode === 'avg' || mode === 'total' || mode === 'max' ||
                  mode === 'none' || mode === 'sum') {

                    query.nested.score_mode = mode;
                }

                return this;
            },

            /**
                  Sets the scope of the query.  A scope allows to run facets on the 
                  same scope name that will work against the nested documents. 
      
                  @deprecated since elasticsearch 0.90
                  @member ejs.NestedQuery
                  @param {String} s The scope name as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scope: function (s) {
                return this;
            }

        });
    };

    /**
      @class
      <p>Matches documents that have fields containing terms with a specified 
      prefix (not analyzed). The prefix query maps to Lucene PrefixQuery.</p>
  
      @name ejs.PrefixQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Matches documents containing the specified un-analyzed prefix.
  
      @param {String} field A valid field name.
      @param {String} value A string prefix.
      */
    ejs.PrefixQuery = function (field, value) {

        var
          _common = ejs.QueryMixin('prefix'),
          query = _common.toJSON();

        query.prefix[field] = {
            value: value
        };

        return extend(_common, {

            /**
                   The field to run the query against.
      
                   @member ejs.PrefixQuery
                   @param {String} f A single field name.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            field: function (f) {
                var oldValue = query.prefix[field];

                if (f == null) {
                    return field;
                }

                delete query.prefix[field];
                field = f;
                query.prefix[f] = oldValue;

                return this;
            },

            /**
                  The prefix value.
      
                  @member ejs.PrefixQuery
                  @param {String} p A string prefix
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            value: function (p) {
                if (p == null) {
                    return query.prefix[field].value;
                }

                query.prefix[field].value = p;
                return this;
            },

            /**
                  Sets rewrite method.  Valid values are: 
                  
                  constant_score_auto - tries to pick the best constant-score rewrite 
                    method based on term and document counts from the query
                    
                  scoring_boolean - translates each term into boolean should and 
                    keeps the scores as computed by the query
                    
                  constant_score_boolean - same as scoring_boolean, expect no scores
                    are computed.
                    
                  constant_score_filter - first creates a private Filter, by visiting 
                    each term in sequence and marking all docs for that term
                    
                  top_terms_boost_N - first translates each term into boolean should
                    and scores are only computed as the boost using the top N
                    scoring terms.  Replace N with an integer value.
                    
                  top_terms_N -   first translates each term into boolean should
                      and keeps the scores as computed by the query. Only the top N
                      scoring terms are used.  Replace N with an integer value.
                  
                  Default is constant_score_auto.
      
                  This is an advanced option, use with care.
      
                  @member ejs.PrefixQuery
                  @param {String} m The rewrite method as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            rewrite: function (m) {
                if (m == null) {
                    return query.prefix[field].rewrite;
                }

                m = m.toLowerCase();
                if (m === 'constant_score_auto' || m === 'scoring_boolean' ||
                  m === 'constant_score_boolean' || m === 'constant_score_filter' ||
                  m.indexOf('top_terms_boost_') === 0 ||
                  m.indexOf('top_terms_') === 0) {

                    query.prefix[field].rewrite = m;
                }

                return this;
            },

            /**
                  Sets the boost value of the <code>Query</code>.
      
                  @member ejs.PrefixQuery
                  @param {Double} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.prefix[field].boost;
                }

                query.prefix[field].boost = boost;
                return this;
            }

        });
    };

    /**
      @class
      <p>A query that is parsed using Lucene's default query parser. Although Lucene provides the
      ability to create your own queries through its API, it also provides a rich query language
      through the Query Parser, a lexer which interprets a string into a Lucene Query.</p>
  
      </p>See the Lucene <a href="http://lucene.apache.org/java/2_9_1/queryparsersyntax.html">Query Parser Syntax</a>
      for more information.</p>
  
      @name ejs.QueryStringQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      A query that is parsed using Lucene's default query parser.
  
      @param {String} qstr A valid Lucene query string.
      */
    ejs.QueryStringQuery = function (qstr) {

        var
          _common = ejs.QueryMixin('query_string'),
          query = _common.toJSON();

        query.query_string.query = qstr;

        return extend(_common, {

            /**
                  Sets the query string on this <code>Query</code> object.
      
                  @member ejs.QueryStringQuery
                  @param {String} qstr A valid Lucene query string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (qstr) {
                if (qstr == null) {
                    return query.query_string.query;
                }

                query.query_string.query = qstr;
                return this;
            },

            /**
                  Sets the default field/property this query should execute against.
      
                  @member ejs.QueryStringQuery
                  @param {String} fieldName The name of document field/property.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            defaultField: function (fieldName) {
                if (fieldName == null) {
                    return query.query_string.default_field;
                }

                query.query_string.default_field = fieldName;
                return this;
            },

            /**
                  A set of fields/properties this query should execute against.  
                  Pass a single value to add to the existing list of fields and 
                  pass an array to overwrite all existing fields.  For each field, 
                  you can apply a field specific boost by appending a ^boost to the 
                  field name.  For example, title^10, to give the title field a
                  boost of 10.
      
                  @member ejs.QueryStringQuery
                  @param {Array} fieldNames A list of document fields/properties.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fields: function (fieldNames) {
                if (query.query_string.fields == null) {
                    query.query_string.fields = [];
                }

                if (fieldNames == null) {
                    return query.query_string.fields;
                }

                if (isString(fieldNames)) {
                    query.query_string.fields.push(fieldNames);
                } else if (isArray(fieldNames)) {
                    query.query_string.fields = fieldNames;
                } else {
                    throw new TypeError('Argument must be a string or array');
                }

                return this;
            },

            /**
                  Sets whether or not queries against multiple fields should be combined using Lucene's
                  <a href="http://lucene.apache.org/java/3_0_0/api/core/org/apache/lucene/search/DisjunctionMaxQuery.html">
                  DisjunctionMaxQuery</a>
      
                  @member ejs.QueryStringQuery
                  @param {String} trueFalse A <code>true/false</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            useDisMax: function (trueFalse) {
                if (trueFalse == null) {
                    return query.query_string.use_dis_max;
                }

                query.query_string.use_dis_max = trueFalse;
                return this;
            },

            /**
                  Set the default <em>Boolean</em> operator. This operator is used to join individual query
                  terms when no operator is explicity used in the query string (i.e., <code>this AND that</code>).
                  Defaults to <code>OR</code>.
      
                  @member ejs.QueryStringQuery
                  @param {String} op The operator to use, AND or OR.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            defaultOperator: function (op) {
                if (op == null) {
                    return query.query_string.default_operator;
                }

                op = op.toUpperCase();
                if (op === 'AND' || op === 'OR') {
                    query.query_string.default_operator = op;
                }

                return this;
            },

            /**
                  Sets the analyzer name used to analyze the <code>Query</code> object.
      
                  @member ejs.QueryStringQuery
                  @param {String} analyzer A valid analyzer name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            analyzer: function (analyzer) {
                if (analyzer == null) {
                    return query.query_string.analyzer;
                }

                query.query_string.analyzer = analyzer;
                return this;
            },

            /**
                  Sets the quote analyzer name used to analyze the <code>query</code>
                  when in quoted text.
      
                  @member ejs.QueryStringQuery
                  @param {String} analyzer A valid analyzer name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            quoteAnalyzer: function (analyzer) {
                if (analyzer == null) {
                    return query.query_string.quote_analyzer;
                }

                query.query_string.quote_analyzer = analyzer;
                return this;
            },

            /**
                  Sets whether or not wildcard characters (* and ?) are allowed as the
                  first character of the <code>Query</code>.  Default: true.
      
                  @member ejs.QueryStringQuery
                  @param {Boolean} trueFalse A <code>true/false</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            allowLeadingWildcard: function (trueFalse) {
                if (trueFalse == null) {
                    return query.query_string.allow_leading_wildcard;
                }

                query.query_string.allow_leading_wildcard = trueFalse;
                return this;
            },

            /**
                  Sets whether or not terms from wildcard, prefix, fuzzy, and
                  range queries should automatically be lowercased in the <code>Query</code>
                  since they are not analyzed.  Default: true.
      
                  @member ejs.QueryStringQuery
                  @param {Boolean} trueFalse A <code>true/false</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lowercaseExpandedTerms: function (trueFalse) {
                if (trueFalse == null) {
                    return query.query_string.lowercase_expanded_terms;
                }

                query.query_string.lowercase_expanded_terms = trueFalse;
                return this;
            },

            /**
                  Sets whether or not position increments will be used in the
                  <code>Query</code>. Default: true.
      
                  @member ejs.QueryStringQuery
                  @param {Boolean} trueFalse A <code>true/false</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            enablePositionIncrements: function (trueFalse) {
                if (trueFalse == null) {
                    return query.query_string.enable_position_increments;
                }

                query.query_string.enable_position_increments = trueFalse;
                return this;
            },


            /**
                  Sets the prefix length for fuzzy queries.  Default: 0.
      
                  @member ejs.QueryStringQuery
                  @param {Integer} fuzzLen A positive <code>integer</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fuzzyPrefixLength: function (fuzzLen) {
                if (fuzzLen == null) {
                    return query.query_string.fuzzy_prefix_length;
                }

                query.query_string.fuzzy_prefix_length = fuzzLen;
                return this;
            },

            /**
                  Set the minimum similarity for fuzzy queries.  Default: 0.5.
      
                  @member ejs.QueryStringQuery
                  @param {Double} minSim A <code>double</code> value between 0 and 1.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fuzzyMinSim: function (minSim) {
                if (minSim == null) {
                    return query.query_string.fuzzy_min_sim;
                }

                query.query_string.fuzzy_min_sim = minSim;
                return this;
            },

            /**
                  Sets the default slop for phrases. If zero, then exact phrase matches
                  are required.  Default: 0.
      
                  @member ejs.QueryStringQuery
                  @param {Integer} slop A positive <code>integer</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            phraseSlop: function (slop) {
                if (slop == null) {
                    return query.query_string.phrase_slop;
                }

                query.query_string.phrase_slop = slop;
                return this;
            },

            /**
                  Sets whether or not we should attempt to analyzed wilcard terms in the
                  <code>Query</code>. By default, wildcard terms are not analyzed.
                  Analysis of wildcard characters is not perfect.  Default: false.
      
                  @member ejs.QueryStringQuery
                  @param {Boolean} trueFalse A <code>true/false</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            analyzeWildcard: function (trueFalse) {
                if (trueFalse == null) {
                    return query.query_string.analyze_wildcard;
                }

                query.query_string.analyze_wildcard = trueFalse;
                return this;
            },

            /**
                  Sets whether or not we should auto generate phrase queries *if* the
                  analyzer returns more than one term. Default: false.
      
                  @member ejs.QueryStringQuery
                  @param {Boolean} trueFalse A <code>true/false</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            autoGeneratePhraseQueries: function (trueFalse) {
                if (trueFalse == null) {
                    return query.query_string.auto_generate_phrase_queries;
                }

                query.query_string.auto_generate_phrase_queries = trueFalse;
                return this;
            },

            /**
                  Sets a percent value controlling how many "should" clauses in the
                  resulting <code>Query</code> should match.
      
                  @member ejs.QueryStringQuery
                  @param {Integer} minMatch An <code>integer</code> between 0 and 100.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minimumShouldMatch: function (minMatch) {
                if (minMatch == null) {
                    return query.query_string.minimum_should_match;
                }

                query.query_string.minimum_should_match = minMatch;
                return this;
            },

            /**
                  Sets the tie breaker value for a <code>Query</code> using
                  <code>DisMax</code>.  The tie breaker capability allows results
                  that include the same term in multiple fields to be judged better than
                  results that include this term in only the best of those multiple
                  fields, without confusing this with the better case of two different
                  terms in the multiple fields.  Default: 0.0.
      
                  @member ejs.QueryStringQuery
                  @param {Double} tieBreaker A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            tieBreaker: function (tieBreaker) {
                if (tieBreaker == null) {
                    return query.query_string.tie_breaker;
                }

                query.query_string.tie_breaker = tieBreaker;
                return this;
            },

            /**
                  If they query string should be escaped or not.
      
                  @member ejs.QueryStringQuery
                  @param {Boolean} trueFalse A <code>true/false</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            escape: function (trueFalse) {
                if (trueFalse == null) {
                    return query.query_string.escape;
                }

                query.query_string.escape = trueFalse;
                return this;
            },

            /**
                  Sets the max number of term expansions for fuzzy queries.  
      
                  @member ejs.QueryStringQuery
                  @param {Integer} max A positive <code>integer</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fuzzyMaxExpansions: function (max) {
                if (max == null) {
                    return query.query_string.fuzzy_max_expansions;
                }

                query.query_string.fuzzy_max_expansions = max;
                return this;
            },

            /**
                  Sets fuzzy rewrite method.  Valid values are: 
                  
                  constant_score_auto - tries to pick the best constant-score rewrite 
                    method based on term and document counts from the query
                    
                  scoring_boolean - translates each term into boolean should and 
                    keeps the scores as computed by the query
                    
                  constant_score_boolean - same as scoring_boolean, expect no scores
                    are computed.
                    
                  constant_score_filter - first creates a private Filter, by visiting 
                    each term in sequence and marking all docs for that term
                    
                  top_terms_boost_N - first translates each term into boolean should
                    and scores are only computed as the boost using the top N
                    scoring terms.  Replace N with an integer value.
                    
                  top_terms_N -   first translates each term into boolean should
                      and keeps the scores as computed by the query. Only the top N
                      scoring terms are used.  Replace N with an integer value.
                  
                  Default is constant_score_auto.
      
                  This is an advanced option, use with care.
                  
                  @member ejs.QueryStringQuery
                  @param {String} m The rewrite method as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fuzzyRewrite: function (m) {
                if (m == null) {
                    return query.query_string.fuzzy_rewrite;
                }

                m = m.toLowerCase();
                if (m === 'constant_score_auto' || m === 'scoring_boolean' ||
                  m === 'constant_score_boolean' || m === 'constant_score_filter' ||
                  m.indexOf('top_terms_boost_') === 0 ||
                  m.indexOf('top_terms_') === 0) {

                    query.query_string.fuzzy_rewrite = m;
                }

                return this;
            },

            /**
                  Sets rewrite method.  Valid values are: 
                  
                  constant_score_auto - tries to pick the best constant-score rewrite 
                    method based on term and document counts from the query
                    
                  scoring_boolean - translates each term into boolean should and 
                    keeps the scores as computed by the query
                    
                  constant_score_boolean - same as scoring_boolean, expect no scores
                    are computed.
                    
                  constant_score_filter - first creates a private Filter, by visiting 
                    each term in sequence and marking all docs for that term
                    
                  top_terms_boost_N - first translates each term into boolean should
                    and scores are only computed as the boost using the top N
                    scoring terms.  Replace N with an integer value.
                    
                  top_terms_N -   first translates each term into boolean should
                      and keeps the scores as computed by the query. Only the top N
                      scoring terms are used.  Replace N with an integer value.
                  
                  Default is constant_score_auto.
      
                  This is an advanced option, use with care.
      
                  @member ejs.QueryStringQuery
                  @param {String} m The rewrite method as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            rewrite: function (m) {
                if (m == null) {
                    return query.query_string.rewrite;
                }

                m = m.toLowerCase();
                if (m === 'constant_score_auto' || m === 'scoring_boolean' ||
                  m === 'constant_score_boolean' || m === 'constant_score_filter' ||
                  m.indexOf('top_terms_boost_') === 0 ||
                  m.indexOf('top_terms_') === 0) {

                    query.query_string.rewrite = m;
                }

                return this;
            },

            /**
                  Sets the suffix to automatically add to the field name when 
                  performing a quoted search.
      
                  @member ejs.QueryStringQuery
                  @param {String} s The suffix as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            quoteFieldSuffix: function (s) {
                if (s == null) {
                    return query.query_string.quote_field_suffix;
                }

                query.query_string.quote_field_suffix = s;
                return this;
            },

            /**
                  Enables lenient parsing of the query string.
      
                  @member ejs.QueryStringQuery
                  @param {Boolean} trueFalse A boolean value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lenient: function (trueFalse) {
                if (trueFalse == null) {
                    return query.query_string.lenient;
                }

                query.query_string.lenient = trueFalse;
                return this;
            }

        });
    };

    /**
      @class
      <p>Matches documents with fields that have terms within a certain range. 
      The type of the Lucene query depends on the field type, for string fields, 
      the TermRangeQuery, while for number/date fields, the query is a 
      NumericRangeQuery.</p>
  
      @name ejs.RangeQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Matches documents with fields that have terms within a certain range.
  
      @param {String} field A valid field name.
      */
    ejs.RangeQuery = function (field) {

        var
          _common = ejs.QueryMixin('range'),
          query = _common.toJSON();

        query.range[field] = {};

        return extend(_common, {

            /**
                   The field to run the query against.
      
                   @member ejs.RangeQuery
                   @param {String} f A single field name.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            field: function (f) {
                var oldValue = query.range[field];

                if (f == null) {
                    return field;
                }

                delete query.range[field];
                field = f;
                query.range[f] = oldValue;

                return this;
            },

            /**
                  The lower bound. Defaults to start from the first.
      
                  @member ejs.RangeQuery
                  @param {*} f the lower bound value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            from: function (f) {
                if (f == null) {
                    return query.range[field].from;
                }

                query.range[field].from = f;
                return this;
            },

            /**
                  The upper bound. Defaults to unbounded.
      
                  @member ejs.RangeQuery
                  @param {*} t the upper bound value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            to: function (t) {
                if (t == null) {
                    return query.range[field].to;
                }

                query.range[field].to = t;
                return this;
            },

            /**
                  Should the first from (if set) be inclusive or not. 
                  Defaults to true
      
                  @member ejs.RangeQuery
                  @param {Boolean} trueFalse true to include, false to exclude 
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            includeLower: function (trueFalse) {
                if (trueFalse == null) {
                    return query.range[field].include_lower;
                }

                query.range[field].include_lower = trueFalse;
                return this;
            },

            /**
                  Should the last to (if set) be inclusive or not. Defaults to true.
      
                  @member ejs.RangeQuery
                  @param {Boolean} trueFalse true to include, false to exclude 
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            includeUpper: function (trueFalse) {
                if (trueFalse == null) {
                    return query.range[field].include_upper;
                }

                query.range[field].include_upper = trueFalse;
                return this;
            },

            /**
                  Greater than value.  Same as setting from to the value, and 
                  include_lower to false,
      
                  @member ejs.RangeQuery
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            gt: function (val) {
                if (val == null) {
                    return query.range[field].gt;
                }

                query.range[field].gt = val;
                return this;
            },

            /**
                  Greater than or equal to value.  Same as setting from to the value,
                  and include_lower to true.
      
                  @member ejs.RangeQuery
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            gte: function (val) {
                if (val == null) {
                    return query.range[field].gte;
                }

                query.range[field].gte = val;
                return this;
            },

            /**
                  Less than value.  Same as setting to to the value, and include_upper 
                  to false.
      
                  @member ejs.RangeQuery
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lt: function (val) {
                if (val == null) {
                    return query.range[field].lt;
                }

                query.range[field].lt = val;
                return this;
            },

            /**
                  Less than or equal to value.  Same as setting to to the value, 
                  and include_upper to true.
      
                  @member ejs.RangeQuery
                  @param {*} val the value, type depends on field type
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lte: function (val) {
                if (val == null) {
                    return query.range[field].lte;
                }

                query.range[field].lte = val;
                return this;
            },

            /**
                  Sets the boost value of the <code>Query</code>.
      
                  @member ejs.RangeQuery
                  @param {Double} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.range[field].boost;
                }

                query.range[field].boost = boost;
                return this;
            }

        });
    };

    /**
      @class
      <p>Matches documents that have fields matching a regular expression. Based 
      on Lucene 4.0 RegexpQuery which uses automaton to efficiently iterate over 
      index terms.</p>
  
      @name ejs.RegexpQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Matches documents that have fields matching a regular expression.
  
      @param {String} field A valid field name.
      @param {String} value A regex pattern.
      */
    ejs.RegexpQuery = function (field, value) {

        var
          _common = ejs.QueryMixin('regexp'),
          query = _common.toJSON();

        query.regexp[field] = {
            value: value
        };

        return extend(_common, {

            /**
                   The field to run the query against.
      
                   @member ejs.RegexpQuery
                   @param {String} f A single field name.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            field: function (f) {
                var oldValue = query.regexp[field];

                if (f == null) {
                    return field;
                }

                delete query.regexp[field];
                field = f;
                query.regexp[f] = oldValue;

                return this;
            },

            /**
                  The regexp value.
      
                  @member ejs.RegexpQuery
                  @param {String} p A string regexp
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            value: function (p) {
                if (p == null) {
                    return query.regexp[field].value;
                }

                query.regexp[field].value = p;
                return this;
            },

            /**
                  The regex flags to use.  Valid flags are:
                
                  INTERSECTION - Support for intersection notation
                  COMPLEMENT - Support for complement notation
                  EMPTY - Support for the empty language symbol: #
                  ANYSTRING - Support for the any string symbol: @
                  INTERVAL - Support for numerical interval notation: <n-m>
                  NONE - Disable support for all syntax options
                  ALL - Enables support for all syntax options
                
                  Use multiple flags by separating with a "|" character.  Example:
                
                  INTERSECTION|COMPLEMENT|EMPTY
      
                  @member ejs.RegexpQuery
                  @param {String} f The flags as a string, separate multiple flags with "|".
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            flags: function (f) {
                if (f == null) {
                    return query.regexp[field].flags;
                }

                query.regexp[field].flags = f;
                return this;
            },

            /**
                  The regex flags to use as a numeric value.  Advanced use only,
                  it is probably better to stick with the <code>flags</code> option.
                
                  @member ejs.RegexpQuery
                  @param {String} v The flags as a numeric value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            flagsValue: function (v) {
                if (v == null) {
                    return query.regexp[field].flags_value;
                }

                query.regexp[field].flags_value = v;
                return this;
            },

            /**
                  Sets rewrite method.  Valid values are: 
                
                  constant_score_auto - tries to pick the best constant-score rewrite 
                    method based on term and document counts from the query
                  
                  scoring_boolean - translates each term into boolean should and 
                    keeps the scores as computed by the query
                  
                  constant_score_boolean - same as scoring_boolean, expect no scores
                    are computed.
                  
                  constant_score_filter - first creates a private Filter, by visiting 
                    each term in sequence and marking all docs for that term
                  
                  top_terms_boost_N - first translates each term into boolean should
                    and scores are only computed as the boost using the top N
                    scoring terms.  Replace N with an integer value.
                  
                  top_terms_N -   first translates each term into boolean should
                      and keeps the scores as computed by the query. Only the top N
                      scoring terms are used.  Replace N with an integer value.
                
                  Default is constant_score_auto.
      
                  This is an advanced option, use with care.
      
                  @member ejs.RegexpQuery
                  @param {String} m The rewrite method as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            rewrite: function (m) {
                if (m == null) {
                    return query.regexp[field].rewrite;
                }

                m = m.toLowerCase();
                if (m === 'constant_score_auto' || m === 'scoring_boolean' ||
                  m === 'constant_score_boolean' || m === 'constant_score_filter' ||
                  m.indexOf('top_terms_boost_') === 0 ||
                  m.indexOf('top_terms_') === 0) {

                    query.regexp[field].rewrite = m;
                }

                return this;
            },

            /**
                  Sets the boost value of the <code>Query</code>.
      
                  @member ejs.RegexpQuery
                  @param {Double} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.regexp[field].boost;
                }

                query.regexp[field].boost = boost;
                return this;
            }

        });
    };

    /**
      @class
      <p>Matches spans near the beginning of a field. The spanFirstQuery allows you to search
      for Spans that start and end within the first <code>n</code> positions of the document.
      The span first query maps to Lucene SpanFirstQuery.</p>
  
      @name ejs.SpanFirstQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Matches spans near the beginning of a field.
  
      @param {Query} spanQry A valid SpanQuery
      @param {Integer} end the maximum end position in a match.
      
      */
    ejs.SpanFirstQuery = function (spanQry, end) {

        if (!isQuery(spanQry)) {
            throw new TypeError('Argument must be a SpanQuery');
        }

        var
          _common = ejs.QueryMixin('span_first'),
          query = _common.toJSON();

        query.span_first.match = spanQry.toJSON();
        query.span_first.end = end;

        return extend(_common, {

            /**
                  Sets the span query to match on.
      
                  @member ejs.SpanFirstQuery
                  @param {Object} spanQuery Any valid span type query.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            match: function (spanQuery) {
                if (spanQuery == null) {
                    return query.span_first.match;
                }

                if (!isQuery(spanQuery)) {
                    throw new TypeError('Argument must be a SpanQuery');
                }

                query.span_first.match = spanQuery.toJSON();
                return this;
            },

            /**
                  Sets the maximum end position permitted in a match.
      
                  @member ejs.SpanFirstQuery
                  @param {Number} position The maximum position length to consider.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            end: function (position) {
                if (position == null) {
                    return query.span_first.end;
                }

                query.span_first.end = position;
                return this;
            }

        });
    };

    /**
      @class
      <p>Wraps lucene MultiTermQueries as a SpanQuery so it can be used in the
      various Span* queries.  Examples of valid MultiTermQueries are
      <code>Fuzzy, NumericRange, Prefix, Regex, Range, and Wildcard</code>.</p>
  
      @name ejs.SpanMultiTermQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Use MultiTermQueries as a SpanQuery.
  
      @param {Query} qry An optional multi-term query object.
      */
    ejs.SpanMultiTermQuery = function (qry) {

        if (qry != null && !isQuery(qry)) {
            throw new TypeError('Argument must be a MultiTermQuery');
        }

        var
          _common = ejs.QueryMixin('span_multi'),
          query = _common.toJSON();

        query.span_multi.match = {};

        if (qry != null) {
            query.span_multi.match = qry.toJSON();
        }

        return extend(_common, {

            /**
                  Sets the span query to match on.
      
                  @member ejs.SpanMultiTermQuery
                  @param {Object} mtQuery Any valid multi-term query.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            match: function (mtQuery) {
                if (mtQuery == null) {
                    return query.span_multi.match;
                }

                if (!isQuery(mtQuery)) {
                    throw new TypeError('Argument must be a MultiTermQuery');
                }

                query.span_multi.match = mtQuery.toJSON();
                return this;
            }

        });
    };

    /**
      @class
      <p>A spanNearQuery will look to find a number of spanQuerys within a given
      distance from each other.</p>
  
      @name ejs.SpanNearQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Matches spans which are near one another.
  
      @param {(Query|Query[])} clauses A single SpanQuery or array of SpanQueries
      @param {Integer} slop The number of intervening unmatched positions
  
      */
    ejs.SpanNearQuery = function (clauses, slop) {

        var
          i,
          len,
          _common = ejs.QueryMixin('span_near'),
          query = _common.toJSON();

        query.span_near.clauses = [];
        query.span_near.slop = slop;

        if (isQuery(clauses)) {
            query.span_near.clauses.push(clauses.toJSON());
        } else if (isArray(clauses)) {
            for (i = 0, len = clauses.length; i < len; i++) {
                if (!isQuery(clauses[i])) {
                    throw new TypeError('Argument must be array of SpanQueries');
                }

                query.span_near.clauses.push(clauses[i].toJSON());
            }
        } else {
            throw new TypeError('Argument must be SpanQuery or array of SpanQueries');
        }

        return extend(_common, {

            /**
                  Sets the clauses used.  If passed a single SpanQuery, it is added
                  to the existing list of clauses.  If passed an array of
                  SpanQueries, they replace any existing clauses.
      
                  @member ejs.SpanNearQuery
                  @param {(Query|Query[])} clauses A SpanQuery or array of SpanQueries.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            clauses: function (clauses) {
                var i, len;

                if (clauses == null) {
                    return query.span_near.clauses;
                }

                if (isQuery(clauses)) {
                    query.span_near.clauses.push(clauses.toJSON());
                } else if (isArray(clauses)) {
                    query.span_near.clauses = [];
                    for (i = 0, len = clauses.length; i < len; i++) {
                        if (!isQuery(clauses[i])) {
                            throw new TypeError('Argument must be array of SpanQueries');
                        }

                        query.span_near.clauses.push(clauses[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be SpanQuery or array of SpanQueries');
                }

                return this;
            },

            /**
                  Sets the maximum number of intervening unmatched positions.
      
                  @member ejs.SpanNearQuery
                  @param {Number} distance The number of intervening unmatched positions.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            slop: function (distance) {
                if (distance == null) {
                    return query.span_near.slop;
                }

                query.span_near.slop = distance;
                return this;
            },

            /**
                  Sets whether or not matches are required to be in-order.
      
                  @member ejs.SpanNearQuery
                  @param {Boolean} trueFalse Determines if matches must be in-order.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            inOrder: function (trueFalse) {
                if (trueFalse == null) {
                    return query.span_near.in_order;
                }

                query.span_near.in_order = trueFalse;
                return this;
            },

            /**
                  Sets whether or not payloads are being used. A payload is an arbitrary
                  byte array stored at a specific position (i.e. token/term).
      
                  @member ejs.SpanNearQuery
                  @param {Boolean} trueFalse Whether or not to return payloads.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            collectPayloads: function (trueFalse) {
                if (trueFalse == null) {
                    return query.span_near.collect_payloads;
                }

                query.span_near.collect_payloads = trueFalse;
                return this;
            }

        });
    };

    /**
      @class
      <p>Removes matches which overlap with another span query.
      The span not query maps to Lucene SpanNotQuery.</p>
  
      @name ejs.SpanNotQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Removes matches which overlap with another span query.
  
      @param {Query} includeQry a valid SpanQuery whose matching docs will be returned.
      @param {Query} excludeQry a valid SpanQuery whose matching docs will not be returned
      
      */
    ejs.SpanNotQuery = function (includeQry, excludeQry) {

        if (!isQuery(includeQry) || !isQuery(excludeQry)) {
            throw new TypeError('Argument must be a SpanQuery');
        }

        var
          _common = ejs.QueryMixin('span_not'),
          query = _common.toJSON();

        query.span_not.include = includeQry.toJSON();
        query.span_not.exclude = excludeQry.toJSON();

        return extend(_common, {

            /**
                  Set the span query whose matches are filtered.
      
                  @member ejs.SpanNotQuery
                  @param {Object} spanQuery Any valid span type query.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            include: function (spanQuery) {
                if (spanQuery == null) {
                    return query.span_not.include;
                }

                if (!isQuery(spanQuery)) {
                    throw new TypeError('Argument must be a SpanQuery');
                }

                query.span_not.include = spanQuery.toJSON();
                return this;
            },

            /**
                  Sets the span query whose matches must not overlap those returned.
      
                  @member ejs.SpanNotQuery
                  @param {Object} spanQuery Any valid span type query.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            exclude: function (spanQuery) {
                if (spanQuery == null) {
                    return query.span_not.exclude;
                }

                if (!isQuery(spanQuery)) {
                    throw new TypeError('Argument must be a SpanQuery');
                }

                query.span_not.exclude = spanQuery.toJSON();
                return this;
            }

        });
    };

    /**
      @class
      <p>The spanOrQuery takes an array of SpanQuerys and will match if any of the
      underlying SpanQueries match. The span or query maps to Lucene SpanOrQuery.</p>
  
      @name ejs.SpanOrQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Matches the union of its span clauses.
  
      @param {Object} clauses A single SpanQuery or array of SpanQueries.
  
      */
    ejs.SpanOrQuery = function (clauses) {

        var
          i,
          len,
          _common = ejs.QueryMixin('span_or'),
          query = _common.toJSON();

        query.span_or.clauses = [];

        if (isQuery(clauses)) {
            query.span_or.clauses.push(clauses.toJSON());
        } else if (isArray(clauses)) {
            for (i = 0, len = clauses.length; i < len; i++) {
                if (!isQuery(clauses[i])) {
                    throw new TypeError('Argument must be array of SpanQueries');
                }

                query.span_or.clauses.push(clauses[i].toJSON());
            }
        } else {
            throw new TypeError('Argument must be SpanQuery or array of SpanQueries');
        }

        return extend(_common, {

            /**
                  Sets the clauses used.  If passed a single SpanQuery, it is added
                  to the existing list of clauses.  If passed an array of
                  SpanQueries, they replace any existing clauses.
      
                  @member ejs.SpanOrQuery
                  @param {(Query|Query[])} clauses A SpanQuery or array of SpanQueries.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            clauses: function (clauses) {
                var i, len;

                if (clauses == null) {
                    return query.span_or.clauses;
                }

                if (isQuery(clauses)) {
                    query.span_or.clauses.push(clauses.toJSON());
                } else if (isArray(clauses)) {
                    query.span_or.clauses = [];
                    for (i = 0, len = clauses.length; i < len; i++) {
                        if (!isQuery(clauses[i])) {
                            throw new TypeError('Argument must be array of SpanQueries');
                        }

                        query.span_or.clauses.push(clauses[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be SpanQuery or array of SpanQueries');
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>A spanTermQuery is the basic unit of Lucene's Span Query which allows for nested,
      positional restrictions when matching documents. The spanTermQuery simply matches
      spans containing a term. It's essentially a termQuery with positional information asscoaited.</p>
  
      @name ejs.SpanTermQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Matches spans containing a term
  
      @param {String} field the document field/field to query against
      @param {String} value the literal value to be matched
      */
    ejs.SpanTermQuery = function (field, value) {

        var
          _common = ejs.QueryMixin('span_term'),
          query = _common.toJSON();

        query.span_term[field] = {
            term: value
        };

        return extend(_common, {

            /**
                  Sets the field to query against.
      
                  @member ejs.SpanTermQuery
                  @param {String} f A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                var oldValue = query.span_term[field];

                if (f == null) {
                    return field;
                }

                delete query.span_term[field];
                field = f;
                query.span_term[f] = oldValue;

                return this;
            },

            /**
                  Sets the term.
      
                  @member ejs.SpanTermQuery
                  @param {String} t A single term.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            term: function (t) {
                if (t == null) {
                    return query.span_term[field].term;
                }

                query.span_term[field].term = t;
                return this;
            },

            /**
                  Sets the boost value for documents matching the <code>Query</code>.
      
                  @member ejs.SpanTermQuery
                  @param {Double} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.span_term[field].boost;
                }

                query.span_term[field].boost = boost;
                return this;
            }

        });
    };

    /**
      @class
      <p>A <code>TermQuery</code> can be used to return documents containing a given
      keyword or <em>term</em>. For instance, you might want to retieve all the
      documents/objects that contain the term <code>Javascript</code>. Term filters
      often serve as the basis for more complex queries such as <em>Boolean</em> queries.</p>
  
      @name ejs.TermQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      A Query that matches documents containing a term. This may be
      combined with other terms with a BooleanQuery.
  
      @param {String} field the document field/key to query against
      @param {String} term the literal value to be matched
      */
    ejs.TermQuery = function (field, term) {

        var
          _common = ejs.QueryMixin('term'),
          query = _common.toJSON();

        query.term[field] = {
            term: term
        };

        return extend(_common, {

            /**
                  Sets the fields to query against.
      
                  @member ejs.TermQuery
                  @param {String} f A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                var oldValue = query.term[field];

                if (f == null) {
                    return field;
                }

                delete query.term[field];
                field = f;
                query.term[f] = oldValue;

                return this;
            },

            /**
                  Sets the term.
      
                  @member ejs.TermQuery
                  @param {String} t A single term.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            term: function (t) {
                if (t == null) {
                    return query.term[field].term;
                }

                query.term[field].term = t;
                return this;
            },

            /**
                  Sets the boost value for documents matching the <code>Query</code>.
      
                  @member ejs.TermQuery
                  @param {Number} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.term[field].boost;
                }

                query.term[field].boost = boost;
                return this;
            }

        });
    };

    /**
      @class
      <p>A query that match on any (configurable) of the provided terms. This is 
      a simpler syntax query for using a bool query with several term queries 
      in the should clauses.</p>
  
      @name ejs.TermsQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      A Query that matches documents containing provided terms. 
  
      @param {String} field the document field/key to query against
      @param {(String|String[])} terms a single term or array of "terms" to match
      */
    ejs.TermsQuery = function (field, terms) {

        var
          _common = ejs.QueryMixin('terms'),
          query = _common.toJSON();

        if (isString(terms)) {
            query.terms[field] = [terms];
        } else if (isArray(terms)) {
            query.terms[field] = terms;
        } else {
            throw new TypeError('Argument must be string or array');
        }

        return extend(_common, {

            /**
                  Sets the fields to query against.
      
                  @member ejs.TermsQuery
                  @param {String} f A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                var oldValue = query.terms[field];

                if (f == null) {
                    return field;
                }

                delete query.terms[field];
                field = f;
                query.terms[f] = oldValue;

                return this;
            },

            /**
                  Sets the terms.  If you t is a String, it is added to the existing
                  list of terms.  If t is an array, the list of terms replaces the
                  existing terms.
      
                  @member ejs.TermsQuery
                  @param {(String|String[])} t A single term or an array or terms.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            terms: function (t) {
                if (t == null) {
                    return query.terms[field];
                }

                if (isString(t)) {
                    query.terms[field].push(t);
                } else if (isArray(t)) {
                    query.terms[field] = t;
                } else {
                    throw new TypeError('Argument must be string or array');
                }

                return this;
            },

            /**
                  Sets the minimum number of terms that need to match in a document
                  before that document is returned in the results.
      
                  @member ejs.TermsQuery
                  @param {Integer} min A positive integer.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minimumShouldMatch: function (min) {
                if (min == null) {
                    return query.terms.minimum_should_match;
                }

                query.terms.minimum_should_match = min;
                return this;
            },

            /**
                  Enables or disables similarity coordinate scoring of documents
                  matching the <code>Query</code>. Default: false.
      
                  @member ejs.TermsQuery
                  @param {String} trueFalse A <code>true/false</code value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            disableCoord: function (trueFalse) {
                if (trueFalse == null) {
                    return query.terms.disable_coord;
                }

                query.terms.disable_coord = trueFalse;
                return this;
            }

        });
    };

    /**
      @class
      <p>TThe top_children query runs the child query with an estimated hits size, 
      and out of the hit docs, aggregates it into parent docs. If there aren’t 
      enough parent docs matching the requested from/size search request, then it 
      is run again with a wider (more hits) search.</p>
  
      <p>The top_children also provide scoring capabilities, with the ability to 
      specify max, sum or avg as the score type.</p>
  
      @name ejs.TopChildrenQuery
      @ejs query
      @borrows ejs.QueryMixin.boost as boost
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      Returns child documents matching the query aggregated into the parent docs.
  
      @param {Object} qry A valid query object.
      @param {String} type The child type to execute the query on
      */
    ejs.TopChildrenQuery = function (qry, type) {

        if (!isQuery(qry)) {
            throw new TypeError('Argument must be a Query');
        }

        var
          _common = ejs.QueryMixin('top_children'),
          query = _common.toJSON();

        query.top_children.query = qry.toJSON();
        query.top_children.type = type;

        return extend(_common, {

            /**
                  Sets the query
      
                  @member ejs.TopChildrenQuery
                  @param {Object} q A valid Query object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (q) {
                if (q == null) {
                    return query.top_children.query;
                }

                if (!isQuery(q)) {
                    throw new TypeError('Argument must be a Query');
                }

                query.top_children.query = q.toJSON();
                return this;
            },

            /**
                  Sets the child document type to search against
      
                  @member ejs.TopChildrenQuery
                  @param {String} t A valid type name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (t) {
                if (t == null) {
                    return query.top_children.type;
                }

                query.top_children.type = t;
                return this;
            },

            /**
                  Sets the scope of the query.  A scope allows to run facets on the 
                  same scope name that will work against the child documents. 
      
                  @deprecated since elasticsearch 0.90
                  @member ejs.TopChildrenQuery
                  @param {String} s The scope name as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scope: function (s) {
                return this;
            },

            /**
                  Sets the scoring type.  Valid values are max, sum, or avg. If
                  another value is passed it we silently ignore the value.
      
                  @deprecated since elasticsearch 0.90.1, use scoreMode
                  
                  @member ejs.TopChildrenQuery
                  @param {String} s The scoring type as a string. 
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            score: function (s) {
                if (s == null) {
                    return query.top_children.score;
                }

                s = s.toLowerCase();
                if (s === 'max' || s === 'sum' || s === 'avg' || s === 'total') {
                    query.top_children.score = s;
                }

                return this;
            },

            /**
                  Sets the scoring type.  Valid values are max, sum, total, or avg. 
                  If another value is passed it we silently ignore the value.
      
                  @member ejs.TopChildrenQuery
                  @param {String} s The scoring type as a string. 
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scoreMode: function (s) {
                if (s == null) {
                    return query.top_children.score_mode;
                }

                s = s.toLowerCase();
                if (s === 'max' || s === 'sum' || s === 'avg' || s === 'total') {
                    query.top_children.score_mode = s;
                }

                return this;
            },

            /**
                  Sets the factor which is the number of hits that are asked for in
                  the child query.  Defaults to 5.
      
                  @member ejs.TopChildrenQuery
                  @param {Integer} f A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            factor: function (f) {
                if (f == null) {
                    return query.top_children.factor;
                }

                query.top_children.factor = f;
                return this;
            },

            /**
                  Sets the incremental factor.  The incremental factor is used when not
                  enough child documents are returned so the factor is multiplied by
                  the incremental factor to fetch more results.  Defaults to 52
      
                  @member ejs.TopChildrenQuery
                  @param {Integer} f A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            incrementalFactor: function (f) {
                if (f == null) {
                    return query.top_children.incremental_factor;
                }

                query.top_children.incremental_factor = f;
                return this;
            }

        });
    };

    /**
      @class
      <p>Matches documents that have fields matching a wildcard expression 
      (not analyzed). Supported wildcards are *, which matches any character 
      sequence (including the empty one), and ?, which matches any single 
      character. Note this query can be slow, as it needs to iterate over many 
      wildcards. In order to prevent extremely slow wildcard queries, a wildcard 
      wildcard should not start with one of the wildcards * or ?. The wildcard query 
      maps to Lucene WildcardQuery.</p>
  
      @name ejs.WildcardQuery
      @ejs query
      @borrows ejs.QueryMixin._type as _type
      @borrows ejs.QueryMixin.toJSON as toJSON
  
      @desc
      A Query that matches documents containing a wildcard. This may be
      combined with other wildcards with a BooleanQuery.
  
      @param {String} field the document field/key to query against
      @param {String} value the literal value to be matched
      */
    ejs.WildcardQuery = function (field, value) {

        var
          _common = ejs.QueryMixin('wildcard'),
          query = _common.toJSON();

        query.wildcard[field] = {
            value: value
        };

        return extend(_common, {

            /**
                  Sets the fields to query against.
      
                  @member ejs.WildcardQuery
                  @param {String} f A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                var oldValue = query.wildcard[field];

                if (f == null) {
                    return field;
                }

                delete query.wildcard[field];
                field = f;
                query.wildcard[f] = oldValue;

                return this;
            },

            /**
                  Sets the wildcard query value.
      
                  @member ejs.WildcardQuery
                  @param {String} v A single term.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            value: function (v) {
                if (v == null) {
                    return query.wildcard[field].value;
                }

                query.wildcard[field].value = v;
                return this;
            },

            /**
                  Sets rewrite method.  Valid values are: 
                  
                  constant_score_auto - tries to pick the best constant-score rewrite 
                    method based on term and document counts from the query
                    
                  scoring_boolean - translates each term into boolean should and 
                    keeps the scores as computed by the query
                    
                  constant_score_boolean - same as scoring_boolean, expect no scores
                    are computed.
                    
                  constant_score_filter - first creates a private Filter, by visiting 
                    each term in sequence and marking all docs for that term
                    
                  top_terms_boost_N - first translates each term into boolean should
                    and scores are only computed as the boost using the top N
                    scoring terms.  Replace N with an integer value.
                    
                  top_terms_N -   first translates each term into boolean should
                      and keeps the scores as computed by the query. Only the top N
                      scoring terms are used.  Replace N with an integer value.
                  
                  Default is constant_score_auto.
      
                  This is an advanced option, use with care.
      
                  @member ejs.WildcardQuery
                  @param {String} m The rewrite method as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            rewrite: function (m) {
                if (m == null) {
                    return query.wildcard[field].rewrite;
                }

                m = m.toLowerCase();
                if (m === 'constant_score_auto' || m === 'scoring_boolean' ||
                  m === 'constant_score_boolean' || m === 'constant_score_filter' ||
                  m.indexOf('top_terms_boost_') === 0 ||
                  m.indexOf('top_terms_') === 0) {

                    query.wildcard[field].rewrite = m;
                }

                return this;
            },

            /**
                  Sets the boost value for documents matching the <code>Query</code>.
      
                  @member ejs.WildcardQuery
                  @param {Number} boost A positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boost: function (boost) {
                if (boost == null) {
                    return query.wildcard[field].boost;
                }

                query.wildcard[field].boost = boost;
                return this;
            }

        });
    };

    /**
      @class
      <p>The boost_factor score allows you to multiply the score by the provided
      boost_factor. This can sometimes be desired since boost value set on specific
      queries gets normalized, while for this score function it does not.</p>
  
      @name ejs.BoostFactorScoreFunction
      @ejs scorefunction
      @borrows ejs.ScoreFunctionMixin.filter as filter
      @borrows ejs.ScoreFunctionMixin._type as _type
      @borrows ejs.ScoreFunctionMixin.toJSON as toJSON
  
      @param {Float} boostVal the boost factor.
  
      @desc
      <p>Multiply the score by the provided boost_factor.</p>
  
      */
    ejs.BoostFactorScoreFunction = function (boostVal) {

        var
          _common = ejs.ScoreFunctionMixin('boost_factor'),
          func = _common.toJSON();

        func.boost_factor = boostVal;

        return extend(_common, {

            /**
            Sets the boost factor.
      
            @member ejs.BoostFactorScoreFunction
            @param {Float} b the boost factor.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            boost: function (b) {
                if (b == null) {
                    return func.boost_factor;
                }

                func.boost_factor = b;
                return this;
            }

        });
    };

    /**
      @class
      <p>Decay functions score a document with a function that decays depending on
      the distance of a numeric field value of the document from a user given
      origin. This is similar to a range query, but with smooth edges instead of
      boxes.</p>
  
      <p>Supported decay functions are: linear, exp, and gauss.</p>
  
      @name ejs.DecayScoreFunction
      @ejs scorefunction
      @borrows ejs.ScoreFunctionMixin.filter as filter
      @borrows ejs.ScoreFunctionMixin._type as _type
      @borrows ejs.ScoreFunctionMixin.toJSON as toJSON
  
      @param {String} field the document field to run decay function against.
  
      @desc
      <p>Score a document with a function that decays depending on the distance
      of a numeric field value of the document from given origin.</p>
  
      */
    ejs.DecayScoreFunction = function (field) {

        var
          mode = 'gauss', // default decay function
          _common = ejs.ScoreFunctionMixin(mode),
          func = _common.toJSON(),
          changeMode = function (newMode) {
              var oldValue;
              if (mode !== newMode) {
                  oldValue = func[mode];
                  delete func[mode];
                  mode = newMode;
                  func[mode] = oldValue;
              }
          };

        func[mode][field] = {};

        return extend(_common, {

            /**
            Use the linear decay function. Linear decay.
      
            @member ejs.DecayScoreFunction
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            linear: function () {
                changeMode('linear');
            },

            /**
            Use the exp decay function. Exponential decay.
      
            @member ejs.DecayScoreFunction
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            exp: function () {
                changeMode('exp');
            },

            /**
            Use the gauss decay function. Normal decay.
      
            @member ejs.DecayScoreFunction
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            gauss: function () {
                changeMode('gauss');
            },

            /**
            Sets the fields to run the decay function against.
      
            @member ejs.DecayScoreFunction
            @param {String} f A valid field name.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            field: function (f) {
                var oldValue = func[mode][field];

                if (f == null) {
                    return field;
                }

                delete func[mode][field];
                field = f;
                func[mode][field] = oldValue;

                return this;
            },

            /**
            Sets the scale/rate of decay.
      
            @member ejs.DecayScoreFunction
            @param {String} s A valid scale value for the field type.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            scale: function (s) {
                if (s == null) {
                    return func[mode][field].scale;
                }

                func[mode][field].scale = s;
                return this;
            },

            /**
            Sets the origin which is the “central point” from which the distance is
            calculated.
      
            @member ejs.DecayScoreFunction
            @param {String} o A valid origin value for the field type.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            origin: function (o) {
                if (o == null) {
                    return func[mode][field].origin;
                }

                if (isGeoPoint(o)) {
                    func[mode][field].origin = o.toJSON();
                } else if (isEJSObject(o)) {
                    throw new TypeError('origin must be a GeoPoint or native type');
                } else {
                    func[mode][field].origin = o;
                }

                return this;
            },

            /**
            Sets the decay value which defines how documents are scored at the distance
            given at scale.
      
            @member ejs.DecayScoreFunction
            @param {Double} d A decay value as a double.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            decay: function (d) {
                if (d == null) {
                    return func[mode][field].decay;
                }

                func[mode][field].decay = d;
                return this;
            },

            /**
            Sets the decay offset.  The decay function will only compute a the decay
            function for documents with a distance greater that the defined offset.
            The default is 0.
      
            @member ejs.DecayScoreFunction
            @param {String} o A valid offset value for the field type.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            offset: function (o) {
                if (o == null) {
                    return func[mode][field].offset;
                }

                func[mode][field].offset = o;
                return this;
            }

        });
    };

    /**
      @class
      <p>The random_score generates scores via a pseudo random number algorithm
      that is initialized with a seed.</p>
  
      @name ejs.RandomScoreFunction
      @ejs scorefunction
      @borrows ejs.ScoreFunctionMixin.filter as filter
      @borrows ejs.ScoreFunctionMixin._type as _type
      @borrows ejs.ScoreFunctionMixin.toJSON as toJSON
  
      @desc
      <p>Randomly score documents.</p>
  
      */
    ejs.RandomScoreFunction = function () {

        var
          _common = ejs.ScoreFunctionMixin('random_score'),
          func = _common.toJSON();

        return extend(_common, {

            /**
            Sets random seed value.
      
            @member ejs.RandomScoreFunction
            @param {Long} s A seed value.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            seed: function (s) {
                if (s == null) {
                    return func.random_score.seed;
                }

                func.random_score.seed = s;
                return this;
            }

        });
    };

    /**
      @class
      <p>The script_score function allows you to wrap another query and customize
      the scoring of it optionally with a computation derived from other numeric
      field values in the doc using a script expression.</p>
  
      @name ejs.ScriptScoreFunction
      @ejs scorefunction
      @borrows ejs.ScoreFunctionMixin.filter as filter
      @borrows ejs.ScoreFunctionMixin._type as _type
      @borrows ejs.ScoreFunctionMixin.toJSON as toJSON
  
      @desc
      <p>Modify a documents score using a script.</p>
  
      */
    ejs.ScriptScoreFunction = function () {

        var
          _common = ejs.ScoreFunctionMixin('script_score'),
          func = _common.toJSON();

        return extend(_common, {

            /**
            Set the script that will modify the score.
      
            @member ejs.ScriptScoreFunction
            @param {String} scriptCode A valid script string to execute.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            script: function (scriptCode) {
                if (scriptCode == null) {
                    return func.script_score.script;
                }

                func.script_score.script = scriptCode;
                return this;
            },

            /**
            Set the script file that will modify the score.
      
            @member ejs.ScriptScoreFunction
            @param {String} file A valid script file to execute.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            scriptFile: function (scriptFile) {
                if (scriptFile == null) {
                    return func.script_score.scriptFile;
                }

                func.script_score.script_file = scriptFile;
                return this;
            },

            /**
            The script language being used.
      
            @member ejs.ScriptScoreFunction
            @param {String} language The language of the script.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            lang: function (language) {
                if (language == null) {
                    return func.script_score.lang;
                }

                func.script_score.lang = language;
                return this;
            },

            /**
            Sets parameters that will be applied to the script.  Overwrites
            any existing params.
      
            @member ejs.ScriptScoreFunction
            @param {Object} p An object where the keys are the parameter name and
              values are the parameter value.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            params: function (p) {
                if (p == null) {
                    return func.script_score.params;
                }

                func.script_score.params = p;
                return this;
            }


        });
    };

    /**
      @class
      <p>A GeoPoint object that can be used in queries and filters that 
      take a GeoPoint.  GeoPoint supports various input formats.</p>
  
      <p>See http://www.elasticsearch.org/guide/reference/mapping/geo-point-type.html</p>
  
      @name ejs.GeoPoint
      @ejs geo
  
      @desc
      <p>Defines a point</p>
  
      @param {Array} p An optional point as an array in [lat, lon] format.
      */
    ejs.GeoPoint = function (p) {

        var point = [0, 0];

        // p  = [lat, lon], convert it to GeoJSON format of [lon, lat]
        if (p != null && isArray(p) && p.length === 2) {
            point = [p[1], p[0]];
        }

        return {

            /**
                  Sets the GeoPoint as properties on an object.  The object must have
                  a 'lat' and 'lon' or a 'geohash' property.  
                
                  Example:
                  {lat: 41.12, lon: -71.34} or {geohash: "drm3btev3e86"}
      
                  @member ejs.GeoPoint
                  @param {Object} obj an object with a lat and lon or geohash property.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            properties: function (obj) {
                if (obj == null) {
                    return point;
                }

                if (isObject(obj) && has(obj, 'lat') && has(obj, 'lon')) {
                    point = {
                        lat: obj.lat,
                        lon: obj.lon
                    };
                } else if (isObject(obj) && has(obj, 'geohash')) {
                    point = {
                        geohash: obj.geohash
                    };
                }

                return this;
            },

            /**
                  Sets the GeoPoint as a string.  The format is "lat,lon".
                
                  Example:
                
                  "41.12,-71.34"
      
                  @member ejs.GeoPoint
                  @param {String} s a String point in "lat,lon" format.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            string: function (s) {
                if (s == null) {
                    return point;
                }

                if (isString(s) && s.indexOf(',') !== -1) {
                    point = s;
                }

                return this;
            },

            /**
                  Sets the GeoPoint as a GeoHash.  The hash is a string of 
                  alpha-numeric characters with a precision length that defaults to 12.
                
                  Example:
                  "drm3btev3e86"
      
                  @member ejs.GeoPoint
                  @param {String} hash an GeoHash as a string
                  @param {Integer} precision an optional precision length, defaults
                    to 12 if not specified.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            geohash: function (hash, precision) {
                // set precision, default to 12
                precision = (precision != null && isNumber(precision)) ? precision : 12;

                if (hash == null) {
                    return point;
                }

                if (isString(hash) && hash.length === precision) {
                    point = hash;
                }

                return this;
            },

            /**
                  Sets the GeoPoint from an array point.  The array must contain only
                  2 values.  The first value is the lat and the 2nd value is the lon.
                
                  Example:
                  [41.12, -71.34]
      
                  @member ejs.GeoPoint
                  @param {Array} a an array of length 2.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            array: function (a) {
                if (a == null) {
                    return point;
                }


                // convert to GeoJSON format of [lon, lat]
                if (isArray(a) && a.length === 2) {
                    point = [a[1], a[0]];
                }

                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
                  
                  @member ejs.GeoPoint
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'geo point';
            },

            /**
                  Retrieves the internal <code>script</code> object. This is typically used by
                  internal API functions so use with caution.
      
                  @member ejs.GeoPoint
                  @returns {String} returns this object's internal object representation.
                  */
            toJSON: function () {
                return point;
            }
        };
    };

    /**
      @class
      <p>Allows to highlight search results on one or more fields.  In order to
      perform highlighting, the actual content of the field is required. If the
      field in question is stored (has store set to yes in the mapping), it will
      be used, otherwise, the actual _source will be loaded and the relevant
      field will be extracted from it.</p>
  
      <p>If no term_vector information is provided (by setting it to
      with_positions_offsets in the mapping), then the plain highlighter will be
      used. If it is provided, then the fast vector highlighter will be used.
      When term vectors are available, highlighting will be performed faster at
      the cost of bigger index size.</p>
  
      <p>See http://www.elasticsearch.org/guide/reference/api/search/highlighting.html</p>
  
      @name ejs.Highlight
      @ejs request
  
      @desc
      <p>Allows to highlight search results on one or more fields.</p>
  
      @param {(String|String[])} fields An optional field or array of fields to highlight.
      */
    ejs.Highlight = function (fields) {

        var highlight = {
            fields: {}
        },

        addOption = function (field, option, val) {
            if (field == null) {
                highlight[option] = val;
            } else {
                if (!has(highlight.fields, field)) {
                    highlight.fields[field] = {};
                }

                highlight.fields[field][option] = val;
            }
        };

        if (fields != null) {
            if (isString(fields)) {
                highlight.fields[fields] = {};
            } else if (isArray(fields)) {
                each(fields, function (field) {
                    highlight.fields[field] = {};
                });
            }
        }

        return {

            /**
                  Allows you to set the fields that will be highlighted.  You can
                  specify a single field or an array of fields.  All fields are
                  added to the current list of fields.
      
                  @member ejs.Highlight
                  @param {(String|String[])} vals A field name or array of field names.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fields: function (vals) {
                if (vals == null) {
                    return highlight.fields;
                }

                if (isString(vals)) {
                    if (!has(highlight.fields, vals)) {
                        highlight.fields[vals] = {};
                    }
                } else if (isArray(vals)) {
                    each(vals, function (field) {
                        if (!has(highlight.fields, field)) {
                            highlight.fields[field] = {};
                        }
                    });
                }
            },

            /**
                  Sets the pre tags for highlighted fragments.  You can apply the
                  tags to a specific field by passing the field name in to the
                  <code>oField</code> parameter.
      
                  @member ejs.Highlight
                  @param {(String|String[])} tags A single tag or an array of tags.
                  @param {String} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            preTags: function (tags, oField) {
                if (tags === null && oField != null) {
                    return highlight.fields[oField].pre_tags;
                } else if (tags == null) {
                    return highlight.pre_tags;
                }

                if (isString(tags)) {
                    addOption(oField, 'pre_tags', [tags]);
                } else if (isArray(tags)) {
                    addOption(oField, 'pre_tags', tags);
                }

                return this;
            },

            /**
                  Sets the post tags for highlighted fragments.  You can apply the
                  tags to a specific field by passing the field name in to the
                  <code>oField</code> parameter.
      
                  @member ejs.Highlight
                  @param {(String|String[])} tags A single tag or an array of tags.
                  @param {String} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            postTags: function (tags, oField) {
                if (tags === null && oField != null) {
                    return highlight.fields[oField].post_tags;
                } else if (tags == null) {
                    return highlight.post_tags;
                }

                if (isString(tags)) {
                    addOption(oField, 'post_tags', [tags]);
                } else if (isArray(tags)) {
                    addOption(oField, 'post_tags', tags);
                }

                return this;
            },

            /**
                  Sets the order of highlight fragments.  You can apply the option
                  to a specific field by passing the field name in to the
                  <code>oField</code> parameter.  Valid values for order are:
      
                  score - the score calculated by Lucene's highlighting framework.
      
                  @member ejs.Highlight
                  @param {String} o The order.  Currently only "score".
                  @param {String} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            order: function (o, oField) {
                if (o === null && oField != null) {
                    return highlight.fields[oField].order;
                } else if (o == null) {
                    return highlight.order;
                }

                o = o.toLowerCase();
                if (o === 'score') {
                    addOption(oField, 'order', o);
                }

                return this;
            },

            /**
                  Sets the schema to be used for the tags. Valid values are:
      
                  styled - 10 <em> pre tags with css class of hltN, where N is 1-10
      
                  @member ejs.Highlight
                  @param {String} s The schema.  Currently only "styled".
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            tagsSchema: function (s) {
                if (s == null) {
                    return highlight.tags_schema;
                }

                s = s.toLowerCase();
                if (s === 'styled') {
                    highlight.tags_schema = s;
                }

                return this;
            },

            /**
                  Enables highlights in documents matched by a filter.
                  You can apply the option to a specific field by passing the field
                  name in to the <code>oField</code> parameter.  Defaults to false.
      
                  @member ejs.Highlight
                  @param {Boolean} trueFalse If filtered docs should be highlighted.
                  @param {String} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            highlightFilter: function (trueFalse, oField) {
                if (trueFalse === null && oField != null) {
                    return highlight.fields[oField].highlight_filter;
                } else if (trueFalse == null) {
                    return highlight.highlight_filter;
                }

                addOption(oField, 'highlight_filter', trueFalse);
                return this;
            },

            /**
                  Sets the size of each highlight fragment in characters.
                  You can apply the option to a specific field by passing the field
                  name in to the <code>oField</code> parameter. Default:  100
      
                  @member ejs.Highlight
                  @param {Integer} size The fragment size in characters.
                  @param {String} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fragmentSize: function (size, oField) {
                if (size === null && oField != null) {
                    return highlight.fields[oField].fragment_size;
                } else if (size == null) {
                    return highlight.fragment_size;
                }

                addOption(oField, 'fragment_size', size);
                return this;
            },

            /**
                  Sets the number of highlight fragments.
                  You can apply the option to a specific field by passing the field
                  name in to the <code>oField</code> parameter. Default:  5
      
                  @member ejs.Highlight
                  @param {Integer} cnt The fragment size in characters.
                  @param {String} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            numberOfFragments: function (cnt, oField) {
                if (cnt === null && oField != null) {
                    return highlight.fields[oField].number_of_fragments;
                } else if (cnt == null) {
                    return highlight.number_of_fragments;
                }

                addOption(oField, 'number_of_fragments', cnt);
                return this;
            },

            /**
                  Sets highlight encoder.  Valid values are:
      
                  default - the default, no encoding
                  html - to encode html characters if you use html tags
      
                  @member ejs.Highlight
                  @param {String} e The encoder.  default or html
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            encoder: function (e) {
                if (e == null) {
                    return highlight.encoder;
                }

                e = e.toLowerCase();
                if (e === 'default' || e === 'html') {
                    highlight.encoder = e;
                }

                return this;
            },

            /**
                  When enabled it will cause a field to be highlighted only if a
                  query matched that field. false means that terms are highlighted
                  on all requested fields regardless if the query matches
                  specifically on them.  You can apply the option to a specific
                  field by passing the field name in to the <code>oField</code>
                  parameter.  Defaults to false.
      
                  @member ejs.Highlight
                  @param {Boolean} trueFalse If filtered docs should be highlighted.
                  @param {String} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            requireFieldMatch: function (trueFalse, oField) {
                if (trueFalse === null && oField != null) {
                    return highlight.fields[oField].require_field_match;
                } else if (trueFalse == null) {
                    return highlight.require_field_match;
                }

                addOption(oField, 'require_field_match', trueFalse);
                return this;
            },

            /**
                  Sets the max number of characters to scan while looking for the
                  start of a boundary character. You can apply the option to a
                  specific field by passing the field name in to the
                  <code>oField</code> parameter. Default:  20
      
                  @member ejs.Highlight
                  @param {Integer} cnt The max characters to scan.
                  @param {String} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boundaryMaxScan: function (cnt, oField) {
                if (cnt === null && oField != null) {
                    return highlight.fields[oField].boundary_max_scan;
                } else if (cnt == null) {
                    return highlight.boundary_max_scan;
                }

                addOption(oField, 'boundary_max_scan', cnt);
                return this;
            },

            /**
                  Set's the boundary characters.  When highlighting a field that is
                  mapped with term vectors, boundary_chars can be configured to
                  define what constitutes a boundary for highlighting. It’s a single
                  string with each boundary character defined in it. You can apply
                  the option to a specific field by passing the field name in to
                  the <code>oField</code> parameter. It defaults to ".,!? \t\n".
      
                  @member ejs.Highlight
                  @param {String} charStr The boundary chars in a string.
                  @param {String} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            boundaryChars: function (charStr, oField) {
                if (charStr === null && oField != null) {
                    return highlight.fields[oField].boundary_chars;
                } else if (charStr == null) {
                    return highlight.boundary_chars;
                }

                addOption(oField, 'boundary_chars', charStr);
                return this;
            },

            /**
                  Sets the highligher type.  You can apply the option
                  to a specific field by passing the field name in to the
                  <code>oField</code> parameter.  Valid values for order are:
      
                  fast-vector-highlighter - the fast vector based highligher
                  highlighter - the slower plain highligher
      
                  @member ejs.Highlight
                  @param {String} t The highligher.
                  @param {String} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (t, oField) {
                if (t === null && oField != null) {
                    return highlight.fields[oField].type;
                } else if (t == null) {
                    return highlight.type;
                }

                t = t.toLowerCase();
                if (t === 'fast-vector-highlighter' || t === 'highlighter' ||
                    t === 'postings') {
                    addOption(oField, 'type', t);
                }

                return this;
            },

            /**
                  Sets the fragmenter type.  You can apply the option
                  to a specific field by passing the field name in to the
                  <code>oField</code> parameter.  Valid values for order are:
      
                  simple - breaks text up into same-size fragments with no concerns
                    over spotting sentence boundaries.
                  span - breaks text up into same-size fragments but does not split
                    up Spans.
      
                  @member ejs.Highlight
                  @param {String} f The fragmenter.
                  @param {String} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fragmenter: function (f, oField) {
                if (f === null && oField != null) {
                    return highlight.fields[oField].fragmenter;
                } else if (f == null) {
                    return highlight.fragmenter;
                }

                f = f.toLowerCase();
                if (f === 'simple' || f === 'span') {
                    addOption(oField, 'fragmenter', f);
                }

                return this;
            },

            /**
                  Sets arbitrary options that can be passed to the highlighter
                  implementation in use.
      
                  @since elasticsearch 0.90.1
      
                  @member ejs.Highlight
                  @param {String} opts A map/object of option name and values.
                  @param {Object} oField An optional field name
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            options: function (opts, oField) {
                if (opts === null && oField != null) {
                    return highlight.fields[oField].options;
                } else if (opts == null) {
                    return highlight.options;
                }

                if (!isObject(opts) || isArray(opts) || isEJSObject(opts)) {
                    throw new TypeError('Parameter must be an object');
                }

                addOption(oField, 'options', opts);
                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
      
                  @member ejs.Highlight
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'highlight';
            },

            /**
                  Retrieves the internal <code>script</code> object. This is typically used by
                  internal API functions so use with caution.
      
                  @member ejs.Highlight
                  @returns {String} returns this object's internal object representation.
                  */
            toJSON: function () {
                return highlight;
            }
        };
    };

    /**
      @class
      <p>A shape which has already been indexed in another index and/or index 
      type. This is particularly useful for when you have a pre-defined list of 
      shapes which are useful to your application and you want to reference this 
      using a logical name (for example ‘New Zealand’) rather than having to 
      provide their coordinates each time.</p>
  
      @name ejs.IndexedShape
      @ejs geo
  
      @desc
      <p>Defines a shape that already exists in an index/type.</p>
  
      @param {String} type The name of the type where the shape is indexed.
      @param {String} id The document id of the shape.
  
      */
    ejs.IndexedShape = function (type, id) {

        var indexedShape = {
            type: type,
            id: id
        };

        return {

            /**
                  Sets the type which the shape is indexed under.
      
                  @member ejs.IndexedShape
                  @param {String} t a valid shape type.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (t) {
                if (t == null) {
                    return indexedShape.type;
                }

                indexedShape.type = t;
                return this;
            },

            /**
                  Sets the document id of the indexed shape.
      
                  @member ejs.IndexedShape
                  @param {String} id a valid document id.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            id: function (id) {
                if (id == null) {
                    return indexedShape.id;
                }

                indexedShape.id = id;
                return this;
            },

            /**
                  Sets the index which the shape is indexed under. 
                  Defaults to "shapes".
      
                  @member ejs.IndexedShape
                  @param {String} idx a valid index name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            index: function (idx) {
                if (idx == null) {
                    return indexedShape.index;
                }

                indexedShape.index = idx;
                return this;
            },

            /**
                  Sets the field name containing the indexed shape. 
                  Defaults to "shape".
      
                  @member ejs.IndexedShape
                  @param {String} field a valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            shapeFieldName: function (field) {
                if (field == null) {
                    return indexedShape.shape_field_name;
                }

                indexedShape.shape_field_name = field;
                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
                  
                  @member ejs.IndexedShape
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'indexed shape';
            },

            /**
                  Retrieves the internal <code>script</code> object. This is typically used by
                  internal API functions so use with caution.
      
                  @member ejs.IndexedShape
                  @returns {String} returns this object's internal object representation.
                  */
            toJSON: function () {
                return indexedShape;
            }
        };
    };

    /**
      @class
      <p>The <code>Request</code> object provides methods generating an elasticsearch request body.</p>
  
      @name ejs.Request
      @ejs request
  
      @desc
      <p>Provides methods for generating request bodies.</p>
  
      @param {Object} conf A configuration object containing the initilization
        parameters.  The following parameters can be set in the conf object:
          indices - single index name or array of index names
          types - single type name or array of types
          routing - the shard routing value
      */
    ejs.Request = function () {

        /**
            The internal query object.
            @member ejs.Request
            @property {Object} query
            */
        var query = {};

        return {

            /**
                  <p>Sets the sorting for the query.  This accepts many input formats.</p>
      
                  <dl>
                      <dd><code>sort()</code> - The current sorting values are returned.</dd>
                      <dd><code>sort(fieldName)</code> - Adds the field to the current list of sorting values.</dd>
                      <dd><code>sort(fieldName, order)</code> - Adds the field to the current list of
                          sorting with the specified order.  Order must be asc or desc.</dd>
                      <dd><code>sort(ejs.Sort)</code> - Adds the Sort value to the current list of sorting values.</dd>
                      <dd><code>sort(array)</code> - Replaces all current sorting values with values
                          from the array.  The array must contain only strings and Sort objects.</dd>
                  </dl>
      
                  <p>Multi-level sorting is supported so the order in which sort fields
                  are added to the query requests is relevant.</p>
      
                  <p>It is recommended to use <code>Sort</code> objects when possible.</p>
      
                  @member ejs.Request
                  @param {String} fieldName The field to be sorted by.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            sort: function () {
                var i, len;

                if (!has(query, "sort")) {
                    query.sort = [];
                }

                if (arguments.length === 0) {
                    return query.sort;
                }

                // if passed a single argument
                if (arguments.length === 1) {
                    var sortVal = arguments[0];

                    if (isString(sortVal)) {
                        // add  a single field name
                        query.sort.push(sortVal);
                    } else if (isSort(sortVal)) {
                        // add the Sort object
                        query.sort.push(sortVal.toJSON());
                    } else if (isArray(sortVal)) {
                        // replace with all values in the array
                        // the values must be a fieldName (string) or a
                        // Sort object.  Any other type throws an Error.
                        query.sort = [];
                        for (i = 0, len = sortVal.length; i < len; i++) {
                            if (isString(sortVal[i])) {
                                query.sort.push(sortVal[i]);
                            } else if (isSort(sortVal[i])) {
                                query.sort.push(sortVal[i].toJSON());
                            } else {
                                throw new TypeError('Invalid object in array');
                            }
                        }
                    } else {
                        // Invalid object type as argument.
                        throw new TypeError('Argument must be string, Sort, or array');
                    }
                } else if (arguments.length === 2) {
                    // handle the case where a single field name and order are passed
                    var field = arguments[0],
                      order = arguments[1];

                    if (isString(field) && isString(order)) {
                        order = order.toLowerCase();
                        if (order === 'asc' || order === 'desc') {
                            var sortObj = {};
                            sortObj[field] = { order: order };
                            query.sort.push(sortObj);
                        }
                    }
                }

                return this;
            },

            /**
                 Enables score computation and tracking during sorting.  Be default,
                 when sorting scores are not computed.
      
                  @member ejs.Request
                  @param {Boolean} trueFalse If scores should be computed and tracked.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            trackScores: function (trueFalse) {
                if (trueFalse == null) {
                    return query.track_scores;
                }

                query.track_scores = trueFalse;
                return this;
            },

            /**
                  A search result set could be very large (think Google). Setting the
                  <code>from</code> parameter allows you to page through the result set
                  by making multiple request. This parameters specifies the starting
                  result/document number point. Combine with <code>size()</code> to achieve paging.
      
                  @member ejs.Request
                  @param {Array} f The offset at which to start fetching results/documents from the result set.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            from: function (f) {
                if (f == null) {
                    return query.from;
                }

                query.from = f;
                return this;
            },

            /**
                  Sets the number of results/documents to be returned. This is set on a per page basis.
      
                  @member ejs.Request
                  @param {Integer} s The number of results that are to be returned by the search.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            size: function (s) {
                if (s == null) {
                    return query.size;
                }

                query.size = s;
                return this;
            },

            /**
                  A timeout, bounding the request to be executed within the
                  specified time value and bail when expired. Defaults to no timeout.
      
                  <p>This option is valid during the following operations:
                      <code>search</code> and <code>delete by query</code></p>
      
                  @member ejs.Request
                  @param {Long} t The timeout value in milliseconds.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            timeout: function (t) {
                if (t == null) {
                    return query.timeout;
                }

                query.timeout = t;
                return this;
            },


            /**
                  By default, searches return full documents, meaning every property or field.
                  This method allows you to specify which fields you want returned.
      
                  Pass a single field name and it is appended to the current list of
                  fields.  Pass an array of fields and it replaces all existing
                  fields.
      
                  @member ejs.Request
                  @param {(String|String[])} s The field as a string or fields as array
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fields: function (fieldList) {
                if (fieldList == null) {
                    return query.fields;
                }

                if (query.fields == null) {
                    query.fields = [];
                }

                if (isString(fieldList)) {
                    query.fields.push(fieldList);
                } else if (isArray(fieldList)) {
                    query.fields = fieldList;
                } else {
                    throw new TypeError('Argument must be a string or an array');
                }

                return this;
            },

            /**
                  Allows to control how the _source field is returned with every hit.
                  By default operations return the contents of the _source field
                  unless you have used the fields parameter or if the _source field
                  is disabled.  Set the includes parameter to false to completely
                  disable returning the source field.
      
                  @member ejs.Request
                  @param {(String|Boolean|String[])} includes The field or list of fields to include as array.
                    Set to a boolean false to disable the source completely.
                  @param {(String|String[])} excludes The  optional field or list of fields to exclude.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            source: function (includes, excludes) {
                if (includes == null && excludes == null) {
                    return query._source;
                }

                if (!isArray(includes) && !isString(includes) && !isBoolean(includes)) {
                    throw new TypeError('Argument includes must be a string, an array, or a boolean');
                }

                if (excludes != null && !isArray(excludes) && !isString(excludes)) {
                    throw new TypeError('Argument excludes must be a string or an array');
                }

                if (isBoolean(includes)) {
                    query._source = includes;
                } else {
                    query._source = {
                        includes: includes
                    };

                    if (excludes != null) {
                        query._source.excludes = excludes;
                    }
                }

                return this;
            },

            /**
                  Once a query executes, you can use rescore to run a secondary, more
                  expensive query to re-order the results.
      
                  @member ejs.Request
                  @param {Rescore} r The rescore configuration.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            rescore: function (r) {
                if (r == null) {
                    return query.rescore;
                }

                if (!isRescore(r)) {
                    throw new TypeError('Argument must be a Rescore');
                }

                query.rescore = r.toJSON();

                return this;
            },

            /**
                  Allows you to set the specified query on this search object. This is the
                  query that will be used when the search is executed.
      
                  @member ejs.Request
                  @param {Query} someQuery Any valid <code>Query</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            query: function (someQuery) {
                if (someQuery == null) {
                    return query.query;
                }

                if (!isQuery(someQuery)) {
                    throw new TypeError('Argument must be a Query');
                }

                query.query = someQuery.toJSON();
                return this;
            },

            /**
                  Allows you to set the specified facet on this request object. Multiple facets can
                  be set, all of which will be returned when the search is executed.
      
                  @member ejs.Request
                  @param {Facet} facet Any valid <code>Facet</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            facet: function (facet) {
                if (facet == null) {
                    return query.facets;
                }

                if (query.facets == null) {
                    query.facets = {};
                }

                if (!isFacet(facet)) {
                    throw new TypeError('Argument must be a Facet');
                }

                extend(query.facets, facet.toJSON());

                return this;
            },

            /**
            Add an aggregation.  This method can be called multiple times
            in order to set multiple nested aggregations that will be executed
            at the same time as the search request.
      
            @member ejs.Request
            @param {Aggregation} agg Any valid <code>Aggregation</code> object.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            aggregation: function (agg) {
                if (agg == null) {
                    return query.aggs;
                }

                if (query.aggs == null) {
                    query.aggs = {};
                }

                if (!isAggregation(agg)) {
                    throw new TypeError('Argument must be an Aggregation');
                }

                extend(query.aggs, agg.toJSON());

                return this;
            },

            /**
            Add an aggregation.  This method can be called multiple times
            in order to set multiple nested aggregations that will be executed
            at the same time as the search request.  Alias for the aggregation method.
      
            @member ejs.Request
            @param {Aggregation} agg Any valid <code>Aggregation</code> object.
            @returns {Object} returns <code>this</code> so that calls can be chained.
            */
            agg: function (agg) {
                return this.aggregation(agg);
            },

            /**
                  Allows you to set a specified filter on this request object.
      
                  @member ejs.Request
                  @param {Object} filter Any valid <code>Filter</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            filter: function (filter) {
                if (filter == null) {
                    return query.filter;
                }

                if (!isFilter(filter)) {
                    throw new TypeError('Argument must be a Filter');
                }

                query.filter = filter.toJSON();
                return this;
            },

            /**
                  Performs highlighting based on the <code>Highlight</code>
                  settings.
      
                  @member ejs.Request
                  @param {Highlight} h A valid Highlight object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            highlight: function (h) {
                if (h == null) {
                    return query.highlight;
                }

                if (!isHighlight(h)) {
                    throw new TypeError('Argument must be a Highlight object');
                }

                query.highlight = h.toJSON();
                return this;
            },

            /**
                  Allows you to set the specified suggester on this request object.
                  Multiple suggesters can be set, all of which will be returned when
                  the search is executed.  Global suggestion text can be set by
                  passing in a string vs. a <code>Suggest</code> object.
      
                  @since elasticsearch 0.90
      
                  @member ejs.Request
                  @param {(String|Suggest)} s A valid Suggest object or a String to
                    set as the global suggest text.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            suggest: function (s) {
                if (s == null) {
                    return query.suggest;
                }

                if (query.suggest == null) {
                    query.suggest = {};
                }

                if (isString(s)) {
                    query.suggest.text = s;
                } else if (isSuggest(s)) {
                    extend(query.suggest, s.toJSON());
                } else {
                    throw new TypeError('Argument must be a string or Suggest object');
                }

                return this;
            },

            /**
                  Computes a document property dynamically based on the supplied <code>ScriptField</code>.
      
                  @member ejs.Request
                  @param {ScriptField} oScriptField A valid <code>ScriptField</code>.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scriptField: function (oScriptField) {
                if (oScriptField == null) {
                    return query.script_fields;
                }

                if (query.script_fields == null) {
                    query.script_fields = {};
                }

                if (!isScriptField(oScriptField)) {
                    throw new TypeError('Argument must be a ScriptField');
                }

                extend(query.script_fields, oScriptField.toJSON());
                return this;
            },

            /**
                  Boosts hits in the specified index by the given boost value.
      
                  @member ejs.Request
                  @param {String} index the index to boost
                  @param {Double} boost the boost value
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            indexBoost: function (index, boost) {
                if (query.indices_boost == null) {
                    query.indices_boost = {};
                }

                if (arguments.length === 0) {
                    return query.indices_boost;
                }

                query.indices_boost[index] = boost;
                return this;
            },

            /**
                  Enable/Disable explanation of score for each search result.
      
                  @member ejs.Request
                  @param {Boolean} trueFalse true to enable, false to disable
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            explain: function (trueFalse) {
                if (trueFalse == null) {
                    return query.explain;
                }

                query.explain = trueFalse;
                return this;
            },

            /**
                  Enable/Disable returning version number for each search result.
      
                  @member ejs.Request
                  @param {Boolean} trueFalse true to enable, false to disable
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            version: function (trueFalse) {
                if (trueFalse == null) {
                    return query.version;
                }

                query.version = trueFalse;
                return this;
            },

            /**
                  Filters out search results will scores less than the specified minimum score.
      
                  @member ejs.Request
                  @param {Double} min a positive <code>double</code> value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minScore: function (min) {
                if (min == null) {
                    return query.min_score;
                }

                query.min_score = min;
                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
      
                  @member ejs.Request
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'request';
            },

            /**
                  Retrieves the internal <code>query</code> object. This is typically used by
                  internal API functions so use with caution.
      
                  @member ejs.Request
                  @returns {String} returns this object's internal object representation.
                  */
            toJSON: function () {
                return query;
            }

        };
    };

    /**
      @class
      <p>A method that allows to rescore queries with a typically more expensive.</p>
  
      @name ejs.Rescore
      @ejs request
  
      @desc
      <p>Defines an operation that rescores a query with another query.</p>
  
      @param {Number} windowSize The optional number of documents to reorder per shard.
      @param {Query} windowSize The optional query to use for rescoring.
  
      */
    ejs.Rescore = function (windowSize, qry) {

        if (windowSize != null && !isNumber(windowSize)) {
            throw new TypeError('Argument must be a Number');
        }

        if (qry != null && !isQuery(qry)) {
            throw new TypeError('Argument must be a Query');
        }

        var rescore = {
            query: {}
        };

        if (windowSize != null) {
            rescore.window_size = windowSize;
        }

        if (qry != null) {
            rescore.query.rescore_query = qry.toJSON();
        }

        return {

            /**
                  Sets the query used by the rescoring.
      
                  @member ejs.Rescore
                  @param {Query} someQuery a valid query.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            rescoreQuery: function (someQuery) {
                if (someQuery == null) {
                    return rescore.query.rescore_query;
                }

                if (!isQuery(someQuery)) {
                    throw new TypeError('Argument must be a Query');
                }

                rescore.query.rescore_query = someQuery.toJSON();
                return this;
            },

            /**
                  Sets the weight assigned to the original query of the rescoring.
      
                  @member ejs.Rescore
                  @param {Number} weight a valid query weight.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            queryWeight: function (weight) {
                if (weight == null) {
                    return rescore.query.query_weight;
                }

                if (!isNumber(weight)) {
                    throw new TypeError('Argument must be a Number');
                }

                rescore.query.query_weight = weight;
                return this;
            },

            /**
                  Sets the weight assigned to the query used to rescore the original query.
      
                  @member ejs.Rescore
                  @param {Number} weight a valid rescore query weight.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            rescoreQueryWeight: function (weight) {
                if (weight == null) {
                    return rescore.query.rescore_query_weight;
                }

                if (!isNumber(weight)) {
                    throw new TypeError('Argument must be a Number');
                }

                rescore.query.rescore_query_weight = weight;
                return this;
            },

            /**
                  Sets the window_size parameter of the rescoring.
      
                  @member ejs.Rescore
                  @param {Number} size a valid window size.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            windowSize: function (size) {
                if (size == null) {
                    return rescore.window_size;
                }

                if (!isNumber(size)) {
                    throw new TypeError('Argument must be a Number');
                }

                rescore.window_size = size;
                return this;
            },

            /**
                  Sets the scoring mode.  Valid values are:
                  
                  total - default mode, the scores combined
                  multiply - the scores multiplied
                  min - the lowest of the scores
                  max - the highest score 
                  avg - the average of the scores
      
                  @member ejs.Rescore
                  @param {String} s The score mode as a string.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            scoreMode: function (s) {
                if (s == null) {
                    return rescore.query.score_mode;
                }

                s = s.toLowerCase();
                if (s === 'total' || s === 'min' || s === 'max' || s === 'multiply' ||
                  s === 'avg') {
                    rescore.query.score_mode = s;
                }

                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
      
                  @member ejs.Rescore
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'rescore';
            },

            /**
                  Retrieves the internal <code>script</code> object. This is typically used by
                  internal API functions so use with caution.
      
                  @member ejs.Rescore
                  @returns {String} returns this object's internal object representation.
                  */
            toJSON: function () {
                return rescore;
            }
        };
    };
    /**
      @class
      <p>ScriptField's allow you create dynamic fields on stored documents at query
      time. For example, you might have a set of document thats containsthe fields
      <code>price</code> and <code>quantity</code>. At query time, you could define a computed
      property that dynamically creates a new field called <code>total</code>in each document
      based on the calculation <code>price * quantity</code>.</p>
  
      @name ejs.ScriptField
      @ejs request
  
      @desc
      <p>Computes dynamic document properties based on information from other fields.</p>
  
      @param {String} fieldName A name of the script field to create.
  
      */
    ejs.ScriptField = function (fieldName) {
        var script = {};

        script[fieldName] = {};

        return {

            /**
                  The script language being used. Currently supported values are
                  <code>javascript</code> and <code>mvel</code>.
      
                  @member ejs.ScriptField
                  @param {String} language The language of the script.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lang: function (language) {
                if (language == null) {
                    return script[fieldName].lang;
                }

                script[fieldName].lang = language;
                return this;
            },

            /**
                  Sets the script/code that will be used to perform the calculation.
      
                  @member ejs.ScriptField
                  @param {String} expression The script/code to use.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            script: function (expression) {
                if (expression == null) {
                    return script[fieldName].script;
                }

                script[fieldName].script = expression;
                return this;
            },

            /**
                  Allows you to set script parameters to be used during the execution of the script.
      
                  @member ejs.ScriptField
                  @param {Object} oParams An object containing key/value pairs representing param name/value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            params: function (oParams) {
                if (oParams == null) {
                    return script[fieldName].params;
                }

                script[fieldName].params = oParams;
                return this;
            },

            /**
                  If execeptions thrown from the script should be ignored or not.
                  Default: false
      
                  @member ejs.ScriptField
                  @param {Boolean} trueFalse if execptions should be ignored
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            ignoreFailure: function (trueFalse) {
                if (trueFalse == null) {
                    return script[fieldName].ignore_failure;
                }

                script[fieldName].ignore_failure = trueFalse;
                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
                  
                  @member ejs.ScriptField
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'script field';
            },

            /**
                  Retrieves the internal <code>script</code> object. This is typically used by
                  internal API functions so use with caution.
      
                  @member ejs.ScriptField
                  @returns {String} returns this object's internal <code>facet</code> property.
                  */
            toJSON: function () {
                return script;
            }
        };
    };

    /**
      @class
      <p>A Shape object that can be used in queries and filters that 
      take a Shape.  Shape uses the GeoJSON format.</p>
  
      <p>See http://www.geojson.org/</p>
  
      @name ejs.Shape
      @ejs geo
  
      @desc
      <p>Defines a shape</p>
  
      @param {String} type A valid shape type.
      @param {Array} coords An valid coordinat definition for the given shape.
  
      */
    ejs.Shape = function (type, coords) {

        var
          shape = {},
          validType = function (t) {
              var valid = false;
              if (t === 'point' || t === 'linestring' || t === 'polygon' ||
                t === 'multipoint' || t === 'envelope' || t === 'multipolygon' ||
                t === 'circle' || t === 'multilinestring') {
                  valid = true;
              }

              return valid;
          };

        type = type.toLowerCase();
        if (validType(type)) {
            shape.type = type;
            shape.coordinates = coords;
        }

        return {

            /**
                  Sets the shape type.  Can be set to one of:  point, linestring, polygon,
                  multipoint, envelope, or multipolygon.
      
                  @member ejs.Shape
                  @param {String} t a valid shape type.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (t) {
                if (t == null) {
                    return shape.type;
                }

                t = t.toLowerCase();
                if (validType(t)) {
                    shape.type = t;
                }

                return this;
            },

            /**
                  Sets the coordinates for the shape definition.  Note, the coordinates
                  are not validated in this api.  Please see GeoJSON and ElasticSearch
                  documentation for correct coordinate definitions.
      
                  @member ejs.Shape
                  @param {Array} c a valid coordinates definition for the shape.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            coordinates: function (c) {
                if (c == null) {
                    return shape.coordinates;
                }

                shape.coordinates = c;
                return this;
            },

            /**
                  Sets the radius for parsing a circle <code>Shape</code>.
      
                  @member ejs.Shape
                  @param {String} r a valid radius value for a circle.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            radius: function (r) {
                if (r == null) {
                    return shape.radius;
                }

                shape.radius = r;
                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
                  
                  @member ejs.Shape
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'shape';
            },

            /**
                  Retrieves the internal <code>script</code> object. This is typically used by
                  internal API functions so use with caution.
      
                  @member ejs.Shape
                  @returns {String} returns this object's internal object representation.
                  */
            toJSON: function () {
                return shape;
            }
        };
    };

    /**
      @class
      <p>A Sort object that can be used in on the Request object to specify 
      various types of sorting.</p>
  
      <p>See http://www.elasticsearch.org/guide/reference/api/search/sort.html</p>
  
      @name ejs.Sort
      @ejs request
  
      @desc
      <p>Defines a sort value</p>
  
      @param {String} fieldName The fieldName to sort against.  Defaults to _score
        if not specified.
      */
    ejs.Sort = function (fieldName) {

        // default to sorting against the documents score.
        if (fieldName == null) {
            fieldName = '_score';
        }

        var sort = {},
          key = fieldName, // defaults to field search
          geo_key = '_geo_distance', // used when doing geo distance sort
          script_key = '_script'; // used when doing script sort

        // defaults to a field sort
        sort[key] = {};

        return {

            /**
                  Set's the field to sort on
      
                  @member ejs.Sort
                  @param {String} f The name of a field 
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (f) {
                var oldValue = sort[key];

                if (f == null) {
                    return fieldName;
                }

                delete sort[key];
                fieldName = f;
                key = f;
                sort[key] = oldValue;

                return this;
            },

            /**
                  Enables sorting based on a distance from a GeoPoint
      
                  @member ejs.Sort
                  @param {GeoPoint} point A valid GeoPoint object
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            geoDistance: function (point) {
                var oldValue = sort[key];

                if (point == null) {
                    return sort[key][fieldName];
                }

                if (!isGeoPoint(point)) {
                    throw new TypeError('Argument must be a GeoPoint');
                }

                delete sort[key];
                key = geo_key;
                sort[key] = oldValue;
                sort[key][fieldName] = point.toJSON();

                return this;
            },

            /**
                  Enables sorting based on a script.
      
                  @member ejs.Sort
                  @param {String} scriptCode The script code as a string
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            script: function (scriptCode) {
                var oldValue = sort[key];

                if (scriptCode == null) {
                    return sort[key].script;
                }

                delete sort[key];
                key = script_key;
                sort[key] = oldValue;
                sort[key].script = scriptCode;

                return this;
            },

            /**
                  Sets the sort order.  Valid values are:
                
                  asc - for ascending order
                  desc - for descending order
      
                  Valid during sort types:  field, geo distance, and script
                
                  @member ejs.Sort
                  @param {String} o The sort order as a string, asc or desc.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            order: function (o) {
                if (o == null) {
                    return sort[key].order;
                }

                o = o.toLowerCase();
                if (o === 'asc' || o === 'desc') {
                    sort[key].order = o;
                }

                return this;
            },

            /**
                  Sets the sort order to ascending (asc).  Same as calling
                  <code>order('asc')</code>.
                
                  @member ejs.Sort
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            asc: function () {
                sort[key].order = 'asc';
                return this;
            },

            /**
                  Sets the sort order to descending (desc).  Same as calling
                  <code>order('desc')</code>.
                
                  @member ejs.Sort
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            desc: function () {
                sort[key].order = 'desc';
                return this;
            },

            /**
                  Sets the order with a boolean value.  
                
                  true = descending sort order
                  false = ascending sort order
      
                  Valid during sort types:  field, geo distance, and script
                
                  @member ejs.Sort
                  @param {Boolean} trueFalse If sort should be in reverse order.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            reverse: function (trueFalse) {
                if (trueFalse == null) {
                    return sort[key].reverse;
                }

                sort[key].reverse = trueFalse;
                return this;
            },

            /**
                  Sets the value to use for missing fields.  Valid values are:
                
                  _last - to put documents with the field missing last
                  _first - to put documents with the field missing first
                  {String} - any string value to use as the sort value.
      
                  Valid during sort types:  field
                
                  @member ejs.Sort
                  @param {String} m The value to use for documents with the field missing.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            missing: function (m) {
                if (m == null) {
                    return sort[key].missing;
                }

                sort[key].missing = m;
                return this;
            },

            /**
                  Sets if the sort should ignore unmapped fields vs throwing an error.
      
                  Valid during sort types:  field
                
                  @member ejs.Sort
                  @param {Boolean} trueFalse If sort should ignore unmapped fields.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            ignoreUnmapped: function (trueFalse) {
                if (trueFalse == null) {
                    return sort[key].ignore_unmapped;
                }

                sort[key].ignore_unmapped = trueFalse;
                return this;
            },

            /**
                   Sets the distance unit.  Valid values are "mi" for miles or "km"
                   for kilometers. Defaults to "km".
      
                   Valid during sort types:  geo distance
                 
                   @member ejs.Sort
                   @param {Number} unit the unit of distance measure.
                   @returns {Object} returns <code>this</code> so that calls can be chained.
                   */
            unit: function (unit) {
                if (unit == null) {
                    return sort[key].unit;
                }

                unit = unit.toLowerCase();
                if (unit === 'mi' || unit === 'km') {
                    sort[key].unit = unit;
                }

                return this;
            },

            /**
                  If the lat/long points should be normalized to lie within their
                  respective normalized ranges.
                
                  Normalized ranges are:
                  lon = -180 (exclusive) to 180 (inclusive) range
                  lat = -90 to 90 (both inclusive) range
      
                  Valid during sort types:  geo distance
                
                  @member ejs.Sort
                  @param {String} trueFalse True if the coordinates should be normalized. False otherwise.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            normalize: function (trueFalse) {
                if (trueFalse == null) {
                    return sort[key].normalize;
                }

                sort[key].normalize = trueFalse;
                return this;
            },

            /**
                  How to compute the distance. Can either be arc (better precision) 
                  or plane (faster). Defaults to arc.
      
                  Valid during sort types:  geo distance
                
                  @member ejs.Sort
                  @param {String} type The execution type as a string.  
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            distanceType: function (type) {
                if (type == null) {
                    return sort[key].distance_type;
                }

                type = type.toLowerCase();
                if (type === 'arc' || type === 'plane') {
                    sort[key].distance_type = type;
                }

                return this;
            },

            /**
                  Sets parameters that will be applied to the script.  Overwrites 
                  any existing params.
      
                  Valid during sort types:  script
                
                  @member ejs.Sort
                  @param {Object} p An object where the keys are the parameter name and 
                    values are the parameter value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            params: function (p) {
                if (p == null) {
                    return sort[key].params;
                }

                sort[key].params = p;
                return this;
            },

            /**
                  Sets the script language.
      
                  Valid during sort types:  script
                
                  @member ejs.Sort
                  @param {String} lang The script language, default mvel.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            lang: function (lang) {
                if (lang == null) {
                    return sort[key].lang;
                }

                sort[key].lang = lang;
                return this;
            },

            /**
                  Sets the script sort type.  Valid values are:
                
                  <dl>
                      <dd><code>string</code> - script return value is sorted as a string</dd>
                      <dd><code>number</code> - script return value is sorted as a number</dd>
                  <dl>
      
                  Valid during sort types:  script
                
                  @member ejs.Sort
                  @param {String} type The sort type.  Either string or number.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            type: function (type) {
                if (type == null) {
                    return sort[key].type;
                }

                type = type.toLowerCase();
                if (type === 'string' || type === 'number') {
                    sort[key].type = type;
                }

                return this;
            },

            /**
                  Sets the sort mode.  Valid values are:
                
                  <dl>
                      <dd><code>min</code> - sort by lowest value</dd>
                      <dd><code>max</code> - sort by highest value</dd>
                      <dd><code>sum</code> - sort by the sum of all values</dd>
                      <dd><code>avg</code> - sort by the average of all values</dd>
                  <dl>
                  
                  Valid during sort types:  field, geo distance
                
                  @since elasticsearch 0.90
                  @member ejs.Sort
                  @param {String} m The sort mode.  Either min, max, sum, or avg.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            mode: function (m) {
                if (m == null) {
                    return sort[key].mode;
                }

                m = m.toLowerCase();
                if (m === 'min' || m === 'max' || m === 'sum' || m === 'avg') {
                    sort[key].mode = m;
                }

                return this;
            },

            /**
                  Sets the path of the nested object.
      
                  Valid during sort types:  field, geo distance
                
                  @since elasticsearch 0.90
                  @member ejs.Sort
                  @param {String} path The nested path value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            nestedPath: function (path) {
                if (path == null) {
                    return sort[key].nested_path;
                }

                sort[key].nested_path = path;
                return this;
            },

            /**
                  <p>Allows you to set a filter that nested objects must match
                  in order to be considered during sorting.</p>
      
                  Valid during sort types: field, geo distance
                  
                  @since elasticsearch 0.90
                  @member ejs.Sort
                  @param {Object} oFilter A valid <code>Filter</code> object.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            nestedFilter: function (oFilter) {
                if (oFilter == null) {
                    return sort[key].nested_filter;
                }

                if (!isFilter(oFilter)) {
                    throw new TypeError('Argument must be a Filter');
                }

                sort[key].nested_filter = oFilter.toJSON();
                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
                
                  @member ejs.Sort
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'sort';
            },

            /**
                  Retrieves the internal <code>script</code> object. This is typically used by
                  internal API functions so use with caution.
      
                  @member ejs.Sort
                  @returns {String} returns this object's internal object representation.
                  */
            toJSON: function () {
                return sort;
            }
        };
    };

    /**
      @class
      @suggester
      <p>The completion suggester is a so-called prefix suggester. It does not do spell 
      correction like the term or phrase suggesters but allows basic auto-complete functionality.</p>
  
      @name ejs.CompletionSuggester
      @ejs suggest
      @borrows ejs.SuggesterMixin.text as text
      @borrows ejs.SuggesterMixin._type as _type
      @borrows ejs.SuggesterMixin.toJSON as toJSON
      @borrows ejs.SuggestContextMixin.analyzer as analyzer
      @borrows ejs.SuggestContextMixin.field as field
      @borrows ejs.SuggestContextMixin.size as size
      @borrows ejs.SuggestContextMixin.shardSize as shardSize
    
      @since elasticsearch 0.90.4
    
      @desc
      <p>A suggester that allows basic auto-complete functionality.</p>
  
      @param {String} name The name which be used to refer to this suggester.
      */
    ejs.CompletionSuggester = function (name) {

        var
          _context,
          _common = ejs.SuggesterMixin(name),
          suggest = _common.toJSON();

        suggest[name].completion = {};
        _context = ejs.SuggestContextMixin(suggest[name].completion);

        return extend(_common, _context, {

            /**
                  <p>Enable fuzzy completions which means a can spell a word
                  incorrectly and still get a suggestion.</p>
      
                  @member ejs.CompletionSuggester
                  @param {Boolean} trueFalse true to enable fuzzy completions, false to disable.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            fuzzy: function (trueFalse) {
                if (trueFalse == null) {
                    return suggest[name].completion.fuzzy;
                }

                if (trueFalse && suggest[name].completion.fuzzy == null) {
                    suggest[name].completion.fuzzy = {};
                } else if (!trueFalse && suggest[name].completion.fuzzy != null) {
                    delete suggest[name].completion.fuzzy;
                }

                return this;
            },

            /**
                  <p>Sets if transpositions should be counted as one or two changes, defaults 
                  to true when fuzzy is enabled.  Automatically enables fuzzy suggestions
                  when set to any value.</p>
      
                  @member ejs.CompletionSuggester
                  @param {Boolean} trueFalse true to enable transpositions.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            transpositions: function (trueFalse) {
                if (suggest[name].completion.fuzzy == null) {
                    suggest[name].completion.fuzzy = {};
                }

                if (trueFalse == null) {
                    return suggest[name].completion.fuzzy.transpositions;
                }

                suggest[name].completion.fuzzy.transpositions = trueFalse;
                return this;
            },

            /**
                  <p>Sets all are measurements (like edit distance, transpositions and lengths) 
                  in unicode code points (actual letters) instead of bytes.  Automatically 
                  enables fuzzy suggestions when set to any value.</p>
      
                  @member ejs.CompletionSuggester
                  @param {Boolean} trueFalse true to set unicode aware, false to disable.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            unicodeAware: function (trueFalse) {
                if (suggest[name].completion.fuzzy == null) {
                    suggest[name].completion.fuzzy = {};
                }

                if (trueFalse == null) {
                    return suggest[name].completion.fuzzy.unicode_aware;
                }

                suggest[name].completion.fuzzy.unicode_aware = trueFalse;
                return this;
            },

            /**
                  <p>Maximum edit distance (fuzziness), defaults to 1.  Automatically 
                  enables fuzzy suggestions when set to any value.</p>
      
                  @member ejs.CompletionSuggester
                  @param {Integer} d A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            editDistance: function (d) {
                if (suggest[name].completion.fuzzy == null) {
                    suggest[name].completion.fuzzy = {};
                }

                if (d == null) {
                    return suggest[name].completion.fuzzy.edit_distance;
                }

                suggest[name].completion.fuzzy.edit_distance = d;
                return this;
            },

            /**
                  <p>Minimum length of the input before fuzzy suggestions are returned, defaults 
                  to 3.  Automatically enables fuzzy suggestions when set to any value.</p>
      
                  @member ejs.CompletionSuggester
                  @param {Integer} m A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            minLength: function (m) {
                if (suggest[name].completion.fuzzy == null) {
                    suggest[name].completion.fuzzy = {};
                }

                if (m == null) {
                    return suggest[name].completion.fuzzy.min_length;
                }

                suggest[name].completion.fuzzy.min_length = m;
                return this;
            },

            /**
                  <p>Minimum length of the input, which is not checked for fuzzy alternatives, defaults 
                  to 1.  Automatically enables fuzzy suggestions when set to any value.</p>
      
                  @member ejs.CompletionSuggester
                  @param {Integer} l A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            prefixLength: function (l) {
                if (suggest[name].completion.fuzzy == null) {
                    suggest[name].completion.fuzzy = {};
                }

                if (l == null) {
                    return suggest[name].completion.fuzzy.prefix_length;
                }

                suggest[name].completion.fuzzy.prefix_length = l;
                return this;
            }

        });
    };

    /**
      @class
      <p>DirectGenerator is a candidate generator for <code>PhraseSuggester</code>.
      It generates terms based on edit distance and operators much like the
      <code>TermSuggester</code>.</p>
  
      @name ejs.DirectGenerator
      @ejs suggest
      @borrows ejs.DirectSettingsMixin.accuracy as accuracy
      @borrows ejs.DirectSettingsMixin.suggestMode as suggestMode
      @borrows ejs.DirectSettingsMixin.sort as sort
      @borrows ejs.DirectSettingsMixin.stringDistance as stringDistance
      @borrows ejs.DirectSettingsMixin.maxEdits as maxEdits
      @borrows ejs.DirectSettingsMixin.maxInspections as maxInspections
      @borrows ejs.DirectSettingsMixin.maxTermFreq as maxTermFreq
      @borrows ejs.DirectSettingsMixin.prefixLength as prefixLength
      @borrows ejs.DirectSettingsMixin.minWordLen as minWordLen
      @borrows ejs.DirectSettingsMixin.minDocFreq as minDocFreq
  
      @since elasticsearch 0.90
    
      @desc
      <p>A candidate generator that generates terms based on edit distance.</p>
    
      */
    ejs.DirectGenerator = function () {


        var

        generator = {},
        _common = ejs.DirectSettingsMixin(generator);

        return extend(_common, {

            /**
                  <p>Sets an analyzer that is applied to each of the tokens passed to 
                  this generator.  The analyzer is applied to the original tokens,
                  not the generated tokens.</p>
      
                  @member ejs.DirectGenerator
                  @param {String} analyzer A valid analyzer name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            preFilter: function (analyzer) {
                if (analyzer == null) {
                    return generator.pre_filter;
                }

                generator.pre_filter = analyzer;
                return this;
            },

            /**
                  <p>Sets an analyzer that is applied to each of the generated tokens 
                  before they are passed to the actual phrase scorer.</p>
      
                  @member ejs.DirectGenerator
                  @param {String} analyzer A valid analyzer name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            postFilter: function (analyzer) {
                if (analyzer == null) {
                    return generator.post_filter;
                }

                generator.post_filter = analyzer;
                return this;
            },

            /**
                  <p>Sets the field used to generate suggestions from.</p>
      
                  @member ejs.DirectGenerator
                  @param {String} field A valid field name.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            field: function (field) {
                if (field == null) {
                    return generator.field;
                }

                generator.field = field;
                return this;
            },

            /**
                  <p>Sets the number of suggestions returned for each token.</p>
      
                  @member ejs.DirectGenerator
                  @param {Integer} s A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            size: function (s) {
                if (s == null) {
                    return generator.size;
                }

                generator.size = s;
                return this;
            },

            /**
                  The type of ejs object.  For internal use only.
              
                  @member ejs.DirectGenerator
                  @returns {String} the type of object
                  */
            _type: function () {
                return 'generator';
            },

            /**
                  <p>Retrieves the internal <code>generator</code> object. This is typically used by
                     internal API functions so use with caution.</p>
      
                  @member ejs.DirectGenerator
                  @returns {String} returns this object's internal <code>generator</code> property.
                  */
            toJSON: function () {
                return generator;
            }
        });
    };

    /**
      @class
      <p>PhraseSuggester extends the <code>PhraseSuggester</code> and suggests
      entire corrected phrases instead of individual tokens.  The individual
      phrase suggestions are weighted based on ngram-langugage models. In practice
      it will be able to make better decision about which tokens to pick based on
      co-occurence and frequencies.</p>
  
      @name ejs.PhraseSuggester
      @ejs suggest
      @borrows ejs.SuggesterMixin.text as text
      @borrows ejs.SuggesterMixin._type as _type
      @borrows ejs.SuggesterMixin.toJSON as toJSON
      @borrows ejs.SuggestContextMixin.analyzer as analyzer
      @borrows ejs.SuggestContextMixin.field as field
      @borrows ejs.SuggestContextMixin.size as size
      @borrows ejs.SuggestContextMixin.shardSize as shardSize
  
      @since elasticsearch 0.90
  
      @desc
      <p>A suggester that suggests entire corrected phrases.</p>
  
      @param {String} name The name which be used to refer to this suggester.
      */
    ejs.PhraseSuggester = function (name) {

        var
          _context,
          _common = ejs.SuggesterMixin(name),
          suggest = _common.toJSON();

        suggest[name].phrase = {};
        _context = ejs.SuggestContextMixin(suggest[name].phrase);

        return extend(_common, _context, {

            /**
                  <p>Sets the likelihood of a term being a misspelled even if the
                  term exists in the dictionary. The default it 0.95 corresponding
                  to 5% or the real words are misspelled.</p>
      
                  @member ejs.PhraseSuggester
                  @param {Double} l A positive double value greater than 0.0.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            realWordErrorLikelihood: function (l) {
                if (l == null) {
                    return suggest[name].phrase.real_word_error_likelihood;
                }

                suggest[name].phrase.real_word_error_likelihood = l;
                return this;
            },

            /**
                  <p>Sets the confidence level defines a factor applied to the input
                  phrases score which is used as a threshold for other suggest
                  candidates. Only candidates that score higher than the threshold
                  will be included in the result.</p>
      
                  @member ejs.PhraseSuggester
                  @param {Double} c A positive double value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            confidence: function (c) {
                if (c == null) {
                    return suggest[name].phrase.confidence;
                }

                suggest[name].phrase.confidence = c;
                return this;
            },

            /**
                  <p>Sets the separator that is used to separate terms in the bigram
                  field. If not set the whitespce character is used as a
                  separator.</p>
      
                  @member ejs.PhraseSuggester
                  @param {String} sep A string separator.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            separator: function (sep) {
                if (sep == null) {
                    return suggest[name].phrase.separator;
                }

                suggest[name].phrase.separator = sep;
                return this;
            },

            /**
                  <p>Sets the maximum percentage of the terms that at most
                  considered to be misspellings in order to form a correction.</p>
      
                  @member ejs.PhraseSuggester
                  @param {Double} c A positive double value greater between 0 and 1.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            maxErrors: function (max) {
                if (max == null) {
                    return suggest[name].phrase.max_errors;
                }

                suggest[name].phrase.max_errors = max;
                return this;
            },

            /**
                  <p>Sets the max size of the n-grams (shingles) in the field. If
                  the field doesn't contain n-grams (shingles) this should be
                  omitted or set to 1.</p>
      
                  @member ejs.PhraseSuggester
                  @param {Integer} s A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            gramSize: function (s) {
                if (s == null) {
                    return suggest[name].phrase.gram_size;
                }

                suggest[name].phrase.gram_size = s;
                return this;
            },

            /**
                  <p>Forces the use of unigrams.</p>
      
                  @member ejs.PhraseSuggester
                  @param {Boolean} trueFalse True to force unigrams, false otherwise.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            forceUnigrams: function (trueFalse) {
                if (trueFalse == null) {
                    return suggest[name].phrase.force_unigrams;
                }

                suggest[name].phrase.force_unigrams = trueFalse;
                return this;
            },

            /**
                  <p>Sets the token limit.</p>
      
                  @member ejs.PhraseSuggester
                  @param {Integer} l A positive integer value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            tokenLimit: function (l) {
                if (l == null) {
                    return suggest[name].phrase.token_limit;
                }

                suggest[name].phrase.token_limit = l;
                return this;
            },

            /**
                  <p>A smoothing model that takes the weighted mean of the unigrams,
                  bigrams and trigrams based on user supplied weights (lambdas). The
                  sum of tl, bl, and ul must equal 1.</p>
      
                  @member ejs.PhraseSuggester
                  @param {Double} tl A positive double value used for trigram weight.
                  @param {Double} bl A positive double value used for bigram weight.
                  @param {Double} ul A positive double value used for unigram weight.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            linearSmoothing: function (tl, bl, ul) {
                if (arguments.length === 0) {
                    return suggest[name].phrase.smoothing;
                }

                suggest[name].phrase.smoothing = {
                    linear: {
                        trigram_lambda: tl,
                        bigram_lambda: bl,
                        unigram_lambda: ul
                    }
                };

                return this;
            },

            /**
                  <p>A smoothing model that uses an additive smoothing model where a
                  constant (typically 1.0 or smaller) is added to all counts to
                  balance weights, The default alpha is 0.5.</p>
      
                  @member ejs.PhraseSuggester
                  @param {Double} alpha A double value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            laplaceSmoothing: function (alpha) {
                if (alpha == null) {
                    return suggest[name].phrase.smoothing;
                }

                suggest[name].phrase.smoothing = {
                    laplace: {
                        alpha: alpha
                    }
                };

                return this;
            },

            /**
                  <p>A simple backoff model that backs off to lower order n-gram
                  models if the higher order count is 0 and discounts the lower
                  order n-gram model by a constant factor. The default discount is
                  0.4.</p>
      
                  @member ejs.PhraseSuggester
                  @param {Double} discount A double value.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            stupidBackoffSmoothing: function (discount) {
                if (discount == null) {
                    return suggest[name].phrase.smoothing;
                }

                suggest[name].phrase.smoothing = {
                    stupid_backoff: {
                        discount: discount
                    }
                };

                return this;
            },

            /**
                  <p>Enables highlighting of suggestions</p>
      
                  @member ejs.PhraseSuggester
                  @param {String} preTag A tag used at highlight start.
                  @param {String} postTag A tag used at the end of the highlight.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            highlight: function (preTag, postTag) {
                if (arguments.length === 0) {
                    return suggest[name].phrase.highlight;
                }

                suggest[name].phrase.highlight = {
                    pre_tag: preTag,
                    post_tag: postTag
                };

                return this;
            },

            /**
                  Adds a direct generator. If passed a single <code>Generator</code>
                  it is added to the list of existing generators.  If passed an
                  array of Generators, they replace all existing generators.
      
                  @member ejs.PhraseSuggester
                  @param {(Generator|Generator[])} oGenerator A valid Generator or
                    array of Generator objects.
                  @returns {Object} returns <code>this</code> so that calls can be chained.
                  */
            directGenerator: function (oGenerator) {
                var i, len;

                if (suggest[name].phrase.direct_generator == null) {
                    suggest[name].phrase.direct_generator = [];
                }

                if (oGenerator == null) {
                    return suggest[name].phrase.direct_generator;
                }

                if (isGenerator(oGenerator)) {
                    suggest[name].phrase.direct_generator.push(oGenerator.toJSON());
                } else if (isArray(oGenerator)) {
                    suggest[name].phrase.direct_generator = [];
                    for (i = 0, len = oGenerator.length; i < len; i++) {
                        if (!isGenerator(oGenerator[i])) {
                            throw new TypeError('Argument must be an array of Generators');
                        }

                        suggest[name].phrase.direct_generator.push(oGenerator[i].toJSON());
                    }
                } else {
                    throw new TypeError('Argument must be a Generator or array of Generators');
                }

                return this;
            }

        });
    };

    /**
      @class
      <p>TermSuggester suggests terms based on edit distance. The provided suggest 
      text is analyzed before terms are suggested. The suggested terms are 
      provided per analyzed suggest text token.  This leaves the suggest-selection 
      to the API consumer.  For a higher level suggester, please use the 
      <code>PhraseSuggester</code>.</p>
  
      @name ejs.TermSuggester
      @ejs suggest
      @borrows ejs.SuggesterMixin.text as text
      @borrows ejs.SuggesterMixin._type as _type
      @borrows ejs.SuggesterMixin.toJSON as toJSON
      @borrows ejs.DirectSettingsMixin.accuracy as accuracy
      @borrows ejs.DirectSettingsMixin.suggestMode as suggestMode
      @borrows ejs.DirectSettingsMixin.sort as sort
      @borrows ejs.DirectSettingsMixin.stringDistance as stringDistance
      @borrows ejs.DirectSettingsMixin.maxEdits as maxEdits
      @borrows ejs.DirectSettingsMixin.maxInspections as maxInspections
      @borrows ejs.DirectSettingsMixin.maxTermFreq as maxTermFreq
      @borrows ejs.DirectSettingsMixin.prefixLength as prefixLength
      @borrows ejs.DirectSettingsMixin.minWordLen as minWordLen
      @borrows ejs.DirectSettingsMixin.minDocFreq as minDocFreq
      @borrows ejs.SuggestContextMixin.analyzer as analyzer
      @borrows ejs.SuggestContextMixin.field as field
      @borrows ejs.SuggestContextMixin.size as size
      @borrows ejs.SuggestContextMixin.shardSize as shardSize
  
      @since elasticsearch 0.90
      
      @desc
      <p>A suggester that suggests terms based on edit distance.</p>
  
      @param {String} name The name which be used to refer to this suggester.
      */
    ejs.TermSuggester = function (name) {

        var
          _direct,
          _context,
          _common = ejs.SuggesterMixin(name),
          suggest = _common.toJSON();

        suggest[name].term = {};
        _direct = ejs.DirectSettingsMixin(suggest[name].term);
        _context = ejs.SuggestContextMixin(suggest[name].term);

        return extend(_common, _direct, _context);
    };

    // run in noConflict mode
    ejs.noConflict = function () {
        root.ejs = _ejs;
        return this;
    };

}).call(this);

//var request = ejs.Request()
//new ejs.TermsAggregation("sdf").;
var elasticui;
(function (elasticui) {
    (function (util) {
        var EjsCollection = (function () {
            function EjsCollection() {
                this.ejsObjects = [];
                this.jsonObjects = [];
            }
            EjsCollection.prototype.indexOf = function (ejsObject) {
                return this.jsonObjects.indexOf(util.EjsTool.getJsonFromEjsObject(ejsObject));
            };

            EjsCollection.prototype.add = function (ejsObject) {
                var idx = this.indexOf(ejsObject);
                if (idx == -1) {
                    this.ejsObjects.push(ejsObject);
                    this.jsonObjects.push(util.EjsTool.getJsonFromEjsObject(ejsObject));
                }
            };

            EjsCollection.prototype.remove = function (ejsObject) {
                var idx = this.indexOf(ejsObject);
                if (idx > -1) {
                    this.ejsObjects.splice(idx, 1);
                    this.jsonObjects.splice(idx, 1);
                }
            };
            return EjsCollection;
        })();
        util.EjsCollection = EjsCollection;
    })(elasticui.util || (elasticui.util = {}));
    var util = elasticui.util;
})(elasticui || (elasticui = {}));
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var elasticui;
(function (elasticui) {
    (function (util) {
        var FilterCollection = (function (_super) {
            __extends(FilterCollection, _super);
            function FilterCollection() {
                _super.apply(this, arguments);
            }
            FilterCollection.prototype.getAsFilter = function () {
                return util.FilterTool.combineFilters(this.ejsObjects);
            };

            FilterCollection.prototype.getAsORFilter = function () {
                return util.FilterTool.combineFiltersShould(this.ejsObjects);
            };

            FilterCollection.prototype.contains = function (filter) {
                return this.indexOf(filter) > -1;
            };
            return FilterCollection;
        })(util.EjsCollection);
        util.FilterCollection = FilterCollection;
    })(elasticui.util || (elasticui.util = {}));
    var util = elasticui.util;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (util) {
        var FilterTool = (function () {
            function FilterTool() {
            }
            FilterTool.combineFilters = function (filters) {
                if (filters.length === 1) {
                    return filters[0];
                } else if (filters.length > 1) {
                    return ejs.BoolFilter().must(filters);
                }
                return null;
            };

            FilterTool.combineFiltersShould = function (filters) {
                if (filters.length === 1) {
                    return filters[0];
                } else if (filters.length > 1) {
                    return ejs.BoolFilter().should(filters);
                }
                return null;
            };
            return FilterTool;
        })();
        util.FilterTool = FilterTool;
    })(elasticui.util || (elasticui.util = {}));
    var util = elasticui.util;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (_services) {
        _services.services = angular.module('elasticui.services', []);
    })(elasticui.services || (elasticui.services = {}));
    var services = elasticui.services;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (_directives) {
        _directives.directives = angular.module('elasticui.directives', []);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var AggregationDirective = (function () {
            function AggregationDirective() {
                var directive = {};

                directive.restrict = 'EAC';
                directive.scope = true;

                directive.controller = elasticui.controllers.AggregationController;
                directive.link = function (scope, element, attrs, aggCtrl) {
                    scope.$watch(element.attr('eui-aggregation') + " | euiCached", function (val) {
                        return scope.aggregation.agg = val;
                    });

                    var filterSelf = true;
                    var filterSelfAttr = element.attr('eui-filter-self');
                    if (filterSelfAttr) {
                        scope.$watch(filterSelfAttr, function (val) {
                            return scope.aggregation.filterSelf = val;
                        });
                        filterSelf = scope.$eval(filterSelfAttr);
                    }

                    scope.aggregation = {
                        agg: scope.$eval(element.attr('eui-aggregation') + " | euiCached"),
                        filterSelf: filterSelf
                    };

                    aggCtrl.init();
                };
                return directive;
            }
            return AggregationDirective;
        })();
        directives.AggregationDirective = AggregationDirective;
        directives.directives.directive('euiAggregation', elasticui.directives.AggregationDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var FilterDirective = (function () {
            function FilterDirective() {
                var directive = {};
                directive.restrict = 'A';
                directive.scope = true;
                directive.controller = elasticui.controllers.FilterController;
                directive.link = function (scope, element, attrs, filterCtrl) {
                    scope.$watch(element.attr('eui-filter') + " | euiCached", function (val) {
                        return scope.filter.filter = val;
                    });

                    var enabled = false;
                    var enabledAttr = element.attr('eui-enabled');
                    if (enabledAttr) {
                        scope.$watch(enabledAttr, function (val) {
                            return scope.filter.enabled = val;
                        });
                        enabled = scope.$eval(enabledAttr);
                    }

                    scope.filter = {
                        filter: scope.$eval(element.attr('eui-filter') + " | euiCached"),
                        enabled: enabled
                    };

                    filterCtrl.init();
                };
                return directive;
            }
            return FilterDirective;
        })();
        directives.FilterDirective = FilterDirective;
        directives.directives.directive('euiFilter', FilterDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var IndexDirective = (function () {
            function IndexDirective() {
                var directive = {};
                directive.restrict = 'EAC';
                directive.scope = false;

                directive.controller = elasticui.controllers.IndexController;
                directive.link = function (scope, element, attrs, indexCtrl) {
                    scope.$watch(attrs.euiIndex, function (val) {
                        indexCtrl.indexVM.index = val;
                    });
                    indexCtrl.indexVM.index = scope.$eval(attrs.euiIndex);
                };
                return directive;
            }
            return IndexDirective;
        })();
        directives.IndexDirective = IndexDirective;
        directives.directives.directive('euiIndex', IndexDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var InvertedDirective = (function () {
            function InvertedDirective() {
                var directive = {};

                directive.require = 'ngModel';
                directive.link = function (scope, element, attrs, ngModel) {
                    ngModel.$parsers.push(function (val) {
                        return !val;
                    });
                    ngModel.$formatters.push(function (val) {
                        return !val;
                    });
                };
                return directive;
            }
            return InvertedDirective;
        })();
        directives.InvertedDirective = InvertedDirective;
        directives.directives.directive('euiInverted', InvertedDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var OrFilterDirective = (function () {
            function OrFilterDirective() {
                var directive = {};
                directive.restrict = 'EAC';
                directive.scope = true;

                directive.controller = elasticui.controllers.OrFilterController;
                directive.link = function (scope, element, attrs, filterCtrl) {
                };
                return directive;
            }
            return OrFilterDirective;
        })();
        directives.OrFilterDirective = OrFilterDirective;
        directives.directives.directive('euiOrFilter', OrFilterDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var SortDirective = (function () {
            function SortDirective() {
                var directive = {};
                directive.restrict = 'A';
                directive.scope = true;

                directive.controller = elasticui.controllers.SortController;
                directive.link = function (scope, element, attrs, sortCtrl) {
                    scope.$watch(element.attr('eui-sort') + " | euiCached", function (val) {
                        return scope.sorting.sort = val;
                    });

                    var enabled = false;
                    var enabledAttr = element.attr('eui-enabled');
                    if (enabledAttr) {
                        scope.$watch(enabledAttr, function (val) {
                            return scope.sorting.enabled = val;
                        });
                        enabled = scope.$eval(enabledAttr);
                    }

                    scope.sorting = {
                        sort: scope.$eval(element.attr('eui-sort') + " | euiCached"),
                        enabled: enabled
                    };

                    sortCtrl.init();
                };
                return directive;
            }
            return SortDirective;
        })();
        directives.SortDirective = SortDirective;
        directives.directives.directive('euiSort', SortDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var ReturnFieldsDirective = (function () {
            function ReturnFieldsDirective() {
                var directive = {};
                directive.restrict = 'A';
                directive.scope = true;

                directive.controller = elasticui.controllers.ReturnFieldsController;
                directive.link = function (scope, element, attrs, returnFieldsCtrl) {
                    scope.$watch(element.attr('eui-return-fields') + " | euiCached", function (val) {
                        return scope.returnFields.returnField = val;
                    });

                    var enabled = false;
                    var enabledAttr = element.attr('eui-enabled');
                    if (enabledAttr) {
                        scope.$watch(enabledAttr, function (val) {
                            return scope.returnFields.enabled = val;
                        });
                        enabled = scope.$eval(enabledAttr);
                    }

                    scope.returnFields = {
                        returnField: scope.$eval(element.attr('eui-return-fields') + " | euiCached"),
                        enabled: enabled
                    };

                    returnFieldsCtrl.init();
                };
                return directive;
            }
            return ReturnFieldsDirective;
        })();
        directives.ReturnFieldsDirective = ReturnFieldsDirective;
        directives.directives.directive('euiReturnFields', ReturnFieldsDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var VarDirective = (function () {
            function VarDirective($timeout) {
                var directive = {};
                directive.restrict = 'EAC';
                directive.scope = false;
                directive.transclude = false;

                directive.link = {
                    pre: function (scope, element, attrs) {
                        var key = element.attr('eui-key');
                        scope.$watch(element.attr('eui-value'), function (newVal, oldVal) {
                            if (!angular.equals(newVal, oldVal)) {
                                scope[key] = newVal;
                            }
                        }, true);
                        scope[key] = scope.$eval(element.attr('eui-value'));
                    }
                };
                return directive;
            }
            VarDirective.$inject = ['$timeout'];
            return VarDirective;
        })();
        directives.VarDirective = VarDirective;
        directives.directives.directive('euiVar', VarDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (_filters) {
        _filters.filters = angular.module('elasticui.filters', []);
    })(elasticui.filters || (elasticui.filters = {}));
    var filters = elasticui.filters;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (filters) {
        var CachedFilter = (function () {
            function CachedFilter() {
                var values = {};
                return function (input) {
                    if (!input) {
                        return input;
                    }
                    var json = angular.toJson(input.toJSON());
                    if (!values[json]) {
                        values[json] = input;
                    }
                    return values[json];
                };
            }
            return CachedFilter;
        })();
        filters.CachedFilter = CachedFilter;

        filters.filters.filter('euiCached', CachedFilter);
    })(elasticui.filters || (elasticui.filters = {}));
    var filters = elasticui.filters;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (filters) {
        var MapFilter = (function () {
            function MapFilter() {
                return function (input, property) {
                    var ret = [];
                    if (!input || !input.length) {
                        return input;
                    }
                    var arr = MapFilter.parseString(property);
                    return input.map(function (el) {
                        return [el.key, MapFilter.getValue(el, arr)];
                    });
                };
            }
            MapFilter.parseString = function (input) {
                return input.split(".");
            };

            MapFilter.getValue = function (element, propertyArray) {
                var value = element;

                angular.forEach(propertyArray, function (property) {
                    if (!value) {
                        return value;
                    }
                    value = value[property];
                });

                return value;
            };
            return MapFilter;
        })();
        filters.MapFilter = MapFilter;

        filters.filters.filter('euiMap', MapFilter);
    })(elasticui.filters || (elasticui.filters = {}));
    var filters = elasticui.filters;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (filters) {
        var PageRangeFilter = (function () {
            function PageRangeFilter() {
                return function (input, total, current, neighbours) {
                    if (typeof neighbours === "undefined") { neighbours = 5; }
                    for (var i = 1; i <= total; i++) {
                        if (i <= current + neighbours && i >= current - neighbours || (i < current && current - neighbours < 4) || (i > current + neighbours && total - (current + neighbours) < 4)) {
                            input.push(i);
                        } else if (i == 1) {
                            input.push(1, -1);
                        } else if (i == total) {
                            input.push(-2, total);
                        }
                    }
                    return input;
                };
            }
            return PageRangeFilter;
        })();
        filters.PageRangeFilter = PageRangeFilter;

        filters.filters.filter('euiPageRange', PageRangeFilter);
    })(elasticui.filters || (elasticui.filters = {}));
    var filters = elasticui.filters;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (filters) {
        var RangeFilter = (function () {
            function RangeFilter() {
                return function (input, total) {
                    total = parseInt(total);
                    for (var i = 0; i < total; i++) {
                        input.push(i);
                    }
                    return input;
                };
            }
            return RangeFilter;
        })();
        filters.RangeFilter = RangeFilter;

        filters.filters.filter('euiRange', RangeFilter);
    })(elasticui.filters || (elasticui.filters = {}));
    var filters = elasticui.filters;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (filters) {
        var RoundFilter = (function () {
            function RoundFilter() {
                return function (input) {
                    if (!input) {
                        return input;
                    }
                    return Math.round(input);
                };
            }
            return RoundFilter;
        })();
        filters.RoundFilter = RoundFilter;

        filters.filters.filter('euiRound', RoundFilter);
    })(elasticui.filters || (elasticui.filters = {}));
    var filters = elasticui.filters;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (filters) {
        var TimestampFilter = (function () {
            function TimestampFilter() {
                return function (input) {
                    return new Date(input).getTime();
                };
            }
            return TimestampFilter;
        })();
        filters.TimestampFilter = TimestampFilter;

        filters.filters.filter('euiTimestamp', TimestampFilter);
    })(elasticui.filters || (elasticui.filters = {}));
    var filters = elasticui.filters;
})(elasticui || (elasticui = {}));
angular.module('elasticui.controllers', []).controller(elasticui.controllers);
var elasticui;
(function (elasticui) {
    (function (controllers) {
        var AggregationController = (function () {
            function AggregationController($scope) {
                this.scope = $scope;
            }
            AggregationController.prototype.init = function () {
                var _this = this;
                this.scope.$parent.$watch('indexVM.results', function () {
                    return _this.updateResults();
                });
                this.scope.$watch('aggregation.agg', function (newVal, oldVal) {
                    if (!elasticui.util.EjsTool.equals(oldVal, newVal)) {
                        if (_this.previousProvider) {
                            _this.scope.indexVM.aggregationProviders.remove(_this.previousProvider);
                        }
                        _this.updateAgg();
                    }
                });

                this.scope.$watch('aggregation.filterSelf', function (newVal, oldVal) {
                    if (newVal !== oldVal) {
                        if (_this.previousProvider) {
                            _this.scope.indexVM.aggregationProviders.remove(_this.previousProvider);
                        }
                        _this.updateAgg();
                    }
                });

                this.scope.$on('$destroy', function () {
                    if (_this.previousProvider) {
                        _this.scope.indexVM.aggregationProviders.remove(_this.previousProvider);
                    }
                });

                this.updateAgg();
            };

            AggregationController.prototype.updateResults = function () {
                var res = this.scope.indexVM.results;
                if (this.scope.aggregation.agg && res && res.aggregations) {
                    var name = AggregationController.getAggName(this.scope.aggregation.agg);

                    var aggKey = Object.keys(res.aggregations).filter(function (key) {
                        return key == name || key == "filtered_" + name;
                    })[0];
                    var agg = res.aggregations[aggKey];
                    if (aggKey == "filtered_" + name) {
                        agg = agg[name];
                    }
                    this.scope.aggResult = agg;
                }
            };

            AggregationController.prototype.updateAgg = function () {
                var _this = this;
                var provider = null;

                if (this.scope.aggregation.agg) {
                    provider = function (filters) {
                        return _this.getAggregation(filters);
                    };
                }

                if (provider) {
                    this.scope.indexVM.aggregationProviders.add(provider);
                }

                this.previousProvider = provider;
            };

            AggregationController.getAggName = function (ejsAggregation) {
                return Object.keys(ejsAggregation.toJSON())[0];
            };

            AggregationController.prototype.getAggregationExplicit = function (ejsAggregation, filterSelf, filters) {
                var _this = this;
                if (!ejsAggregation) {
                    return null;
                }

                var facetFilters = filters;
                if (!filterSelf) {
                    facetFilters = facetFilters.filter(function (val) {
                        return val != _this.scope.combinedFilter && (typeof val.field === "undefined" || val.field() != ejsAggregation.field());
                    });
                }

                var combinedFilters = elasticui.util.FilterTool.combineFilters(facetFilters);
                if (combinedFilters != null) {
                    ejsAggregation = new ejs.FilterAggregation("filtered_" + AggregationController.getAggName(ejsAggregation)).filter(combinedFilters).agg(ejsAggregation);
                }
                return ejsAggregation;
            };

            AggregationController.prototype.getAggregation = function (filters) {
                return this.getAggregationExplicit(this.scope.aggregation.agg, this.scope.aggregation.filterSelf, filters);
            };
            AggregationController.$inject = ['$scope'];
            return AggregationController;
        })();
        controllers.AggregationController = AggregationController;
    })(elasticui.controllers || (elasticui.controllers = {}));
    var controllers = elasticui.controllers;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (controllers) {
        var FilterController = (function () {
            function FilterController($scope) {
                this.scope = $scope;
            }
            FilterController.prototype.init = function () {
                var _this = this;
                if (this.scope.filter.filter) {
                    var isEnabled = this.scope.filters.contains(this.scope.filter.filter);
                    if (!isEnabled && this.scope.filter.enabled) {
                        this.scope.filters.add(this.scope.filter.filter);
                        isEnabled = true;
                    }
                }

                this.scope.filter.enabled = isEnabled;
                this.scope.$watch('filter.enabled', function (newVal, oldVal) {
                    if (newVal !== oldVal) {
                        _this.updateFilter();
                    }
                });

                this.scope.$watch('filter.filter', function (newVal, oldVal) {
                    if (!elasticui.util.EjsTool.equals(oldVal, newVal)) {
                        if (oldVal) {
                            _this.scope.filters.remove(oldVal);
                        }
                        _this.updateFilter();
                    }
                });
            };

            FilterController.prototype.updateFilter = function () {
                if (!this.scope.filter.filter) {
                    return;
                }

                if (this.scope.filter.enabled) {
                    this.scope.filters.add(this.scope.filter.filter);
                } else {
                    this.scope.filters.remove(this.scope.filter.filter);
                }
            };
            FilterController.$inject = ['$scope'];
            return FilterController;
        })();
        controllers.FilterController = FilterController;
    })(elasticui.controllers || (elasticui.controllers = {}));
    var controllers = elasticui.controllers;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (controllers) {
        var IndexController = (function () {
            function IndexController($scope, $timeout, $window, es, $rootScope) {
                var _this = this;
                this.filters = new elasticui.util.FilterCollection();
                this.indexVM = {
                    host: null,
                    query: null,
                    sort: null,
                    aggregationProviders: new elasticui.util.SimpleSet(),
                    filters: this.filters,
                    highlight: null,
                    returnFields: null,
                    loaded: false,
                    page: 1,
                    index: null,
                    loading: false,
                    pageCount: 0,
                    pageSize: null,
                    results: null,
                    refresh: function () {
                        return _this.refreshIfDocCountChanged();
                    },
                    error: null
                };
                this.searchPromise = null;
                this.refreshPromise = null;
                this.es = es;
                this.$rootScope = $rootScope;

                $scope.indexVM = this.indexVM;
                $scope.ejs = $window.ejs;
                $scope.filters = this.filters;
                $scope.$watchCollection('indexVM.filters.ejsObjects', function () {
                    _this.indexVM.page = 1;
                    _this.search();
                });
                $scope.$watchCollection('indexVM.aggregationProviders.objects', function () {
                    return _this.search();
                });

                $scope.$watch('indexVM.host', function () {
                    if (_this.indexVM.host != null && es.setHost(_this.indexVM.host)) {
                        _this.search();
                    }
                });
                $scope.$watch('indexVM.sort', function () {
                    _this.indexVM.page = 1;
                    _this.search();
                });
                $scope.$watch('indexVM.page', function () {
                    return _this.search();
                });
                $scope.$watch('indexVM.pageSize', function () {
                    return _this.search();
                });
                $scope.$watch('indexVM.index', function () {
                    return _this.search();
                });
                $scope.$watch('indexVM.query', function () {
                    return _this.search();
                });
                $scope.$watch('indexVM.highlight', function () {
                    return _this.search();
                });
                $scope.$watch('indexVM.returnFields', function () {
                    return _this.search();
                });

                $timeout(function () {
                    return _this.loaded();
                }, 200);
            }
            IndexController.prototype.loaded = function () {
                if (!this.indexVM.loaded) {
                    this.indexVM.loaded = true;
                    //this.search();
                }
            };

            IndexController.prototype.getSearchPromise = function () {
                var request = ejs.Request();

                for (var i = 0; i < this.indexVM.aggregationProviders.objects.length; i++) {
                    var provider = this.indexVM.aggregationProviders.objects[i];
                    var agg = provider(this.filters.ejsObjects);
                    request.agg(agg);
                }

                var combinedFilter = this.filters.getAsFilter();
                if (combinedFilter != null) {
                    request.filter(combinedFilter);
                }

                if (this.indexVM.query != null) {
                    request.query(this.indexVM.query);
                } else {
                    request.query(ejs.MatchAllQuery());
                }

                if (this.indexVM.sort != null) {
                    request.sort(this.indexVM.sort);
                }

                if (this.indexVM.highlight != null) {
                    request.highlight(this.indexVM.highlight);
                }

                if (this.indexVM.pageSize != null) {
                    request.size(this.indexVM.pageSize);
                }

                if (this.indexVM.returnFields != null) {
                    request.source(this.indexVM.returnFields.source().includes);
                }

                var res = this.es.client.search({
                    index: this.indexVM.index,
                    from: this.indexVM.pageSize * (this.indexVM.page - 1),
                    body: request
                });

                return res;
            };

            IndexController.prototype.onError = function (err) {
                this.$rootScope.$broadcast('eui-search-error', err);
                this.indexVM.error = err;
            };

            IndexController.prototype.search = function () {
                var _this = this;
                if (!this.indexVM.loaded || !this.indexVM.index) {
                    return;
                }
                if (this.refreshPromise != null) {
                    this.refreshPromise.abort();
                    this.refreshPromise = null;
                }
                this.indexVM.loading = true;
                this.searchPromise = this.getSearchPromise();
                this.searchPromise.then(function (body) {
                    _this.searchPromise = null;
                    _this.indexVM.error = null;
                    _this.onResult(body);
                }, function (err) {
                    if (_this.searchPromise) {
                        _this.searchPromise = null;
                        _this.onError(err);
                    }
                });
            };

            IndexController.prototype.refreshIfDocCountChanged = function () {
                var _this = this;
                if (!this.indexVM.loaded || !this.indexVM.index || this.searchPromise != null) {
                    return;
                }
                this.indexVM.loading = true;
                this.refreshPromise = this.getSearchPromise();
                this.refreshPromise.then(function (body) {
                    _this.refreshPromise = null;
                    _this.indexVM.error = null;
                    _this.onResult(body, true);
                }, function (err) {
                    if (_this.refreshPromise) {
                        _this.refreshPromise = null;
                        _this.onError(err);
                    }
                });
            };

            IndexController.prototype.onResult = function (body, updateOnlyIfCountChanged) {
                if (typeof updateOnlyIfCountChanged === "undefined") { updateOnlyIfCountChanged = false; }
                if (!updateOnlyIfCountChanged || this.indexVM.results == null || this.indexVM.results.hits.total != body.hits.total) {
                    this.indexVM.results = body;
                    this.indexVM.pageCount = Math.ceil(this.indexVM.results.hits.total / this.indexVM.pageSize);
                }
                this.indexVM.loading = false;
            };
            IndexController.$inject = ['$scope', '$timeout', '$window', 'es', '$rootScope'];
            return IndexController;
        })();
        controllers.IndexController = IndexController;
    })(elasticui.controllers || (elasticui.controllers = {}));
    var controllers = elasticui.controllers;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (controllers) {
        var OrFilterController = (function () {
            function OrFilterController($scope) {
                var _this = this;
                this.filters = new elasticui.util.FilterCollection();
                $scope.filters = this.filters;
                $scope.$watchCollection('filters.ejsObjects', function () {
                    return _this.updateCombinedFilter();
                });

                this.scope = $scope;
            }
            OrFilterController.prototype.updateCombinedFilter = function () {
                if (this.scope.combinedFilter) {
                    this.scope.$parent.filters.remove(this.scope.combinedFilter);
                }

                this.scope.combinedFilter = this.filters.getAsORFilter();
                if (this.scope.combinedFilter) {
                    this.scope.$parent.filters.add(this.scope.combinedFilter);
                }
            };
            OrFilterController.$inject = ['$scope'];
            return OrFilterController;
        })();
        controllers.OrFilterController = OrFilterController;
    })(elasticui.controllers || (elasticui.controllers = {}));
    var controllers = elasticui.controllers;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (controllers) {
        var SortController = (function () {
            function SortController($scope) {
                this.scope = $scope;
            }
            SortController.prototype.init = function () {
                var _this = this;
                this.scope.$watch('indexVM.sort', function () {
                    return _this.updateEnabled();
                });
                this.scope.$watch('sorting.sort', function () {
                    return _this.updateSort();
                });
                this.scope.$watch('sorting.enabled', function (newVal, oldVal) {
                    if (newVal !== oldVal) {
                        _this.updateSort();
                    }
                });

                this.updateSort();
            };

            SortController.prototype.updateSort = function () {
                if (this.scope.sorting.enabled) {
                    this.scope.indexVM.sort = this.scope.sorting.sort;
                } else {
                    if (this.isEnabledOnIndexScope()) {
                        this.scope.indexVM.sort = null;
                    }
                }
            };

            SortController.prototype.updateEnabled = function () {
                this.scope.sorting.enabled = this.isEnabledOnIndexScope();
            };

            SortController.prototype.isEnabledOnIndexScope = function () {
                return this.scope.indexVM.sort != null && angular.equals(this.scope.indexVM.sort.toJSON(), this.scope.sorting.sort.toJSON());
            };
            SortController.$inject = ['$scope'];
            return SortController;
        })();
        controllers.SortController = SortController;
    })(elasticui.controllers || (elasticui.controllers = {}));
    var controllers = elasticui.controllers;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (controllers) {
        var ReturnFieldsController = (function () {
            function ReturnFieldsController($scope) {
                this.scope = $scope;
            }
            ReturnFieldsController.prototype.init = function () {
                var _this = this;
                this.scope.$watch('indexVM.returnFields', function () {
                    return _this.updateEnabled();
                });
                this.scope.$watch('returnFields.returnField', function () {
                    return _this.updateReturnFields();
                });
                this.scope.$watch('returnFields.enabled', function (newVal, oldVal) {
                    if (newVal !== oldVal) {
                        _this.updateReturnFields();
                    }
                });

                this.updateReturnFields();
            };

            ReturnFieldsController.prototype.updateReturnFields = function () {
                if (this.scope.returnFields.enabled) {
                    this.scope.indexVM.returnFields = this.scope.returnFields.returnField;
                } else {
                    if (this.isEnabledOnIndexScope()) {
                        this.scope.indexVM.returnFields = null;
                    }
                }
            };

            ReturnFieldsController.prototype.updateEnabled = function () {
                this.scope.returnFields.enabled = this.isEnabledOnIndexScope();
            };

            ReturnFieldsController.prototype.isEnabledOnIndexScope = function () {
                return this.scope.indexVM.returnFields != null && angular.equals(this.scope.indexVM.returnFields.toJSON(), this.scope.returnFields.returnField.toJSON());
            };
            ReturnFieldsController.$inject = ['$scope'];
            return ReturnFieldsController;
        })();
        controllers.ReturnFieldsController = ReturnFieldsController;
    })(elasticui.controllers || (elasticui.controllers = {}));
    var controllers = elasticui.controllers;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (services) {
        var ElasticService = (function () {
            function ElasticService(esFactory, euiHost) {
                this.esFactory = esFactory;
                this.setHost(euiHost);
            }
            ElasticService.prototype.setHost = function (host) {
                if (host === this.host) {
                    return false;
                }

                this.host = host;
                this.client = this.esFactory({
                    host: host,
                    calcDeadTimeout: "flat"
                });

                return true;
            };
            ElasticService.$inject = ['esFactory', 'euiHost'];
            return ElasticService;
        })();
        services.ElasticService = ElasticService;
        services.services.service('es', ElasticService);
    })(elasticui.services || (elasticui.services = {}));
    var services = elasticui.services;
})(elasticui || (elasticui = {}));
angular.module('elasticui', ['elasticsearch', 'elasticui.filters', 'elasticui.controllers', 'elasticui.services', 'elasticui.directives', 'elasticui.widgets.directives']);
var elasticui;
(function (elasticui) {
    (function (widgets) {
        (function (_directives) {
            _directives.directives = angular.module('elasticui.widgets.directives', []);
            _directives.default_agg_count = 0;
        })(widgets.directives || (widgets.directives = {}));
        var directives = widgets.directives;
    })(elasticui.widgets || (elasticui.widgets = {}));
    var widgets = elasticui.widgets;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (widgets) {
        (function (directives) {
            var ChecklistDirective = (function () {
                function ChecklistDirective($parse) {
                    var directive = {};
                    directive.restrict = 'E';
                    directive.scope = true;

                    directive.link = {
                        'pre': function (scope, element, attrs) {
                            elasticui.util.AngularTool.setupBinding($parse, scope, attrs, ["field", "size"]);
                            scope.agg_name = scope.field.replace(/[^a-z_0-9]/gmi, "_") + "_" + (directives.default_agg_count++);
                        }
                    };

                    directive.template = '\
            <ul class="nav nav-list" eui-aggregation="ejs.TermsAggregation(agg_name).field(field).size(size)">\
                <li ng-repeat="bucket in aggResult.buckets">\
                    <label class="checkbox" eui-filter="ejs.TermsFilter(field, bucket.key)">\
                        <input type="checkbox" ng-model="filter.enabled">\
                        {{bucket.key}} ({{bucket.doc_count}})\
                    </label>\
                </li>\
            </ul>';

                    return directive;
                }
                ChecklistDirective.$inject = ['$parse'];
                return ChecklistDirective;
            })();
            directives.ChecklistDirective = ChecklistDirective;
            directives.directives.directive('euiChecklist', ChecklistDirective);
        })(widgets.directives || (widgets.directives = {}));
        var directives = widgets.directives;
    })(elasticui.widgets || (elasticui.widgets = {}));
    var widgets = elasticui.widgets;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (widgets) {
        (function (directives) {
            var SimplePagingDirective = (function () {
                function SimplePagingDirective() {
                    var directive = {};
                    directive.restrict = 'E';
                    directive.scope = true;

                    directive.template = '\
            <ul class="pager">\
                <li ng-class="{disabled:indexVM.page <= 1}"><a href="" ng-click="indexVM.page=indexVM.page - 1">Previous</a></li>\
                <li ng-class="{disabled:indexVM.pageCount <= indexVM.page}"><a href="" ng-click="indexVM.page=indexVM.page + 1">Next</a></li>\
            </ul>';

                    return directive;
                }
                return SimplePagingDirective;
            })();
            directives.SimplePagingDirective = SimplePagingDirective;
            directives.directives.directive('euiSimplePaging', SimplePagingDirective);
        })(widgets.directives || (widgets.directives = {}));
        var directives = widgets.directives;
    })(elasticui.widgets || (elasticui.widgets = {}));
    var widgets = elasticui.widgets;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (widgets) {
        (function (directives) {
            var SingleselectDirective = (function () {
                function SingleselectDirective($parse) {
                    var directive = {};
                    directive.restrict = 'E';
                    directive.scope = true;

                    directive.link = {
                        'pre': function (scope, element, attrs) {
                            elasticui.util.AngularTool.setupBinding($parse, scope, attrs, ["field", "size"]);
                            scope.agg_name = scope.field.replace(/[^a-z_0-9]/gmi, "_") + "_" + (directives.default_agg_count++);
                        }
                    };

                    directive.template = '\
            <ul class="nav nav-list" eui-aggregation="ejs.TermsAggregation(agg_name).field(field).size(size)">\
                <li ng-repeat="bucket in aggResult.buckets">\
                    <label eui-filter="ejs.TermsFilter(field, bucket.key)">\
                        <span ng-if="!filter.enabled"><a href="" ng-click="filter.enabled=true">{{bucket.key}} <span class="muted">({{bucket.doc_count}})</span></a></span>\
                        <span ng-if="filter.enabled">{{bucket.key}} <a href="" ng-click="filter.enabled=false" class="facet-remove">x</a></span>\
                    </label>\
                </li>\
            </ul>';

                    return directive;
                }
                SingleselectDirective.$inject = ['$parse'];
                return SingleselectDirective;
            })();
            directives.SingleselectDirective = SingleselectDirective;
            directives.directives.directive('euiSingleselect', SingleselectDirective);
        })(widgets.directives || (widgets.directives = {}));
        var directives = widgets.directives;
    })(elasticui.widgets || (elasticui.widgets = {}));
    var widgets = elasticui.widgets;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (controllers) {
        var HighlightController = (function () {
            function HighlightController($scope) {
                this.scope = $scope;
            }
            HighlightController.prototype.init = function () {
                var _this = this;
                this.scope.$watch('indexVM.highlight', function () {
                    return _this.updateEnabled();
                });
                this.scope.$watch('highlighting.highlight', function () {
                    return _this.updateHighlight();
                });
                this.scope.$watch('highlighting.enabled', function (newVal, oldVal) {
                    if (newVal !== oldVal) {
                        _this.updateHighlight();
                    }
                });
                this.updateHighlight();
            };

            HighlightController.prototype.updateHighlight = function () {
                if (this.scope.highlighting.enabled) {
                    this.scope.indexVM.highlight = this.scope.highlighting.highlight;
                } else {
                    if (this.isEnabledOnIndexScope()) {
                        this.scope.indexVM.highlight = null;
                    }
                }
            };

            HighlightController.prototype.updateEnabled = function () {
                this.scope.highlighting.enabled = this.isEnabledOnIndexScope();
            };

            HighlightController.prototype.isEnabledOnIndexScope = function () {
                return this.scope.indexVM.highlight != null && angular.equals(this.scope.indexVM.highlight.toJSON(), this.scope.highlighting.highlight.toJSON());
            };
            HighlightController.$inject = ['$scope'];
            return HighlightController;
        })();
        controllers.HighlightController = HighlightController;
    })(elasticui.controllers || (elasticui.controllers = {}));
    var controllers = elasticui.controllers;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (controllers) {
        var HostController = (function () {
            function HostController($scope) {
                this.scope = $scope;
            }
            HostController.prototype.init = function () {
                var _this = this;
                this.scope.$watch('indexVM.host', function () {
                    return _this.readHost();
                });
                this.scope.$watch('host', function () {
                    return _this.updateHost();
                });

                this.updateHost();
            };

            HostController.prototype.updateHost = function () {
                if (this.scope.host !== null) {
                    this.scope.indexVM.host = this.scope.host;
                }
            };

            HostController.prototype.readHost = function () {
                this.scope.host = this.scope.indexVM.host;
            };
            HostController.$inject = ['$scope'];
            return HostController;
        })();
        controllers.HostController = HostController;
    })(elasticui.controllers || (elasticui.controllers = {}));
    var controllers = elasticui.controllers;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (controllers) {
        var QueryController = (function () {
            function QueryController($scope) {
                this.scope = $scope;
            }
            QueryController.prototype.init = function () {
                var _this = this;
                this.scope.$watch('query.enabled', function (newVal, oldVal) {
                    if (newVal !== oldVal) {
                        _this.updateQuery();
                    }
                });

                this.scope.$watch('query.query', function (newVal, oldVal) {
                    if (!elasticui.util.EjsTool.equals(oldVal, newVal)) {
                        _this.updateQuery();
                    }
                });
                this.updateQuery();
            };

            QueryController.prototype.updateQuery = function () {
                if (!this.scope.query.query) {
                    return;
                }
                if (!this.scope.query.enabled) {
                    this.scope.indexVM.query = null;
                } else {
                    this.scope.indexVM.query = this.scope.query.query;
                }
            };
            QueryController.$inject = ['$scope'];
            return QueryController;
        })();
        controllers.QueryController = QueryController;
    })(elasticui.controllers || (elasticui.controllers = {}));
    var controllers = elasticui.controllers;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (controllers) {
        var SizeController = (function () {
            function SizeController($scope) {
                this.scope = $scope;
            }
            SizeController.prototype.init = function () {
                var _this = this;
                this.scope.$watch('pageSize.size', function () {
                    return _this.updateSize();
                });
                this.updateSize();
            };

            SizeController.prototype.updateSize = function () {
                this.scope.indexVM.pageSize = this.scope.pageSize.size;
            };
            SizeController.$inject = ['$scope'];
            return SizeController;
        })();
        controllers.SizeController = SizeController;
    })(elasticui.controllers || (elasticui.controllers = {}));
    var controllers = elasticui.controllers;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var HighlightDirective = (function () {
            function HighlightDirective() {
                var directive = {};
                directive.restrict = 'A';
                directive.scope = true;

                directive.controller = elasticui.controllers.HighlightController;
                directive.link = function (scope, element, attrs, highlightCtrl) {
                    scope.$watch(element.attr('eui-highlight') + " | euiCached", function (val) {
                        return scope.highlighting.highlight = val;
                    });

                    var enabled = false;
                    var enabledAttr = element.attr('eui-enabled');
                    if (enabledAttr) {
                        scope.$watch(enabledAttr, function (val) {
                            return scope.highlighting.enabled = val;
                        });
                        enabled = scope.$eval(enabledAttr);
                    }

                    scope.highlighting = {
                        highlight: scope.$eval(element.attr('eui-highlight') + " | euiCached"),
                        enabled: enabled
                    };

                    highlightCtrl.init();
                };
                return directive;
            }
            return HighlightDirective;
        })();
        directives.HighlightDirective = HighlightDirective;
        directives.directives.directive('euiHighlight', HighlightDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var HostDirective = (function () {
            function HostDirective() {
                var directive = {};
                directive.restrict = 'A';
                directive.scope = true;

                directive.controller = elasticui.controllers.HostController;
                directive.link = function (scope, element, attrs, hostCtrl) {
                    scope.$watch(element.attr('eui-host'), function (val) {
                        return scope.host = val;
                    });

                    scope.host = scope.$eval(element.attr('eui-host'));

                    hostCtrl.init();
                };
                return directive;
            }
            return HostDirective;
        })();
        directives.HostDirective = HostDirective;
        directives.directives.directive('euiHost', HostDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var QueryDirective = (function () {
            function QueryDirective() {
                var directive = {};
                directive.restrict = 'A';
                directive.scope = true;
                directive.controller = elasticui.controllers.QueryController;
                directive.link = function (scope, element, attrs, queryCtrl) {
                    scope.$watch(element.attr('eui-query') + " | euiCached", function (val) {
                        return scope.query.query = val;
                    });

                    var enabled = false;
                    var enabledAttr = element.attr('eui-enabled');
                    if (enabledAttr) {
                        scope.$watch(enabledAttr, function (val) {
                            return scope.query.enabled = val;
                        });
                        enabled = scope.$eval(enabledAttr);
                    }

                    scope.query = {
                        query: scope.$eval(element.attr('eui-query') + " | euiCached"),
                        enabled: enabled
                    };

                    queryCtrl.init();
                };
                return directive;
            }
            return QueryDirective;
        })();
        directives.QueryDirective = QueryDirective;
        directives.directives.directive('euiQuery', QueryDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (directives) {
        var SizeDirective = (function () {
            function SizeDirective() {
                var directive = {};
                directive.restrict = 'A';
                directive.scope = true;

                directive.controller = elasticui.controllers.SizeController;
                directive.link = function (scope, element, attrs, sizeCtl) {
                    scope.$watch(element.attr('eui-size'), function (val) {
                        return scope.pageSize.size = val;
                    });

                    scope.pageSize = {
                        size: scope.$eval(element.attr('eui-size'))
                    };

                    sizeCtl.init();
                };
                return directive;
            }
            return SizeDirective;
        })();
        directives.SizeDirective = SizeDirective;
        directives.directives.directive('euiSize', SizeDirective);
    })(elasticui.directives || (elasticui.directives = {}));
    var directives = elasticui.directives;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (util) {
        var AngularTool = (function () {
            function AngularTool() {
            }
            AngularTool.setupBinding = function ($parse, scope, attrs, attrsToBind) {
                angular.forEach(attrsToBind, function (attrName, key) {
                    scope.$watch(attrs[attrName], function (val) {
                        if (scope[attrName] != val) {
                            scope[attrName] = val;
                        }
                    });
                    scope[attrName] = $parse(attrs[attrName])(scope);
                });
            };
            return AngularTool;
        })();
        util.AngularTool = AngularTool;
    })(elasticui.util || (elasticui.util = {}));
    var util = elasticui.util;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (util) {
        var EjsTool = (function () {
            function EjsTool() {
            }
            EjsTool.getJsonFromEjsObject = function (object) {
                return angular.toJson(object.toJSON());
            };

            EjsTool.equals = function (objectA, objectB) {
                return !objectA && !objectB || (objectA && objectB && this.getJsonFromEjsObject(objectA) == this.getJsonFromEjsObject(objectB));
            };
            return EjsTool;
        })();
        util.EjsTool = EjsTool;
    })(elasticui.util || (elasticui.util = {}));
    var util = elasticui.util;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (util) {
        var SimpleSet = (function () {
            function SimpleSet() {
                this.objects = [];
            }
            SimpleSet.prototype.indexOf = function (object) {
                return this.objects.indexOf(object);
            };

            SimpleSet.prototype.add = function (object) {
                var idx = this.indexOf(object);
                if (idx == -1) {
                    this.objects.push(object);
                }
            };

            SimpleSet.prototype.remove = function (object) {
                var idx = this.indexOf(object);
                if (idx > -1) {
                    this.objects.splice(idx, 1);
                }
            };
            return SimpleSet;
        })();
        util.SimpleSet = SimpleSet;
    })(elasticui.util || (elasticui.util = {}));
    var util = elasticui.util;
})(elasticui || (elasticui = {}));
var elasticui;
(function (elasticui) {
    (function (widgets) {
        (function (directives) {
            var SearchboxDirective = (function () {
                function SearchboxDirective($parse) {
                    var directive = {};
                    directive.restrict = 'E';
                    directive.scope = true;

                    directive.link = {
                        'pre': function (scope, element, attrs) {
                            elasticui.util.AngularTool.setupBinding($parse, scope, attrs, ["field"]);
                        }
                    };

                    directive.template = '\
            <input type="text" eui-query="ejs.MatchQuery(field, querystring)" ng-model="querystring" eui-enabled="querystring.length" />\
            ';

                    return directive;
                }
                SearchboxDirective.$inject = ['$parse'];
                return SearchboxDirective;
            })();
            directives.SearchboxDirective = SearchboxDirective;
            directives.directives.directive('euiSearchbox', SearchboxDirective);
        })(widgets.directives || (widgets.directives = {}));
        var directives = widgets.directives;
    })(elasticui.widgets || (elasticui.widgets = {}));
    var widgets = elasticui.widgets;
})(elasticui || (elasticui = {}));;
var app = angular.module('app', ['ngRoute', 'ui.bootstrap', 'ngAnimate', 'ngSanitize', 'formatTitleFilter', 'elasticui', 'elasticsearch', 'ngMessages','angular-ladda'])
    .config(['$sceDelegateProvider', function ($sceDelegateProvider) {
	    $sceDelegateProvider.resourceUrlWhitelist([
	      // Allow same origin resource loads.
	      'self',
	      // Allow loading from our assets domain.  Notice the difference between * and **.
	      'https://*.cloudfront.net/**'
	    ]);
}]);

//copy in elastic_search.js
app.factory('Utils', ['$q', function ($q) {
	return {
		isImage: function isImage(src) {
			var deferred = $q.defer();

			var image = new Image();
			image.onerror = function () {
				deferred.resolve(false);
			};
			image.onload = function () {
				deferred.resolve(true);
			};
			image.src = src;

			return deferred.promise;
		}
	}
}]);

app.service('alertService', ['$timeout', function ($timeout) {
	this.alert = {}; //single alert
	this.timer = {};

	//Defaults
	this.levels = {
		success: 'success',
		warning: 'warning',
		error: 'danger',
		info: 'info'
	}

	this.messages = {
		postError: 'An error occured, please try again later.',
		loadError: 'A problem occured while loading this page. Please try again or call Client Services at 866-927-9622.'
	}

	this.timeoutDefault = 5000;


	//Methods
	this.showAlert = function (level, message, hiddenCopy, closeTime) {
		this.close = function (el) {
			el.level = null;
		}

		//single alert
		this.alert.level = level;
		this.alert.message = message;
		this.alert.hiddenCopy = hiddenCopy;
		this.alert.closeTime = closeTime;
		this.alert.closeFn = this.close;
		
		$timeout.cancel(this.timer);

		//single alert
		if (closeTime) {
			this.timer = $timeout(function (al) {
				al.level = null;
			}, closeTime, true, this.alert);
		}
	}
}]);

//Compared Donors Service
app.service('comparedDonorsService', ['$http', 'CacheService', function ($http, CacheService) {
	this.cacheKey = "comparedDonorsKey";
	//this.fullCacheKey = "comparedDonorsFullKey";
	this.maxCompared = 4; //used in CompareDonorsDrawer

	// GET DONORS
	this.getData = function () {
		var data = CacheService.get(this.cacheKey);
		if (data) {
			return data;
		}
		else {
			data = $http.get("/accountajax/getcompareddonors/");
			CacheService.put(this.cacheKey, data);

			return data;
		}
	};


	// ADD, REMOVE, CLEAR ALL
	//this.update = function (donorObj) {
	this.update = function (donorModel) {
		donorObj = donorModel.DonorAccount;
		donorObj.Donor_No = donorObj.Donor_No || donorObj.donor_No;
		donorObj.Photo_Urls = donorObj.Photo_Urls || donorObj.photo_Urls;
		donorObj.UCPTitle = donorObj.UCPTitle || donorObj.uCPTitle;
		donorObj.DonorAccount = {};
		donorObj.NewDonor = donorObj.NewDonor || donorObj.newDonor;
		donorObj.NewRelease = donorObj.NewRelease || donorObj.newRelease;

		// default photo
		if (donorObj.Photo_Urls != null && donorObj.Photo_Urls.length == 0) {
			donorObj.Photo_Urls.push("/_resources/images/donor-silhouette.png");
		}

		//populating some model values
		donorModel.DonorNo = donorObj.Donor_No;
		donorModel.Photos = donorObj.Photo_Urls;


		this.getData().success(function (data) {
			if (data.status == "success") {
				var donors = data.comparedDonors;
                var index = -1;
                for (var i = 0; i < donors.length; i++) {
                    if (donors[i].DonorAccount.Donor_No == donorObj.Donor_No) {
                        index = i;
                    }
                }

					// Remove if in list
                if (index  > -1) {
                    donors.splice(index, 1);

					}
					// Add Donor
					else {
						//reduce donor size
						var donorToAdd = {
							DonorAccount: {
								Donor_No: donorObj.Donor_No,
								Photo_Urls: donorObj.Photo_Urls,
								UCPTitle: donorObj.UCPTitle,
								NewDonor: donorObj.NewDonor,
								NewRelease: donorObj.NewRelease
							}
						};

						//var donorToAdd = donorObj;

						//Add if < max allowed
						if (donors.length < 4) {
							donors.push(donorToAdd);
						}
						// over max
						else {
							bootbox.confirm({
								message: "You may compare up to 4 donors at a time. Would you like to compare the first 4 donors you selected?",
								buttons: {
									confirm: {
										label: 'Yes',
										className: 'btn btn-primary'
									},
									cancel: {
										label: 'No',
										className: 'btn btn-default'
									}
								},
								callback: function (result) {
									if (result) {
										window.location = "/compare-donors/"
									}
								}
							});
						} //end else (> max)
					} //end else (Add donor)
				//} //end else (add/remove donor)
				$http.post("/accountajax/updatecompareddonors/", donors);
			}
		});
	} // end update

    this.remove = function (donorNo) {
        var tempDonorNo = donorNo;
		this.getData().success(function (data) {
			if (data.status == "success") {
				var donors = data.comparedDonors;

                //IE does not support '=>' operator
				//var index = donors.findIndex(donor => donor.DonorAccount.Donor_No == donorNo);

                var index = -1;
                for (var i = 0; i < donors.length; i++) {
                    if (donors[i].DonorAccount.Donor_No == tempDonorNo) {
                        index = i;
                    }
                }


				// Remove if in list
                if (index > -1) {
                    donors.splice(index, 1);

					$http.post("/accountajax/updatecompareddonors/", donors);
				}

			}
		});
	}

	this.clear = function () {
		this.getData().success(function (data) {
			if (data.status == "success") {
				var donors = data.comparedDonors;

				while (donors.length > 0) { donors.pop() }

                $http.post("/accountajax/updatecompareddonors/", donors)
                    .then(function (response) {
                        
                    });
			}
		});
	} // end update
}]);

//FILTERS
// always return lower case
// shortens amex
app.filter('cardType', function () {
	return function (input, prettify) {
		res = "";
		if (input == null) return res;
		res = input.toLowerCase().replace("american express", "amex");
		if (prettify) {
			res = res.replace('amex', 'AMEX').capitalizeFirstLetter();
		}
		return res;
	}
});

app.filter('accountNo', function () {
	return function (input) {
		return input.toLowerCase().replace(/x/g, "");
	}
});

app.filter('defaultStrToBool', function () {
	return function (input) {
		return input.toLowerCase() == "yes";
	}

});

app.config(['$httpProvider', function($httpProvider) {
    //initialize get if not there
    if (!$httpProvider.defaults.headers.get) {
        $httpProvider.defaults.headers.get = {};    
    }    

    // Answer edited to include suggestions from comments
    // because previous version of code introduced browser-related errors

    //disable IE ajax request caching
    $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
    // extra
    $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
    $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
}]);;
app.service('CartService', [function () {
	const ivfTypes = ["-U-T2", "-U-T3"];
	var service = {};
	var $this = this;
	$this.MaxVials = maxVialCountToDisplay;
	$this.MinVials = minVialCountToDisplay;

	service.Cart = {};
	service.update = function (updatedCart) {

		if (updatedCart && updatedCart.Items) {
			for (var i = 0; i < updatedCart.Items.length; i++) {
				var item = updatedCart.Items[i];

				// Commented instead of removed just in case team decides to enforce 2 vials per purchase in cart in the future.
				item.isIVF = new RegExp(ivfTypes.join("|")).test(item.ItemNo);
				item.phone = '1-866-927-9622';
				item.isLowQty = false;

				if (item.AvailableQuantity > $this.MaxVials) {
					item.availabilityCopy = $this.MaxVials + '+ Available';
					var array = new Array(parseInt($this.MaxVials));

                    /*if (!item.isIVF) {
                        for (var j = 0; j < array.length; j++) { // code is implemented below, when uncommenting.
							array[j] = j + 1;
                        }
                    }
					else {
						array = new Array(Math.floor((parseInt($this.MaxVials)) / 2));
                        for (var j = 0; j < array.length; j++) {
							var k = (j + 1) * 2;
                            array[j] = k;
                        }
                    }*/
					for (var j = 0; j < array.length; j++) {
						array[j] = j + 1;
					}
					item.selectQty = array;
				}
				else if (!updatedCart.IsShipFromStorage && item.AvailableQuantity < $this.MinVials) {
					item.availabilityCopy = 'Call for Availability:';
					item.class = 'item-color-red';
					item.isLowQty = true;
					item.selectQty = [0];
				}
				else {
					item.availabilityCopy = item.AvailableQuantity + ' Available';
					var array = new Array(parseInt(item.AvailableQuantity));

                    /*if (!item.isIVF) {
                        for (var j = 0; j < array.length; j++) { // code is implemented below, when uncommenting.
							array[j] = j + 1;
                        }
                    }
					else {
						array = new Array(Math.floor((parseInt(item.AvailableQuantity)) / 2));
                        for (var j = 0; j < array.length; j++) {
							var k = (j + 1) * 2;
                            array[j] = k;
                        }
                    }*/
					for (var j = 0; j < array.length; j++) {
						array[j] = j + 1;
					}
					item.selectQty = array;
					item.class = 'item-color-red';
				}
				updatedCart.Items[i] = item;
			}
			service.Cart = updatedCart;
		}
		return service;
	};

	return service;
}]);

app.controller('cartController', ['$scope', '$http', 'CartService', '$rootScope', function ($scope, $http, CartService, $rootScope) {

	var $this = this;
	$this.LOW_VIALS_LEFT = LOW_VIALS_LEFT;
	$this.familyTodayMinVials = promoMinVials;

	if (currentCart) {
		CartService.update(currentCart);
	}

	$this.cart = CartService.Cart;
	
	$this.showFAQs = false;
	$this.spinnerActive = false;

	$scope.$watch(CartService.update, function (newValue, oldValue) {
		$this.cart = CartService.Cart;
		$this.getTotals();
	}, true);

	$this.getTotals = function () {
		$this.totalVials = 0;
		$this.totalValue = 0;
		if ($this.cart && $this.cart.Items) {
			$this.cart.Items.forEach(function (vialItem) {
				$this.totalVials += parseInt(vialItem.Quantity);
				$this.totalValue += parseInt(vialItem.Quantity * parseInt(vialItem.Price));
			});
		}
		if ($this.totalVials > 0) {
			$('#cart-count-header-wrapper').parent().css('color', '');
			$('#cart-count-header-wrapper').show();
			$('.cart-count').text($this.totalVials);
		}
		else {
			$('#cart-count-header-wrapper').parent().css('color', '#aaa');
			$('#cart-count-header-wrapper').hide();
			$('.cart-count').text("");
		}
	};

	$this.getTotals();


	$this.remove = function (array, index) {
		array.splice(index, 1);
		$this.getTotals();
		CartService.update($this.cart);
		$http.post('/cart/mobileupdatecart/',  $this.cart.Items)
			.then(function (data) {
				if (data && data.content && data.title) {
					$this.message = data.content;
				}
		});
	};

	$this.updateSession = function () {
		$http.post('/cart/mobileupdatecart/', $this.cart.Items).then(function (data) {
			if (data && data.content && data.title) {
				$this.message = data.content;
			}
		});
	};

	$this.checkout = function () {

	    $("#secure-checkout").attr("disabled", true);

		$this.spinnerActive = true;
		createCookie("vialTime", Date.now());
		window.location = "/cart";
	};
}]);

$(document).on('click touchstart', '.cart-icon-link', function (event) {
	var rootScope = $('[ng-controller~="cartController"]').scope().$root;
	rootScope.displayCartModal = true;
	rootScope.$digest();
});;
//app
	//.module('globalsitesearch', ['elasticsearch', 'ngSanitize'])
app.constant('globalEuiHost', globalSearchHOST)
app.service('globalESClient', ['esFactory', function (esFactory) {
		return esFactory({
			host: globalSearchHOST
		});
	}])
app.controller('GlobalSiteSearchController', ['$scope', 'globalESClient', 'esFactory', function ($scope, globalESClient, esFactory) {
		$scope.searchResults = [];
		$scope.showSearchResults = false;
		$scope.showNoResults = false;
		$scope.currentSearch = "";
		$scope.qs = "";

		$scope.clearDisplay = function () {
			$scope.showNoResults = false;
			$scope.searchInfoResults = [];
			$scope.searchDonorResults = [];
			$scope.searchResults = [];
		}

		$scope.clearSearch = function () {
			$scope.clearDisplay();
			$scope.showSearchResults = false;
			$scope.currentSearch = "";
		}

		$scope.wildcardQuery = function (querystring) {

			if (querystring.length < 3) {
				$scope.showSearchResults = false;
				$scope.clearDisplay();
				return;
			}

			$scope.showSearchResults = true;

			var queries = querystring.split(" ");
			var boolQuery = ejs.BoolQuery()
				.should(ejs.MatchQuery('title', querystring.toLowerCase()).type("phrase").slop(3).boost(10))
				.should(ejs.MatchQuery('desc', querystring.toLowerCase()).type("phrase").slop(3).boost(10))
				.should(ejs.MatchQuery('tags', querystring.toLowerCase()))
				//.should(ejs.MatchQuery('about', querystring.toLowerCase()).type("phrase").slop(2).boost(10))
				.should(ejs.MultiMatchQuery('about_*^10', querystring.toLowerCase()).type("phrase_prefix").slop(2))
				.should(ejs.MatchQuery('donor_No', querystring.toLowerCase()))

			for (var i = 0; i < queries.length; i++) {
				var queryPartial = queries[i];
				if (queryPartial.length >= 3) {
					boolQuery = boolQuery
						.should(ejs.PrefixQuery('title', queryPartial.toLowerCase()))
						.should(ejs.PrefixQuery('desc', queryPartial.toLowerCase()))
						.should(ejs.PrefixQuery('tags', queryPartial.toLowerCase()))
						//.should(ejs.PrefixQuery('about', queryPartial.toLowerCase()))
						.should(ejs.PrefixQuery('donor_No', queryPartial.toLowerCase()))
				}
			}

			//var weightedQuery = ejs.FunctionScoreQuery()
			//.query(boolQuery)
			//.functions([
			//	ejs.BoostFactorScoreFunction(10).filter(
			//		ejs.TermFilter("type", "content")
			//	),
			//])
			//.scoreMode("sum")
			//.boostMode("replace")

			$scope.qs = querystring;

			globalESClient.search({
				index: 'ccb_site_search',
				body: ejs.Request()
					.query(
						//weightedQuery
						boolQuery
					)
					.highlight(
						ejs.Highlight(
							['title', 'desc', 'donor_No', 'tags.raw', 'about_*']
						)
						.preTags("<span class='highlight'>")
						.postTags("</span>")
						.fragmentSize(45)
					)
			}).then(function (querystring, resp) {
				if (querystring == $scope.qs) {
					if (resp.hits.total > 0) {
						$scope.showNoResults = false;
						$scope.searchResults = resp.hits.hits;

					} else {
						$scope.clearDisplay();
						$scope.showNoResults = true;
					}
				}
			}.bind(null, querystring), function (error) {
				console.trace(error.message);
			});
		}

		$scope.handleEnter = function (e) {
			var keyCode = e.keyCode || e.which;
			var _searchWord = $('#siteSearchController .searchbox').val();

			if (keyCode == 13 && _searchWord.length >= 3) {
				analyticsTrack("Site Searched", {
					query: _searchWord
				}, function () {
          window.location = "/sitesearch/?q=" + $('#siteSearchController .searchbox').val();
        });
			}
		}

		$scope.getMatchedOn = function (doc) {
			if (!doc.highlight) { return; }

			var keys = Object.keys(doc.highlight);
			keys = keys.map(function (e) {
				return translateTag(e);
			})
			return keys.join(", ");
		
		}

		function translateTag(tag) {
			switch (tag) {
				case "about_Ancestry":
					return "Ancestry";
				case "about_Area_Of_Study":
					return "Area Of Study";
				case "about_Complexion":
					return "Complexion";
				case "about_Donor_Subtype":
					return "Donor Subtype";
				case "about_Education_Highest":
					return "Education";
				case "about_Ethnicity":
					return "Ethnicity";
				case "about_Eye_Color":
					return "Eye Color";
				case "about_Hair_Color":
					return "Hair Color";
				case "about_Hair_Texture":
					return "Hair Texture";
				case "about_Jewish_Ancestry":
					return "Jewish Ancestry";
				case "about_Religion":
					return "Religion";
				case "desc":
					return "Description";
				case "donor_No":
					return "Donor Number";
				case "tags":
					return "Tag";
				case "title":
					return "Title";
				default:
					return tag;
			}
		}

		$scope.limitDescDisplay = function (val) {
			return val.substr(0, 190) + "...";
		}

		$scope.escapeHTML = function (val) {
			var entityMap = {
				"&": "&amp;",
				"<": "&lt;",
				">": "&gt;",
				'"': '&quot;',
				"'": '&#39;',
				"/": '&#x2F;'
			};

			return String(val).replace(/[&<>"'\/]/g, function (s) {
				return entityMap[s];
			});
		}
	}]);;
app.directive('ngCollapse', [function () {
	var uniqueId = 1;
	return {
		restrict: "E",
		transclude: true,
		replace: true,
		scope: {
			ngVisible: '=',
			label: '@'
		},
		templateUrl: "/Angular/Donor/Directives/collapse.html",
		link: function (scope, element) {
			scope.collapsePanelId = 'collapse-panel-' + uniqueId++;
			
			$(".ng-ccb-collapse .collapse").collapse();

			scope.collapse = function (id) {
				var action = this.ngVisible ? "hide" : "show";
				this.ngVisible = !this.ngVisible;
				$("#" + id).collapse(action);
			}
		}
	}
}]);;
app.directive('mobileSlidePanel', [function () {
	var uniqueId = 1;
	return {
		restrict: "E",
		transclude: true,
		replace: true,
		scope: {
			ngShowPanel: '=',
			ngTitle: '@',
			ngShowPurchaseLink: '='
		},
		templateUrl: "/angular/directives/mobileslidepanel.html",
		link: function (scope, element) {
			scope.slidePanelId = 'mobile-slide-panel-' + uniqueId++;

			scope.show = function () {
				//display the fixed overlay
				$('#' + scope.slidePanelId).modal('show');
			};

			scope.hide = function () {
				//close fixed overlay 
				scope.ngShowPanel = false;
				$('#' + scope.slidePanelId).modal('hide');
			};

			scope.$watch('ngShowPanel', function (newVal, oldVal) {
				if (newVal) {
					scope.show();
				}
				else {
					scope.hide();
				}
			}, true);
		}
	}
}]);
;
app.directive('paymentPartial', ['$http', '$timeout', 'ModelService', 'CreditCardService', 'isUKUser', '$rootScope', function ($http, $timeout, ModelService, CreditCardService, isUKUser, $rootScope) {
	var uniqueId = 1;

	return {
		scope: {
			myController: '=',
			displayPaymentPartial: '=',
			itemNo: '=',
			ngAmount: '=',
            ngResetButton: '=',
            ngPromoCode: '=',
            ngSubmitPromoCode: '=',
            ngSwitchLevel: '='
		},
		restrict: "E",
		templateUrl: "/accountajax/paymentpartial/",
        link: function (scope, element) {
            
			scope.$timeout = $timeout;
            scope.radioName = 'user-cards-' + uniqueId++;
            scope.hasPromo = new URLSearchParams(window.location.search).has("promo");
			scope.isUKUser = isUKUser.val;
			usePromoCode();

			scope.creditCardCtrl = {};

			//credit cards
			scope.creditCards = CreditCardService.cards;

			scope.creditCards.forEach(function (card) {
				if (card.Default == 'Yes') {
					scope.selectedCard = card;
					scope.selectedCardExpMonth = card.ExpirationMonth;
					scope.selectedCardExpYear = card.ExpirationYear
				}
			});


			if (!scope.selectedCard && scope.creditCards && scope.creditCards.length > 0) {
			    scope.selectedCard = scope.creditCards[0];
			    scope.creditCards[0].Default = 'Yes';
			}

			scope.$watch('ngAmount', function (newVal, oldVal) {
				scope.itemCost = scope.ngAmount;
			}, true);

			scope.$watch('creditCards', function (newVal, oldVal) {
			    if (newVal) {
			        CreditCardService.cards = newVal;
			    }			
			    if (oldVal && newVal && oldVal.length == 0 && newVal.length == 1) {
			        scope.selectedCard = newVal[0];
			    }
			    else if(newVal) {
			        for (var i = 0; i < newVal.length; i++) {
                        if(newVal[i].Default == 'Yes'){
                            scope.selectedCard = newVal[i];
                            }
			        }
			    }

				
			}, true);
			
			scope.donorNo = scope.myController.model.DonorNo;

			//remove, make sure all is in resetView, and call resetView on load
			scope.alert = {};
			scope.showCardForm = false;
			scope.displayPaymentPartial = false;
			scope.displayPaymentMenu = true;
			scope.displayPromoCodeSection = true;
            scope.displayPromoCodeInput = scope.isUKUser || scope.hasPromo;
            scope.promoCodeVisible = scope.isUKUser || scope.hasPromo; //mobile
			scope.displayPromoCodeList = false;
			scope.showAddPromoCode = true;
			scope.displayPurchaseButton = true;
			scope.displayDefaultCard = (scope.creditCards != null && typeof scope.creditCards !== 'undefined') && scope.creditCards.length > 0;
			scope.displayChangeCard = false;
			scope.loadingUpdateCard = false;
            scope.loadingPromoCodeSubmit = false;
			scope.generalCardUpdating = false;

		    // General State Functions
			scope.resetView = function () {
			    scope.showCardForm = false;
			    scope.displayPaymentPartial = false;
			    scope.displayPaymentMenu = true;
			    scope.displayPromoCodeSection = true;
                scope.displayPromoCodeInput = scope.isUKUser || scope.hasPromo;
			    scope.displayPromoCodeList = false;
			    scope.showAddPromoCode = true;
			    scope.displayPurchaseButton = true;
			    scope.displayDefaultCard = (scope.creditCards != null && typeof scope.creditCards !== 'undefined') && scope.creditCards.length > 0;
			    scope.displayChangeCard = false;
			    scope.loadingUpdateCard = false;
			    scope.loadingPromoCodeSubmit = false;
			    scope.alert = {};
                if (!scope.isUKUser && !new URLSearchParams(window.location.search).has("promo")) { scope.removePromoCode(); }
			    scope.itemCost = scope.ngAmount;

			    scope.myController.newCard = {};
			    scope.myController.hideSections();
				//todo: check if not empty when called on page load. directive is called only after this runs
			    scope.creditCardCtrl.clearForm(); //calls method in creditCardForm.js directive

				usePromoCode();
			    if (scope.ngResetButton != null && typeof scope.ngResetButton !== 'undefined') {
			        scope.ngResetButton();
			    }

			};

		    // Credit Card Functions
			scope.toggleCardForm = function () {
			    if (scope.isUKUser) { return; }
			    if (scope.alert) {
			        scope.alert.visible = false;
			    }
			    else {
			        scope.alert = {};
			    }
				scope.showCardForm = !scope.showCardForm;
				scope.displayPaymentMenu = !scope.showCardForm;
			};

			scope.showChangeCard = function () {
			    scope.displayChangeCard = true;
			    scope.displayPromoCodeSection = false;
			    scope.displayPurchaseButton = false;
			};

			scope.showDefaultCard = function () {
			    scope.displayChangeCard = false;
			   
			    scope.displayPromoCodeSection = true;
			    scope.displayPurchaseButton = true;
			    scope.showCardForm = false;
			    scope.displayPaymentMenu = true;

			    if (scope.creditCards.length == 1) {
			    	scope.selectedCard = scope.creditCards[0];
			    }
			};

			scope.submitNewCard = function () { //send to creditCardForm.js directive
				scope.showDefaultCard();
				trackPageview('_trackPageview', craftAnalyticsPurchaseUrl(scope.itemNo, CreditCardService.cards.length > 0));
				scope.$parent.ngShowPanel = false;
				scope.ngShowPanel = false;
				scope.setDefaultCard(scope.creditCards[scope.creditCards.length-1]); //setting last card as default
			}

			scope.submitNewCardMobile = function () {
				this.submitNewCard();
				this.mobileClose();
			}

			scope.setDefaultCard = function (card) {
				//revert exp. dates to previous selected card
				scope.selectedCard.ExpirationMonth = scope.selectedCardExpMonth;
				scope.selectedCard.ExpirationYear = scope.selectedCardExpYear;
				

				for (var i = 0; i < scope.creditCards.length; i++) {
					scope.creditCards[i].Default = 'No';
					if (scope.creditCards[i].LineNo == card.LineNo) {
						scope.creditCards[i].Default = 'Yes';
					}
				}

				//backup current expiration date to revert when switching card
				scope.selectedCardExpMonth = card.ExpirationMonth;
				scope.selectedCardExpYear = card.ExpirationYear;

				scope.selectedCard = card;
			};

			scope.updateCreditCard = function (card) {
				if (scope.selectedCard) {

					if (card) { //mobile
						card.loadingUpdateCard = true;
					} else {
						scope.generalCardUpdating = true;
					}
					$http.post("/payment/updatecreditcard/", {
						"customerCard": scope.selectedCard,
						"source": prettifySource()
					})
					    .success(function (data) {
					    	scope.loadingUpdateCard = false;
					    	if (card) { //mobile
					    		card.loadingUpdateCard = false;
					    		card.showExpDropdown = false;
					    	}
					    	else {
					    		scope.generalCardUpdating = false;
					    	}
					    	scope.showDefaultCard();
					    	scope.alert = {};
					    	scope.selectedCardExpMonth = scope.selectedCard.ExpirationMonth;
					    	scope.selectedCardExpYear = scope.selectedCard.ExpirationYear;

					    	if (data.status == 'success') {
					    	    scope.alert.visible = false;
					    	    CreditCardService.cards = data.creditCards;
					    	}
					    	else {
					    		scope.alert.visible = true;
					    		scope.alert.text = data.message;
					    		scope.alert.class = 'alert-danger';
					    	}
					    });
				}
				else {
					// No Default Card
				}

			};

			scope.mobileClose = function () {
				this.$parent.hide(); //should be calling mobileSlidePanel
			}

			scope.closeChangeCard = function () {
				scope.showDefaultCard();
				scope.displayChangeCard = false;
			};

			scope.displayCardNo = function (no) {
			    if (no) {
			        return "***" + no.replace(/X/g, '');
			    }
			};

			scope.getLast4CCdigits = function (no) {
				return no.replace(/X/g, '');
			};
		    // End Credit Card Functions

            // Promo Code Functions
			scope.togglePromoCode = function () {
				scope.displayPromoCodeInput = !scope.displayPromoCodeInput;
			};

			scope.showPromoCode = function () {
				scope.displayPromoCodeInput = false;
				scope.showAddPromoCode = false;
				scope.promoCodeVisible = true;
				scope.displayPromoCodeList = true;
			}
			scope.removePromoCode = function () {
				scope.displayPromoCodeInput = false;
				scope.showAddPromoCode = true;
				scope.displayPromoCodeList = false;

				scope.itemCost = scope.oldItemCost;
				scope.oldItemCost = null;
				scope.promoCodeDiscount = null;
				usePromoCode();

			}

            scope.promoCodeSubmit = function (loadTimeout) {
                scope.ngPromoCode = scope.promoCode;
                var purchaseBtn = $('.payment-button .ladda-button');
                var l = purchaseBtn.ladda();

                purchaseBtn.ladda('start');

				$http.post("/payment/promocodesubmit/", { "promoCode": scope.promoCode, "itemNo": scope.itemNo })
                    .success(function (data) {
                        l.ladda('stop');
					    $timeout.cancel(loadTimeout);
					    scope.loadingPromoCodeSubmit = false;
						scope.alert = {};
						if (data.status == 'success') {
							scope.alert.visible = false;
					        scope.oldItemCost = scope.itemCost;
					        scope.promoCodeDiscount = data.discount;
					        scope.itemCost -= data.discount;
							scope.showPromoCode();
						} else {
					    	scope.alert.visible = true;
					    	scope.alert.text = data.message;
					    	scope.alert.class = 'alert-danger';
							scope.alert.logMessage = data.logMessage;
							usePromoCode();
						}
				});
            };

            scope.ngSubmitPromoCode = scope.promoCodeSubmit;
		    // End Promo Code Functions

			scope.purchaseItem = function () {
				var purchaseBtn = $('.payment-button:visible .ladda-button');
				var l = purchaseBtn.ladda();
				l.ladda('start');
				//Check if promo code is enabled but not applied
				if (isPromoCodeNotApplied()) {
					l.ladda('stop');
					return;
				}

				trackPageview('_trackPageview', craftAnalyticsPurchaseUrl(scope.itemNo, false));
				var cc = {};

				for (var i = 0; i < scope.creditCards.length; i++) {
					var card = scope.creditCards[i];
					if (card.Default.toLowerCase() == 'yes') {
						cc = card;
					}
				}

				if (cc && !$.isEmptyObject(cc)) {
					var ccDigits = scope.getLast4CCdigits(cc.AccountNo);
				}
				else {
					ccDigits = "";
					cc.LineNo = "";
				}
				if ((cc && !$.isEmptyObject(cc) && cc.LineNo != 0) || (scope.promoCode && scope.itemCost <= 0)) {

				    var currentTransaction = getTransactionID();
				    var transactionSource = getTransactionSource(scope.itemNo);
				    var transactionPrice = !!scope.itemCost ? parseFloat(scope.itemCost) : 0;

				    var productSKU = getItemSKU(transactionSource, scope.itemNo);
				    var productName = getProductName(transactionSource, scope.itemNo);
				    var itemProductCategory = getItemCatogory(transactionSource, scope.itemNo);

				    $('.confirm-purchase-btn').attr("disabled", true);

					$http.post("/payment/purchase/", { "donorNo": scope.donorNo, "cc4Digits": ccDigits, "itemNo": scope.itemNo, "lineNo": cc.LineNo, "promo": scope.promoCode, "amount": scope.itemCost, "order_id": currentTransaction })
						.success(function (data) {
						    //$timeout.cancel(loadTimeout);

							scope.alert = {};
							if (data.status == 'success') {
								scope.alert.visible = false;

								var today = new Date();
								var endDate = (data.subscriptionExpDate != "" ? new Date(data.subscriptionExpDate).toISOString() : "");

								if (transactionSource == "alacarte") {
									analyticsTrack("Item Purchased", {
										order_id: currentTransaction,
										product_category: "information item",
										product_name: productName,
										donor_id: scope.donorNo,
										price: transactionPrice,
										value: transactionPrice,
										featured_donor: document.URL.includes("featured"),
										donor_type: $("#donor-type .look-a-likes").first().text(),
										level: getItemLevelFromInitials(scope.itemNo.split("-")[1])
									}, function () {
										analyticsTrack("Order Placed", {
											order_id: currentTransaction,
											product_category: "information item",
											total: transactionPrice,
											revenue_client: transactionPrice
										});
									});
								}
								else {
									CheckForWhitelistTraits()
									analytics.identify(data.contactNo, {
										subscription_status: "active",
										subscription_code: scope.itemNo,
										subscription_start_date: today.toISOString(),
										subscription_end_date: endDate,
									})

									if (transactionSource == "subscription") {
										const ogSubLvl = ModelService.Model.UserSubscriptionLevel;
										if (ogSubLvl == 1) {
											let name = productName.trim().split(" ");
											analyticsTrack("Subscription Started", {
												plan_name: name[name.length - 2] + " " + name[name.length - 1],
												plan_code: scope.itemNo,
												plan_billing_amount: parseFloat(scope.itemCost),
												plan_discount: scope.promoCodeDiscount,
												plan_start_date: today.toISOString(),
												plan_end_date: endDate,
												source: document.referrer,
												revenue_client: scope.itemCost
											});
										} else if (ogSubLvl == 2) {
											analyticsTrack("Subscription Upgraded", {
												original_plan_name: "Level 2",
												original_plan_code: "DSS-DIC-LEVEL2-90D",
												original_plan_billing_amount: parseFloat(ModelService.Model.Level_2_price),
												original_plan_discount: parseFloat(ModelService.Model.discount),
												new_plan_name: "Upgrade Level 3",
												new_plan_code: scope.itemNo,
												new_plan_billing_amount: parseFloat(scope.itemCost),
												new_plan_discount: scope.promoCodeDiscount,
												plan_start_date: today.toISOString(),
												plan_end_date: endDate,
												source: document.referrer,
												revenue_client: parseFloat(scope.itemCost),
											});
										}
									}
								}

								// Remove local storage item, because if it isn't removed, will pass along this information to subsequent segment calls
								if (localStorage.getItem("ajs_user_traits")) {
									localStorage.removeItem("ajs_user_traits");
								}

                                scope.removePromoCode();

								// set subscription level and donor resources
								ModelService.Model.DonorResourceItems = data.resources;

								ModelService.Model.UserSubscriptionLevel = data.subscriptionLevel;
								
								ModelService.Model.SubscriptionExpDate = data.subscriptionExpDate;
								ModelService.Model.ChildhoodPhotos = data.childhoodPhotos;

								//scope.displayPaymentMenu = false;
								scope.displayPaymentPartial = false;
								trackPageview('_trackPageview', craftAnalyticsPurchaseUrl(scope.itemNo, true));

								trackEvent(['_addTrans',
								   currentTransaction,		// transaction ID
								   transactionSource,		// affiliation or store name
								   transactionPrice,		// total - required; Shown as "Revenue" in the transactions report. Does not include Tax and Shipping.
								   '0',					// tax
								   '0',  					// shipping
								   '',    					// city
								   '',  					// state or province
								   ''						// country
								]);

								trackEvent(['_addItem',
									currentTransaction,		// transaction ID - necessary to associate item with transaction
									productSKU,				// SKU/code - required
									productName,			// product name - necessary to associate revenue with product (Subscription/A la carte)
									itemProductCategory,	// category or variation
									transactionPrice,		// unit price - required
									'1'						// quantity - required
								]);

								trackEvent(['_trackTrans']);

							}
							else {
								scope.alert.visible = true;
								scope.alert.text = data.message;
								scope.alert.logMessage = data.logMessage;
								scope.alert.class = 'alert-danger';
							}
							l.ladda('stop');

						    //end ga transaction
							
						});
				}
				else {
					l.ladda('stop');
					scope.alert.visible = true;
					scope.alert.text = "Please add a credit card or promo code.";
					scope.alert.class = 'alert-danger';
				}
			};

			function usePromoCode() {

				// Check if user is from UK automatically put promo code
				if (scope.isUKUser) {
					scope.promoCode = "W0316UKC";
					scope.ngPromoCode = scope.promoCode;
					return;
				}

				// Check promo code in query parameter
				if (scope.hasPromo) {
					scope.promoCode = new URLSearchParams(window.location.search).get("promo");
					scope.ngPromoCode = scope.promoCode;
					return;
				}

				// Any other promo code injection will take last priority
				if (scope.promoCode !== '') {
					scope.ngPromoCode = scope.promoCode;
				}
			}

			function isPromoCodeNotApplied() {
				//promo section is open on Desktop or Mobile
				if ((scope.displayPromoCodeInput || (scope.promoCodeVisible && !scope.displayPromoCodeList)) && scope.promoCode != "" && scope.promoCode != undefined) {
					scope.alert.visible = true;
					scope.alert.text = 'Please click "Apply" to use promo code.';
					scope.alert.class = 'alert-warning';
					return true;
				}
				return false;
			}

			function getTransactionID() {
			    return currentUserNo + "_" + Date.now();
			}

			function getTransactionSource(itemNo) {
			    if (itemNo == "DSS-DIC-LEVEL2-90D" || itemNo == "DSS-DIC-LEVEL3-90D" || itemNo == "DSS-DIC-UPGRADE-90D") {
			        return "subscription";
			    }
			    else {
			        return "alacarte";
			    }
			}

			function getItemCatogory(source, itemNo) {
			    var res;
			    if (source == "subscription") {
			        res = itemNo == "DSS-DIC-UPGRADE-90D" ? "Other" : "Donor Subscription";
			    }
			    else {
			        res = "Donor Info";
			    }
			    return res;
			}

			function getProductName(source, itemId) {
			    var res;
			    if (source == "subscription") {
			        switch (itemId) {
			            case "DSS-DIC-LEVEL2-90D":
			                res = "Donor DSS: Donor Subscription Level 2";
			                break;
			            case "DSS-DIC-LEVEL3-90D":
			                res = "Donor DSS: Donor Subscription Level 3";
			                break;
			            case "DSS-DIC-UPGRADE-90D":
			                res = "Donor DSS: Donor Subscription Upgrade to Level 3";
			                break;
			            default:
			                res = "Subscription item NA";
			        }
			    }
			    else { //a la carte
			        var itemCode = itemId.split("-")[1];
			        res = getItemDescriptionFromInitials(itemCode);
			    }
			    return res;
			}

			function getItemSKU(source, itemId) {
			    var res;
			    if (source == "subscription") {
			        switch (itemId) {
			            case "DSS-DIC-LEVEL2-90D":
			                res = "Donor DSS: Donor Subscription Level 2";
			                break;
			            case "DSS-DIC-LEVEL3-90D":
			                res = "Donor DSS: Donor Subscription Level 3";
			                break;
			            case "DSS-DIC-UPGRADE-90D":
			                res = "Donor DSS: Donor Subscription Upgrade to Level 3";
			                break;
			            default:
			                res = "Subscription item NA";
			        }
			    }
			    else { //a la carte
			        var itemParts = itemId.split("-");
			        res = "Donor " + itemParts[0] + ": " + getItemDescriptionFromInitials(itemParts[1]);
			    }
			    return res;

			}

			function getItemDescriptionFromInitials(itemInitials) {
				switch (itemInitials.toUpperCase()) {
					// level 1
					case "SP":
						res = "Donor Profile";
						break
					case "MH":
						res = "Medical History";
						break
					case "GT":
						res = "Genetic Test Summary";
						break
					case "DNA":
						res = "DNA Ancestry";
						break
					case "ES":
						res = "Donor Personal Essay";
						break
					case "SI":
						res = "Staff Impressions";
						break

					// level 2
			        case "LP":
			            res = "Extended Donor Profile";
			            break
			        case "BP":
			            res = "Childhood Photo(s)";
						break
					case "AP":
						res = "Adult Photo(s)"
						break
			        case "EY":
			            res = "Express Yourself";
						break

					// level 3
					case "FF":
						res = "Facial Features Report";
						break
			        case "AI":
			            res = "Donor Conversation";
			            break
			        case "KE":
			            res = "Keirsey Report";
			            break
					case "KQ":
						res = "Keirsey Q&A"
						break

			        default:
			            res = "a La Carte item NA";
			    }
			    return res;
			}

			function getItemLevelFromInitials(itemInitials) {
				switch (itemInitials.toUpperCase()) {
					// level 1
					case "SP":
					case "MH":
					case "GT":
					case "DNA":
					case "ES":
					case "SI":
						res = 1;
						break

					// level 2
					case "LP":
					case "BP":
					case "AP":
					case "EY":
						res = 2;
						break

					// level 3
					case "FF":
					case "AI":
					case "KE":
					case "KQ":
						res = 3;
						break

					default:
						res = "";
				}
				return res;
			}

			function craftAnalyticsPurchaseUrl(itemNo, confirm) {
			    var returnUrl = "/" + getCurrUrl() + "/";
			    var confirm = confirm ? "/confirm" : ""
			    if (itemNo == "DSS-DIC-LEVEL2-90D") {
			        return returnUrl + "subscription/purchase-l2" + confirm;
		        }
			    else if (itemNo == "DSS-DIC-LEVEL3-90D") {
			        return returnUrl + "subscription/purchase-l3" + confirm;
	            }
			    else if (itemNo == "DSS-DIC-UPGRADE-90D") {
			        return returnUrl + "subscription/purchase-upgrade" + confirm;
			    }
			    else {
			        return returnUrl + "alacarte/purchase" + confirm;
			    }
			}

			function craftAnalyticsUpdateCardUrl(itemNo) {
			    var returnUrl = "/" + getCurrUrl() + "/";
			    var section = (itemNo == "DSS-DIC-LEVEL2-90D" || itemNo == "DSS-DIC-LEVEL3-90D" || itemNo == "DSS-DIC-UPGRADE-90D") ? "Subscription" : "aLaCarte";
			    return returnUrl + section + "/purchase/select-payment-method-clicked-change/select-card";
			}

			function getCurrUrl() {
			    if (window.location.pathname.indexOf("donor-subscription/options") > -1) {
			        return "donor-subscription/options";
			    }
			    return "Profile";
			}

		}
	} //end return

	scope.resetView();
}]);

app.filter('formatCost', [function () {
	return function (input) {
		if (input == null || typeof input === 'undefined') {
			return null;
		}
		if (input <= 0) {
			return "Free";
		}
		return "$" + input;
	}
}]);
// End General State Functions

// Before segment identify call is made, make sure non-whitelisted traits are not in "ajs_user_traits" local storage item
// This method is duplicated in multiple javascript files
function CheckForWhitelistTraits() {

	var ajstraits = localStorage.getItem("ajs_user_traits");
	var traits = JSON.parse(ajstraits);

	// planned traits for all segment identify calls
	var whitelistedTraits = ["user_id", "city", "state", "country", "zip_code", "age", "created_at", "customer_type", "self_reported_lead_source", "subscription_status", "subscription_code","subscription_start_date", "subscription_end_date", "vial_purchase_count", "subscription_purchase_count"];

	if (traits !== null){	
		var keys = Object.keys(traits);

		// if there exists a key that is not on the whitelist
		if (!(keys.every(x => whitelistedTraits.includes(x)))) {

			var blackList = [];
			keys.forEach(x => { if (!whitelistedTraits.includes(x)) { blackList.push(x) } });
			blackList.forEach(x => delete traits[x]);

			// override the local storage item with only whitelist traits
			localStorage.setItem("ajs_user_traits", JSON.stringify(traits));
		}
	}
}

// Pathname must start with /donor/{5 digit number}
// Query parameters will pass
const donorPathNameRegex = /^\/donor\/\d{5}(\/|\b)(\?.*)?$/

// Event listener to help manage promo code after registration, uses session storage
window.addEventListener('load', () => {

	// Only run on donor profile page
	if (!donorPathNameRegex.test(window.location.pathname)) {
		return;
	}

	const hasPromo = new URLSearchParams(window.location.search).has('promo');
	const savedURLPromo = sessionStorage.getItem('savedPromo');

	// If has no query parameter and data is available in session storage
	if (!hasPromo && savedURLPromo) {
		window.location.replace(savedURLPromo);
		return;
	}

	// If it has a promo code query in url, upsert session storage
	if (hasPromo) {
		sessionStorage.setItem('savedPromo', window.location.href);
	}

});;
app.directive('creditCardForm', ['$http', '$timeout', function ($http, $timeout) {
	var uniqueId = 1;
	return {
		restrict: "EA",
		templateUrl: "/AccountAjax/creditCardForm/",
		scope: {
			cards: "=",
			cancelCallBackFn: "&cancelfn",
			submitCallBankFn: "&submitfn",
			control: "=",
			submitCopy: "@",

		},
		link: function (scope, element) {
		    scope.$timeout = $timeout;
		    scope.collapsePanelId = 'collapse-panel-' + uniqueId++;
		    scope.loadingCreditCardFormSubmit = false;
			scope.submitCopy = scope.submitCopy || 'Add Card';

		    scope.newCard = {};

			//API
		    scope.thisControl = scope.control || {};
		    scope.thisControl.clearForm = function () {
		    	scope.clearForm();
		    }

		    scope.thisControl.card = scope.newCard;
		    scope.editMode = false;

			//end API
		    scope.thisControl.setEditMode = function (isSet) {
		    	scope.editMode = isSet;
		    }
		    scope.thisControl.getEditMode = function () {
		    	return scope.editMode == true;
		    }

		    scope.clearForm = function () {
		    	for (var property in scope.newCard) {		    		
		    		scope.newCard[property] = null;
		    	}
		    	scope.creditCardForm.$setPristine();
				scope.creditCardForm.$setUntouched();
			}

			if (!scope.alert) {
				scope.alert = {};
			}

			scope.cancel = function () {
				scope.cancelCallBackFn(); //calls method in control (e.g hide section)
				scope.clearForm();	
			}

			scope.submit = function (loadTimeout) {
			    
			    var l = $('.card-form-submit-button.ladda-button:visible').ladda();
			    l.ladda('start');
				$http.post("/payment/addoreditcreditcard/", {
					card: scope.newCard,
					source: prettifySource(),
					company: getCompanyFromSource()

				})
					.then(function (response) {
					    l.ladda('stop');

					    $timeout.cancel(loadTimeout);
					    scope.loadingCreditCardFormSubmit = false;
					    var data = response.data;
					    if (data && data.status == "success")
					    {
					    	scope.alert.visible = false;
							analyticsTrack("Payment Info Entered", {
								payment_method: scope.newCard.accountType
							});
					    	if (scope.editMode) { 
					    		scope.cards.forEach(function (el, index, arr) {
					    			if (el.LineNo == data.CustomerCreditCard.LineNo) {
					    				arr[index] = data.CustomerCreditCard;
					    			}
					    		});
					    	}
					    	else { //add new credit card to list
					    		scope.cards.push(data.CustomerCreditCard)
					    	}

					    	scope.clearForm();
					    	
					    	if (scope.submitCallBankFn)
					    	{
					    		scope.submitCallBankFn();
					    	}

					    }
					    else { //Fail
					    	scope.alert.visible = true;
					    
					    	if (data) {
					    		if (data.message) {
					    			scope.alert.text = data.message;
					    		}
					    		scope.alert.logMessage = data.logMessage;
					    		scope.alert.class = 'alert-danger';

					    		if (typeof _LTracker != 'undefined') {
					    			_LTracker.push({
					    				'category': 'BrowserJsException',
					    				'message': data.message,
					    				'logMessage': data.logMessage
					    			});
					    		}
					    	}
					    	else {
					    		scope.alert.text = 'We\'re sorry, there is a problem with your credit card. Please call Client Services at 866-927-9622.';
					    		scope.alert.logMessage = 'Server was not responsive';
					    		scope.alert.class = 'alert-danger';
					    		if (_LTracker) {
					    			_LTracker.push({
					    				'category': 'BrowserJsException',
					    				'message': 'We\'re sorry, there is a problem with your credit card. Please call Client Services at 866-927-9622.',
					    				'logMessage': 'Server was not responsive',
					    				'status': response.status,
					    				'statusText': response.statusText
					    			});
					    		}
					    	}
					    }
					});
			};

			function craftAnalyticsAddCardUrl(itemNo, hasCards) {
				if (itemNo) {
					var returnUrl = "/profile/";
					var section = (itemNo == "DSS-DIC-LEVEL2-90D" || itemNo == "DSS-DIC-LEVEL3-90D" || itemNo == "DSS-DIC-UPGRADE-90D") ? "Subscription" : "aLaCarte";
					if (hasCards) {
						return returnUrl + section + "/purchase/select-payment-method-clicked-change/add-new-card";
					}
					else {
						return returnurl + section + "/purchase/select-payment-method-no-cc/add-new-card";
					}
				}
				else {
					return null;
				}
			}

			scope.validateExpiration = function () {
				var d = new Date(this.newCard.expirationYear, this.newCard.expirationMonth);

				if (d < new Date()) {
					this.creditCardForm.expirationMonth.$setValidity('expired', false)
					this.creditCardForm.expirationYear.$setValidity('expired', false)
				}
				else {
					this.creditCardForm.expirationMonth.$setValidity('expired', true)
					this.creditCardForm.expirationYear.$setValidity('expired', true)
				}
			}

		}
	}
}]);

function prettifySource() {	
	var path = forceTrailSlash(location.pathname.toLowerCase());
	var res = path;

	if (path.indexOf("billing-info") > -1) {
		res = "Billing Info";
	}
	else if (path.indexOf("donor-subscription/options") > -1) {
		res = "Donor Sub Options";
	}
	else if (path.indexOf("donor/") > -1) {
		res = "Donor Profile";
	}
	else if (path.indexOf("fc-renewal/") > -1) {
		res = "Familycord Renewal";
	}

	return res;
}


function getCompanyFromSource() {
	var path = forceTrailSlash(location.pathname.toLowerCase());
	var res = path.indexOf("fc-renewal/") > -1 ? "stem" : "ccb";
	return res;
};
app.directive('ngCard', [function () {
	return {
		restrict: 'A',
		require: 'ngModel',

		link: function (scope, element, attrs, ctrl) {
			scope.$watch(attrs.ngModel, function () {
				$(element).validateCreditCard(function (result) {
					if (scope.editMode) {
						ctrl.$setValidity('card', true);
					}
					else {
						if (scope.newCard) {
							//set Account Type
							if (result.card_type != null) {
								scope.newCard.accountType = result.card_type.name;
							}
							else {
								scope.newCard.accountType = '';
							}
						}
						//set Validity
						if (result.card_type != null && result.length_valid && result.luhn_valid) {
							ctrl.$setValidity('card', true);
						}
						else {
							ctrl.$setValidity('card', false);
						}
					}
				}, {
					accept: ['visa', 'mastercard', 'discover', 'amex']
				});
			});
		}
	}
}]);;
app.directive('ccbAlert', ['$timeout', function ($timeout) {
	return {
		scope: {
			ngModel: '=alert'
		},
		template: '<div class="alert alert-{{ngModel.level}}" ng-show="ngModel.level">' +
					'   <a href="" class="close" ng-click="close()" ng-hide="ngModel.closeTime">&times;</a>' +
					'	<span class="msg" ng-bind-html="ngModel.message"></span>' +
					'	<span class="errorMsg hidden">{{ngModel.hiddenCopy}}</span>' +
					'</div>'
		,
		link: function (scope, element, attrs) {
			scope.close = function () {
				this.ngModel.closeFn(this.ngModel);
			}
		}
	}
}]);



;
app.directive('accessibleForm', function () {
    return {
        restrict: 'A',
        link: function (scope, elem) {
			
            // set up event handler on the form element
            elem.on('submit', function () {

                // find the first invalid element
                var firstInvalid = elem.first().find(".ng-invalid:visible").first();

				// if we find one, set focus
                if (firstInvalid) {
                    firstInvalid.focus();
                }
            });
        }
    };
});;
//ALERT
app.service('alertService', ['$timeout', function ($timeout) {
	this.alert = {}; //single alert
	this.timer = {};

	//Defaults
	this.levels = {
		success: 'success',
		warning: 'warning',
		error: 'danger',
		info: 'info'
	}

	this.messages = {
		postError: 'An error occured, please try again later.',
		loadError: 'A problem occured while loading this page. Please try again or call Client Services at 866-927-9622.'
	}

	this.timeoutDefault = 5000;


	//Methods
	this.showAlert = function (level, message, hiddenCopy, closeTime) {
		this.close = function (el) {
			el.level = null;
		}

		//single alert
		this.alert.level = level;
		this.alert.message = message;
		this.alert.hiddenCopy = hiddenCopy;
		this.alert.closeTime = closeTime;
		this.alert.closeFn = this.close;

		$timeout.cancel(this.timer);

		//single alert
		if (closeTime) {
			this.timer = $timeout(function (al) {
				al.level = null;
			}, closeTime, true, this.alert);
		}
	}
}]);

//subscription level enum
app.service('SubscriptionLevelService', function () {
	this.SubscriptionLevel =
	{
		Anon: 0,
		Level_1: 1,
		Level_2: 2,
		Level_3: 3
	}
});


app.service('isUKUser', function () {
	this.val = isUKUser;
});

app.service("CreditCardService", function () {
	this.cards = (typeof creditCards != 'undefined') ? creditCards : [];
});

app.service('ModelService', function () {
	this.Model = _donor_model;
});

app.service('CacheService', ['$cacheFactory', function ($cacheFactory) {
	return $cacheFactory('accountCache');
}]);
;
// always return lower case
// shortens amex
app.filter('cardType', function () {
	return function (input, prettify) {
		res = "";
		if (input == null) return res;
		res = input.toLowerCase().replace("american express", "amex");
		if (prettify) {
			res = res.replace('amex', 'AMEX').capitalizeFirstLetter();
		}
		return res;
	}
});



app.filter('accountNo', function () {
	return function (input) {
		return input.toLowerCase().replace(/x/g, "");
	}
});


app.filter('defaultStrToBool', function () {
	return function (input) {
		return input.toLowerCase() == "yes";
	}

});


angular.module('formatTitleFilter', []).filter('formatTitle', function () {
	return function (input) {
		var split = input.split(" ");
		if (split.length >= 2) {
			var res = split[0];
			for (var i = 1; i < split.length; i++) {
				res += "<br>" + split[i];
			}
			return res;
		}
		else {
			return input;
		}
	};
});



// Came from the comments here:  https://gist.github.com/maruf-nc/5625869
app.filter('titlecase', function () {
	return function (input) {
		var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;

		input = input.toLowerCase();
		return input.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function (match, index, title) {
			if (index > 0 && index + match.length !== title.length &&
                match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
                (title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
                title.charAt(index - 1).search(/[^\s-]/) < 0) {
				return match.toLowerCase();
			}

			if (match.substr(1).search(/[A-Z]|\../) > -1) {
				return match;
			}

			return match.charAt(0).toUpperCase() + match.substr(1);
		});
	}
});


app.filter('countryNameByCode', function () {
	return function (input, countriesDict) {
		var dictVal = countriesDict[input]
		if (typeof (countriesDict[input]) == "undefined") {
			return input;
		}
		else {
			return dictVal.Name;
		}

	}
});

//return array of [total] length
app.filter('range', function() {
  return function(input, total) {
    total = parseInt(total);
    for (var i=0; i<total; i++)
      input.push(i);
    return input;
  };
});

app.filter('arrayToString', function () {
	return function (input, del) {
		if (input && input.join) {
			del = del || ',';
			return input.join(del);
		}
		else {
			return input;
		}
	};
});

// returns string for shortand time. e.g 1Y -> 1 Year
// Supports: {Year, Month, Week, Day}
app.filter('timeShortHand', function () {
	return function (shTime) {
		var amount, type, typeStr;

		//Parse Time Length
		var digitMatch = shTime.match(/\d*/);
		
		if (digitMatch.length > 0) {
			amount = digitMatch[0];
		}
		else { return shTime; }
		
		//Parse Time Type
		var timeTypeMatch = shTime.match(/[a-z]/i)
		
		if (timeTypeMatch.length > 0) {
			type = timeTypeMatch[0];
		}
		else { return shTime; }

		//Parse Type
		switch (type.toLowerCase()) {
			case "y":
				typeStr = "Year";
				break;
			case "m":
				typeStr = "Month";
				break;
			case "w":
				typeStr = "Week";
				break;
			case "d":
				typeStr = "Day";
				break;
		}
		
		var pluralStr = amount > 1 ? "s" : "";
		return amount + " " + typeStr + pluralStr;
	};
});;
