UNPKG

jay-brat-frontend-editor

Version:
4,233 lines 830 kB
var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj;}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a;}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r);},p,p.exports,r,e,n,t);}return n[i].exports;}for(var u="function"==typeof require&&require,i=0;i<t.length;i++){o(t[i]);}return o;}return r;})()({1:[function(require,module,exports){module.exports="<div id=\"brat-frontend-editor\">\n    <div id=\"commentpopup\"></div>\n    <div id=\"svg\"></div>\n\n    <!-- Span dialog (view+edit) -->\n    <form id=\"span_form\" class=\"dialog\" title=\"Span\">\n        <!-- Span dialog annotated text -->\n        <fieldset id=\"span_selected_fset\">\n            <legend>Text</legend>\n            <a target=\"brat_linked\" id=\"span_highlight_link\" href=\"#\">Link</a>\n            <div id=\"span_selected\"/>\n        </fieldset>\n        <!-- Span dialog search links -->\n        <fieldset id=\"span_search_fieldset\">\n            <legend>Search</legend>\n            <div id=\"span_search_links\"/>\n        </fieldset>\n        <!-- Span dialog type selector -->\n        <fieldset>\n            <div id=\"entity_and_event_wrapper\" class=\"split_wrapper\">\n                <div id=\"span_entity_section\" class=\"wrapper_half_left\">\n                    <div id=\"entity_label\" class=\"label-like\">\n                        Entity type\n                    </div>\n                    <div id=\"entity_types\" class=\"scroll_wrapper_upper\">\n                        <div class=\"scroller\"></div>\n                    </div>\n                    <!-- NOTE: the attribute labels must be *outside* of the\n                         divs they logically belong to prevent scrollers\n                         overflowing them. -->\n                    <div id=\"entity_attribute_label\" class=\"label-like wrapper_lower_label\">\n                        Entity attributes\n                    </div>\n                    <div id=\"entity_attributes\" class=\"scroll_wrapper_lower\">\n                        <div class=\"scroller small-buttons\"></div>\n                    </div>\n                </div>\n                <div id=\"span_event_section\" class=\"wrapper_half_right\">\n                    <div id=\"event_label\" class=\"label-like\">\n                        Event type\n                    </div>\n                    <div id=\"event_types\" class=\"scroll_wrapper_upper\">\n                        <div class=\"scroller\"></div>\n                    </div>\n                    <div id=\"event_attribute_label\" class=\"wrapper_lower_label label-like\">\n                        Event attributes\n                    </div>\n                    <div id=\"event_attributes\" class=\"scroll_wrapper_lower\">\n                        <div class=\"scroller small-buttons\"></div>\n                    </div>\n                </div>\n            </div>\n        </fieldset>\n        <!-- Span dialog normalization -->\n        <fieldset id=\"norm_fieldset\">\n            <legend>Normalization</legend>\n            <div id=\"norm_container\">\n                <select id=\"span_norm_db\"/>\n                <a id=\"span_norm_db_link\" target=\"brat_linked\" href=\"#\" title=\"Search DB\"><img class=\"brat-fugue-shadowless-magnifier\" src=\"static/img/Fugue-shadowless-magnifier.png\" style=\"vertical-align: middle\"/></a>\n                <span class=\"span_norm_label\">ID:</span>\n                <input id=\"span_norm_id\" class=\"span_norm_id_input\"\n                       style=\"width:20%\"/>\n                <span class=\"span_norm_label\">Ref:</span>\n                <input id=\"span_norm_txt\" class=\"span_norm_txt_input\"\n                       readonly=\"readonly\" style=\"width:45%\"\n                       placeholder=\"Click here to search\"/>\n                <a id=\"span_norm_ref_link\" target=\"brat_linked\" href=\"#\" title=\"See in DB\"><img class=\"brat-fugue-shadowless-external\" src=\"static/img/Fugue-shadowless-external.png\" style=\"vertical-align: middle\"/></a>\n                <input id=\"clear_norm_button\" type=\"button\"\n                       value=\"&#x2715;\" title=\"Clear normalization\"/>\n            </div>\n        </fieldset>\n        <!-- Span dialog notes -->\n        <fieldset>\n            <legend>Notes</legend>\n            <div id=\"notes_container\">\n                <input id=\"span_notes\" class=\"borderless\"/>\n                <input id=\"clear_notes_button\" type=\"button\"\n                       value=\"&#x2715;\" title=\"Clear notes\"/>\n            </div>\n        </fieldset>\n    </form>\n\n    <!-- Rapid mode span dialog -->\n    <form id=\"rapid_span_form\" class=\"dialog\" title=\"Span type\">\n        <fieldset id=\"rapid_span_selected_fset\">\n            <legend>Text</legend>\n            <div id=\"rapid_span_selected\"/>\n        </fieldset>\n        <div id=\"rapid_span_types\" class=\"scroll_fset\" style=\"height:250px\">\n            <fieldset>\n                <legend>Select type</legend>\n                <div class=\"scroller\" id=\"rapid_span_types_div\">\n                    <!-- filled dynamically -->\n                </div>\n            </fieldset>\n        </div>\n    </form>\n\n    <!-- Arc dialog -->\n    <form id=\"arc_form\" class=\"dialog\" title=\"Arc\">\n        <fieldset id=\"arc_origin_fset\">\n            <legend>From</legend>\n            <a target=\"brat_linked\" id=\"arc_highlight_link\" href=\"#\">Link</a>\n            <div id=\"arc_origin\"/>\n        </fieldset>\n\n        <fieldset id=\"arc_target_fset\">\n            <legend>To</legend>\n            <div id=\"arc_target\"/>\n        </fieldset>\n\n        <div id=\"arc_roles\" class=\"scroll_fset\">\n            <fieldset>\n                <legend>Type</legend>\n                <div class=\"scroller\"/>\n            </fieldset>\n        </div>\n\n        <fieldset id=\"arc_notes_fieldset\">\n            <legend>Notes</legend>\n            <input id=\"arc_notes\" class=\"borderless\"/>\n        </fieldset>\n\n    </form>\n\n    <!-- Split span annotation dialog -->\n    <form id=\"split_form\" class=\"dialog\" title=\"Split the Span\">\n        <fieldset>\n            <legend>Split Roles</legend>\n            <div id=\"split_roles\" class=\"scroll_fset\"/>\n        </fieldset>\n    </form>\n\n    <!-- Spinner -->\n    <!--<div id=\"waiter\" class=\"dialog\" title=\"Please wait\">\n        <img class=\"brat-spinner\" src=\"static/img/spinner.gif\"/>\n    </div>-->\n</div>";},{}],2:[function(require,module,exports){/*!
 * jQuery UI 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */(function(c,j){function k(a,b){var d=a.nodeName.toLowerCase();if("area"===d){b=a.parentNode;d=b.name;if(!a.href||!d||b.nodeName.toLowerCase()!=="map")return false;a=c("img[usemap=#"+d+"]")[0];return!!a&&l(a);}return(/input|select|textarea|button|object/.test(d)?!a.disabled:"a"==d?a.href||b:b)&&l(a);}function l(a){return!c(a).parents().andSelf().filter(function(){return c.curCSS(this,"visibility")==="hidden"||c.expr.filters.hidden(this);}).length;}c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.16",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({propAttr:c.fn.prop||c.fn.attr,_focus:c.fn.focus,focus:function focus(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d);},a);}):this._focus.apply(this,arguments);},scrollParent:function scrollParent(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return /(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1));}).eq(0):this.parents().filter(function(){return /(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1));}).eq(0);return /fixed/.test(this.css("position"))||!a.length?c(document):a;},zIndex:function zIndex(a){if(a!==j)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b==="absolute"||b==="relative"||b==="fixed"){b=parseInt(a.css("zIndex"),10);if(!isNaN(b)&&b!==0)return b;}a=a.parent();}}return 0;},disableSelection:function disableSelection(){return this.bind((c.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault();});},enableSelection:function enableSelection(){return this.unbind(".ui-disableSelection");}});c.each(["Width","Height"],function(a,b){function d(f,g,m,n){c.each(e,function(){g-=parseFloat(c.curCSS(f,"padding"+this,true))||0;if(m)g-=parseFloat(c.curCSS(f,"border"+this+"Width",true))||0;if(n)g-=parseFloat(c.curCSS(f,"margin"+this,true))||0;});return g;}var e=b==="Width"?["Left","Right"]:["Top","Bottom"],h=b.toLowerCase(),i={innerWidth:c.fn.innerWidth,innerHeight:c.fn.innerHeight,outerWidth:c.fn.outerWidth,outerHeight:c.fn.outerHeight};c.fn["inner"+b]=function(f){if(f===j)return i["inner"+b].call(this);return this.each(function(){c(this).css(h,d(this,f)+"px");});};c.fn["outer"+b]=function(f,g){if(typeof f!=="number")return i["outer"+b].call(this,f);return this.each(function(){c(this).css(h,d(this,f,true,g)+"px");});};});c.extend(c.expr[":"],{data:function data(a,b,d){return!!c.data(a,d[3]);},focusable:function focusable(a){return k(a,!isNaN(c.attr(a,"tabindex")));},tabbable:function tabbable(a){var b=c.attr(a,"tabindex"),d=isNaN(b);return(d||b>=0)&&k(a,!d);}});c(function(){var a=document.body,b=a.appendChild(b=document.createElement("div"));c.extend(b.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});c.support.minHeight=b.offsetHeight===100;c.support.selectstart="onselectstart"in b;a.removeChild(b).style.display="none";});c.extend(c.ui,{plugin:{add:function add(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]]);}},call:function call(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++){a.options[b[e][0]]&&b[e][1].apply(a.element,d);}}},contains:function contains(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b);},hasScroll:function hasScroll(a,b){if(c(a).css("overflow")==="hidden")return false;b=b&&b==="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d;},isOverAxis:function isOverAxis(a,b,d){return a>b&&a<b+d;},isOver:function isOver(a,b,d,e,h,i){return c.ui.isOverAxis(a,d,h)&&c.ui.isOverAxis(b,e,i);}});}})(jQuery);;/*!
 * jQuery UI Widget 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */(function(b,j){if(b.cleanData){var k=b.cleanData;b.cleanData=function(a){for(var c=0,d;(d=a[c])!=null;c++){try{b(d).triggerHandler("remove");}catch(e){}}k(a);};}else{var l=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add([this]).each(function(){try{b(this).triggerHandler("remove");}catch(d){}});return l.call(b(this),a,c);});};}b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget;}b.expr[":"][f]=function(h){return!!b.data(h,a);};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g);};c=new c();c.options=b.extend(true,{},c.options);b[e][a].prototype=b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a]);};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.charAt(0)==="_")return h;e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==j){h=i;return false;}}):this.each(function(){var g=b.data(this,a);g?g.option(d||{})._init():b.data(this,a,new c(d,this));});return h;};};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c);};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function _createWidget(a,c){b.data(c,this.widgetName,this);this.element=b(c);this.options=b.extend(true,{},this.options,this._getCreateOptions(),a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy();});this._create();this._trigger("create");this._init();},_getCreateOptions:function _getCreateOptions(){return b.metadata&&b.metadata.get(this.element[0])[this.widgetName];},_create:function _create(){},_init:function _init(){},destroy:function destroy(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled");},widget:function widget(){return this.element;},option:function option(a,c){var d=a;if(arguments.length===0)return b.extend({},this.options);if(typeof a==="string"){if(c===j)return this.options[a];d={};d[a]=c;}this._setOptions(d);return this;},_setOptions:function _setOptions(a){var c=this;b.each(a,function(d,e){c._setOption(d,e);});return this;},_setOption:function _setOption(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this;},enable:function enable(){return this._setOption("disabled",false);},disable:function disable(){return this._setOption("disabled",true);},_trigger:function _trigger(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f];}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented());}};})(jQuery);;/*!
 * jQuery UI Mouse 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Mouse
 *
 * Depends:
 *	jquery.ui.widget.js
 */(function(b){var d=false;b(document).mouseup(function(){d=false;});b.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function _mouseInit(){var a=this;this.element.bind("mousedown."+this.widgetName,function(c){return a._mouseDown(c);}).bind("click."+this.widgetName,function(c){if(true===b.data(c.target,a.widgetName+".preventClickEvent")){b.removeData(c.target,a.widgetName+".preventClickEvent");c.stopImmediatePropagation();return false;}});this.started=false;},_mouseDestroy:function _mouseDestroy(){this.element.unbind("."+this.widgetName);},_mouseDown:function _mouseDown(a){if(!d){this._mouseStarted&&this._mouseUp(a);this._mouseDownEvent=a;var c=this,f=a.which==1,g=typeof this.options.cancel=="string"&&a.target.nodeName?b(a.target).closest(this.options.cancel).length:false;if(!f||g||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){c.mouseDelayMet=true;},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted=this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault();return true;}}true===b.data(a.target,this.widgetName+".preventClickEvent")&&b.removeData(a.target,this.widgetName+".preventClickEvent");this._mouseMoveDelegate=function(e){return c._mouseMove(e);};this._mouseUpDelegate=function(e){return c._mouseUp(e);};b(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);a.preventDefault();return d=true;}},_mouseMove:function _mouseMove(a){if(b.browser.msie&&!(document.documentMode>=9)&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);return a.preventDefault();}if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted;},_mouseUp:function _mouseUp(a){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;a.target==this._mouseDownEvent.target&&b.data(a.target,this.widgetName+".preventClickEvent",true);this._mouseStop(a);}return false;},_mouseDistanceMet:function _mouseDistanceMet(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance;},_mouseDelayMet:function _mouseDelayMet(){return this.mouseDelayMet;},_mouseStart:function _mouseStart(){},_mouseDrag:function _mouseDrag(){},_mouseStop:function _mouseStop(){},_mouseCapture:function _mouseCapture(){return true;}});})(jQuery);;/*
 * jQuery UI Position 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Position
 */(function(c){c.ui=c.ui||{};var n=/left|center|right/,o=/top|center|bottom/,t=c.fn.position,u=c.fn.offset;c.fn.position=function(b){if(!b||!b.of)return t.apply(this,arguments);b=c.extend({},b);var a=c(b.of),d=a[0],g=(b.collision||"flip").split(" "),e=b.offset?b.offset.split(" "):[0,0],h,k,j;if(d.nodeType===9){h=a.width();k=a.height();j={top:0,left:0};}else if(d.setTimeout){h=a.width();k=a.height();j={top:a.scrollTop(),left:a.scrollLeft()};}else if(d.preventDefault){b.at="left top";h=k=0;j={top:b.of.pageY,left:b.of.pageX};}else{h=a.outerWidth();k=a.outerHeight();j=a.offset();}c.each(["my","at"],function(){var f=(b[this]||"").split(" ");if(f.length===1)f=n.test(f[0])?f.concat(["center"]):o.test(f[0])?["center"].concat(f):["center","center"];f[0]=n.test(f[0])?f[0]:"center";f[1]=o.test(f[1])?f[1]:"center";b[this]=f;});if(g.length===1)g[1]=g[0];e[0]=parseInt(e[0],10)||0;if(e.length===1)e[1]=e[0];e[1]=parseInt(e[1],10)||0;if(b.at[0]==="right")j.left+=h;else if(b.at[0]==="center")j.left+=h/2;if(b.at[1]==="bottom")j.top+=k;else if(b.at[1]==="center")j.top+=k/2;j.left+=e[0];j.top+=e[1];return this.each(function(){var f=c(this),l=f.outerWidth(),m=f.outerHeight(),p=parseInt(c.curCSS(this,"marginLeft",true))||0,q=parseInt(c.curCSS(this,"marginTop",true))||0,v=l+p+(parseInt(c.curCSS(this,"marginRight",true))||0),w=m+q+(parseInt(c.curCSS(this,"marginBottom",true))||0),i=c.extend({},j),r;if(b.my[0]==="right")i.left-=l;else if(b.my[0]==="center")i.left-=l/2;if(b.my[1]==="bottom")i.top-=m;else if(b.my[1]==="center")i.top-=m/2;i.left=Math.round(i.left);i.top=Math.round(i.top);r={left:i.left-p,top:i.top-q};c.each(["left","top"],function(s,x){c.ui.position[g[s]]&&c.ui.position[g[s]][x](i,{targetWidth:h,targetHeight:k,elemWidth:l,elemHeight:m,collisionPosition:r,collisionWidth:v,collisionHeight:w,offset:e,my:b.my,at:b.at});});c.fn.bgiframe&&f.bgiframe();f.offset(c.extend(i,{using:b.using}));});};c.ui.position={fit:{left:function left(b,a){var d=c(window);d=a.collisionPosition.left+a.collisionWidth-d.width()-d.scrollLeft();b.left=d>0?b.left-d:Math.max(b.left-a.collisionPosition.left,b.left);},top:function top(b,a){var d=c(window);d=a.collisionPosition.top+a.collisionHeight-d.height()-d.scrollTop();b.top=d>0?b.top-d:Math.max(b.top-a.collisionPosition.top,b.top);}},flip:{left:function left(b,a){if(a.at[0]!=="center"){var d=c(window);d=a.collisionPosition.left+a.collisionWidth-d.width()-d.scrollLeft();var g=a.my[0]==="left"?-a.elemWidth:a.my[0]==="right"?a.elemWidth:0,e=a.at[0]==="left"?a.targetWidth:-a.targetWidth,h=-2*a.offset[0];b.left+=a.collisionPosition.left<0?g+e+h:d>0?g+e+h:0;}},top:function top(b,a){if(a.at[1]!=="center"){var d=c(window);d=a.collisionPosition.top+a.collisionHeight-d.height()-d.scrollTop();var g=a.my[1]==="top"?-a.elemHeight:a.my[1]==="bottom"?a.elemHeight:0,e=a.at[1]==="top"?a.targetHeight:-a.targetHeight,h=-2*a.offset[1];b.top+=a.collisionPosition.top<0?g+e+h:d>0?g+e+h:0;}}}};if(!c.offset.setOffset){c.offset.setOffset=function(b,a){if(/static/.test(c.curCSS(b,"position")))b.style.position="relative";var d=c(b),g=d.offset(),e=parseInt(c.curCSS(b,"top",true),10)||0,h=parseInt(c.curCSS(b,"left",true),10)||0;g={top:a.top-g.top+e,left:a.left-g.left+h};"using"in a?a.using.call(b,g):d.css(g);};c.fn.offset=function(b){var a=this[0];if(!a||!a.ownerDocument)return null;if(b)return this.each(function(){c.offset.setOffset(this,b);});return u.call(this);};}})(jQuery);;/*
 * jQuery UI Draggable 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */(function(d){d.widget("ui.draggable",d.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function _create(){if(this.options.helper=="original"&&!/^(?:r|a|f)/.test(this.element.css("position")))this.element[0].style.position="relative";this.options.addClasses&&this.element.addClass("ui-draggable");this.options.disabled&&this.element.addClass("ui-draggable-disabled");this._mouseInit();},destroy:function destroy(){if(this.element.data("draggable")){this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();return this;}},_mouseCapture:function _mouseCapture(a){var b=this.options;if(this.helper||b.disabled||d(a.target).is(".ui-resizable-handle"))return false;this.handle=this._getHandle(a);if(!this.handle)return false;if(b.iframeFix)d(b.iframeFix===true?"iframe":b.iframeFix).each(function(){d('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1E3}).css(d(this).offset()).appendTo("body");});return true;},_mouseStart:function _mouseStart(a){var b=this.options;this.helper=this._createHelper(a);this._cacheHelperProportions();if(d.ui.ddmanager)d.ui.ddmanager.current=this;this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);b.containment&&this._setContainment();if(this._trigger("start",a)===false){this._clear();return false;}this._cacheHelperProportions();d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(a,true);d.ui.ddmanager&&d.ui.ddmanager.dragStart(this,a);return true;},_mouseDrag:function _mouseDrag(a,b){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");if(!b){b=this._uiHash();if(this._trigger("drag",a,b)===false){this._mouseUp({});return false;}this.position=b.position;}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);return false;},_mouseStop:function _mouseStop(a){var b=false;if(d.ui.ddmanager&&!this.options.dropBehaviour)b=d.ui.ddmanager.drop(this,a);if(this.dropped){b=this.dropped;this.dropped=false;}if((!this.element[0]||!this.element[0].parentNode)&&this.options.helper=="original")return false;if(this.options.revert=="invalid"&&!b||this.options.revert=="valid"&&b||this.options.revert===true||d.isFunction(this.options.revert)&&this.options.revert.call(this.element,b)){var c=this;d(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){c._trigger("stop",a)!==false&&c._clear();});}else this._trigger("stop",a)!==false&&this._clear();return false;},_mouseUp:function _mouseUp(a){this.options.iframeFix===true&&d("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this);});d.ui.ddmanager&&d.ui.ddmanager.dragStop(this,a);return d.ui.mouse.prototype._mouseUp.call(this,a);},cancel:function cancel(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this;},_getHandle:function _getHandle(a){var b=!this.options.handle||!d(this.options.handle,this.element).length?true:false;d(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==a.target)b=true;});return b;},_createHelper:function _createHelper(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a])):b.helper=="clone"?this.element.clone().removeAttr("id"):this.element;a.parents("body").length||a.appendTo(b.appendTo=="parent"?this.element[0].parentNode:b.appendTo);a[0]!=this.element[0]&&!/(fixed|absolute)/.test(a.css("position"))&&a.css("position","absolute");return a;},_adjustOffsetFromHelper:function _adjustOffsetFromHelper(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0],top:+a[1]||0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top;},_getParentOffset:function _getParentOffset(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop();}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)};},_getRelativeOffset:function _getRelativeOffset(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()};}else return{top:0,left:0};},_cacheMargins:function _cacheMargins(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0};},_cacheHelperProportions:function _cacheHelperProportions(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};},_setContainment:function _setContainment(){var a=this.options;if(a.containment=="parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[a.containment=="document"?0:d(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,a.containment=="document"?0:d(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(a.containment=="document"?0:d(window).scrollLeft())+d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a.containment=="document"?0:d(window).scrollTop())+(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)&&a.containment.constructor!=Array){a=d(a.containment);var b=a[0];if(b){a.offset();var c=d(b).css("overflow")!="hidden";this.containment=[(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0),(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0),(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom];this.relative_container=a;}}else if(a.containment.constructor==Array)this.containment=a.containment;},_convertPositionTo:function _convertPositionTo(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName);return{top:b.top+this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():f?0:c.scrollLeft())*a)};},_generatePosition:function _generatePosition(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName),e=a.pageX,h=a.pageY;if(this.originalPosition){var g;if(this.containment){if(this.relative_container){g=this.relative_container.offset();g=[this.containment[0]+g.left,this.containment[1]+g.top,this.containment[2]+g.left,this.containment[3]+g.top];}else g=this.containment;if(a.pageX-this.offset.click.left<g[0])e=g[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<g[1])h=g[1]+this.offset.click.top;if(a.pageX-this.offset.click.left>g[2])e=g[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>g[3])h=g[3]+this.offset.click.top;}if(b.grid){h=b.grid[1]?this.originalPageY+Math.round((h-this.originalPageY)/b.grid[1])*b.grid[1]:this.originalPageY;h=g?!(h-this.offset.click.top<g[1]||h-this.offset.click.top>g[3])?h:!(h-this.offset.click.top<g[1])?h-b.grid[1]:h+b.grid[1]:h;e=b.grid[0]?this.originalPageX+Math.round((e-this.originalPageX)/b.grid[0])*b.grid[0]:this.originalPageX;e=g?!(e-this.offset.click.left<g[0]||e-this.offset.click.left>g[2])?e:!(e-this.offset.click.left<g[0])?e-b.grid[0]:e+b.grid[0]:e;}}return{top:h-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop()),left:e-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():f?0:c.scrollLeft())};},_clear:function _clear(){this.helper.removeClass("ui-draggable-dragging");this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove();this.helper=null;this.cancelHelperRemoval=false;},_trigger:function _trigger(a,b,c){c=c||this._uiHash();d.ui.plugin.call(this,a,[b,c]);if(a=="drag")this.positionAbs=this._convertPositionTo("absolute");return d.Widget.prototype._trigger.call(this,a,b,c);},plugins:{},_uiHash:function _uiHash(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs};}});d.extend(d.ui.draggable,{version:"1.8.16"});d.ui.plugin.add("draggable","connectToSortable",{start:function start(a,b){var c=d(this).data("draggable"),f=c.options,e=d.extend({},b,{item:c.element});c.sortables=[];d(f.connectToSortable).each(function(){var h=d.data(this,"sortable");if(h&&!h.options.disabled){c.sortables.push({instance:h,shouldRevert:h.options.revert});h.refreshPositions();h._trigger("activate",a,e);}});},stop:function stop(a,b){var c=d(this).data("draggable"),f=d.extend({},b,{item:c.element});d.each(c.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;c.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert)this.instance.options.revert=true;this.instance._mouseStop(a);this.instance.options.helper=this.instance.options._helper;c.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"});}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",a,f);}});},drag:function drag(a,b){var c=d(this).data("draggable"),f=this;d.each(c.sortables,function(){this.instance.positionAbs=c.positionAbs;this.instance.helperProportions=c.helperProportions;this.instance.offset.click=c.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=d(f).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return b.helper[0];};a.target=this.instance.currentItem[0];this.instance._mouseCapture(a,true);this.instance._mouseStart(a,true,true);this.instance.offset.click.top=c.offset.click.top;this.instance.offset.click.left=c.offset.click.left;this.instance.offset.parent.left-=c.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=c.offset.parent.top-this.instance.offset.parent.top;c._trigger("toSortable",a);c.dropped=this.instance.element;c.currentItem=c.element;this.instance.fromOutside=c;}this.instance.currentItem&&this.instance._mouseDrag(a);}else if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",a,this.instance._uiHash(this.instance));this.instance._mouseStop(a,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();this.instance.placeholder&&this.instance.placeholder.remove();c._trigger("fromSortable",a);c.dropped=false;}});}});d.ui.plugin.add("draggable","cursor",{start:function start(){var a=d("body"),b=d(this).data("draggable").options;if(a.css("cursor"))b._cursor=a.css("cursor");a.css("cursor",b.cursor);},stop:function stop(){var a=d(this).data("draggable").options;a._cursor&&d("body").css("cursor",a._cursor);}});d.ui.plugin.add("draggable","opacity",{start:function start(a,b){a=d(b.helper);b=d(this).data("draggable").options;if(a.css("opacity"))b._opacity=a.css("opacity");a.css("opacity",b.opacity);},stop:function stop(a,b){a=d(this).data("draggable").options;a._opacity&&d(b.helper).css("opacity",a._opacity);}});d.ui.plugin.add("draggable","scroll",{start:function start(){var a=d(this).data("draggable");if(a.scrollParent[0]!=document&&a.scrollParent[0].tagName!="HTML")a.overflowOffset=a.scrollParent.offset();},drag:function drag(a){var b=d(this).data("draggable"),c=b.options,f=false;if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!="HTML"){if(!c.axis||c.axis!="x")if(b.overflowOffset.top+b.scrollParent[0].offsetHeight-a.pageY<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop+c.scrollSpeed;else if(a.pageY-b.overflowOffset.top<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop-c.scrollSpeed;if(!c.axis||c.axis!="y")if(b.overflowOffset.left+b.scrollParent[0].offsetWidth-a.pageX<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft+c.scrollSpeed;else if(a.pageX-b.overflowOffset.left<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft-c.scrollSpeed;}else{if(!c.axis||c.axis!="x")if(a.pageY-d(document).scrollTop()<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()-c.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()+c.scrollSpeed);if(!c.axis||c.axis!="y")if(a.pageX-d(document).scrollLeft()<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()-c.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()+c.scrollSpeed);}f!==false&&d.ui.ddmanager&&!c.dropBehaviour&&d.ui.ddmanager.prepareOffsets(b,a);}});d.ui.plugin.add("draggable","snap",{start:function start(){var a=d(this).data("draggable"),b=a.options;a.snapElements=[];d(b.snap.constructor!=String?b.snap.items||":data(draggable)":b.snap).each(function(){var c=d(this),f=c.offset();this!=a.element[0]&&a.snapElements.push({item:this,width:c.outerWidth(),height:c.outerHeight(),top:f.top,left:f.left});});},drag:function drag(a,b){for(var c=d(this).data("draggable"),f=c.options,e=f.snapTolerance,h=b.offset.left,g=h+c.helperProportions.width,n=b.offset.top,o=n+c.helperProportions.height,i=c.snapElements.length-1;i>=0;i--){var j=c.snapElements[i].left,l=j+c.snapElements[i].width,k=c.snapElements[i].top,m=k+c.snapElements[i].height;if(j-e<h&&h<l+e&&k-e<n&&n<m+e||j-e<h&&h<l+e&&k-e<o&&o<m+e||j-e<g&&g<l+e&&k-e<n&&n<m+e||j-e<g&&g<l+e&&k-e<o&&o<m+e){if(f.snapMode!="inner"){var p=Math.abs(k-o)<=e,q=Math.abs(m-n)<=e,r=Math.abs(j-g)<=e,s=Math.abs(l-h)<=e;if(p)b.position.top=c._convertPositionTo("relative",{top:k-c.helperProportions.height,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:m,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:j-c.helperProportions.width}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:l}).left-c.margins.left;}var t=p||q||r||s;if(f.snapMode!="outer"){p=Math.abs(k-n)<=e;q=Math.abs(m-o)<=e;r=Math.abs(j-h)<=e;s=Math.abs(l-g)<=e;if(p)b.position.top=c._convertPositionTo("relative",{top:k,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:m-c.helperProportions.height,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:j}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:l-c.helperProportions.width}).left-c.margins.left;}if(!c.snapElements[i].snapping&&(p||q||r||s||t))c.options.snap.snap&&c.options.snap.snap.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[i].item}));c.snapElements[i].snapping=p||q||r||s||t;}else{c.snapElements[i].snapping&&c.options.snap.release&&c.options.snap.release.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[i].item}));c.snapElements[i].snapping=false;}}}});d.ui.plugin.add("draggable","stack",{start:function start(){var a=d(this).data("draggable").options;a=d.makeArray(d(a.stack)).sort(function(c,f){return(parseInt(d(c).css("zIndex"),10)||0)-(parseInt(d(f).css("zIndex"),10)||0);});if(a.length){var b=parseInt(a[0].style.zIndex)||0;d(a).each(function(c){this.style.zIndex=b+c;});this[0].style.zIndex=b+a.length;}}});d.ui.plugin.add("draggable","zIndex",{start:function start(a,b){a=d(b.helper);b=d(this).data("draggable").options;if(a.css("zIndex"))b._zIndex=a.css("zIndex");a.css("zIndex",b.zIndex);},stop:function stop(a,b){a=d(this).data("draggable").options;a._zIndex&&d(b.helper).css("zIndex",a._zIndex);}});})(jQuery);;/*
 * jQuery UI Droppable 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Droppables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.mouse.js
 *	jquery.ui.draggable.js
 */(function(d){d.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"},_create:function _create(){var a=this.options,b=a.accept;this.isover=0;this.isout=1;this.accept=d.isFunction(b)?b:function(c){return c.is(b);};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};d.ui.ddmanager.droppables[a.scope]=d.ui.ddmanager.droppables[a.scope]||[];d.ui.ddmanager.droppables[a.scope].push(this);a.addClasses&&this.element.addClass("ui-droppable");},destroy:function destroy(){for(var a=d.ui.ddmanager.droppables[this.options.scope],b=0;b<a.length;b++){a[b]==this&&a.splice(b,1);}this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");return this;},_setOption:function _setOption(a,b){if(a=="accept")this.accept=d.isFunction(b)?b:function(c){return c.is(b);};d.Widget.prototype._setOption.apply(this,arguments);},_activate:function _activate(a){var b=d.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass);b&&this._trigger("activate",a,this.ui(b));},_deactivate:function _deactivate(a){var b=d.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass);b&&this._trigger("deactivate",a,this.ui(b));},_over:function _over(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.addClass(this.options.hoverClass);this._trigger("over",a,this.ui(b));}},_out:function _out(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);this._trigger("out",a,this.ui(b));}},_drop:function _drop(a,b){var c=b||d.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0])return false;var e=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var g=d.data(this,"droppable");if(g.options.greedy&&!g.options.disabled&&g.options.scope==c.options.scope&&g.accept.call(g.element[0],c.currentItem||c.element)&&d.ui.intersect(c,d.extend(g,{offset:g.element.offset()}),g.options.tolerance)){e=true;return false;}});if(e)return false;if(this.accept.call(this.element[0],c.currentItem||c.element)){this.options.activeClass&&this.element.removeClass(this.options.activeClass);this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);this._trigger("drop",a,this.ui(c));return this.element;}return false;},ui:function ui(a){return{draggable:a.currentItem||a.element,helper:a.helper,position:a.position,offset:a.positionAbs};}});d.extend(d.ui.droppable,{version:"1.8.16"});d.ui.intersect=function(a,b,c){if(!b.offset)return false;var e=(a.positionAbs||a.position.absolute).left,g=e+a.helperProportions.width,f=(a.positionAbs||a.position.absolute).top,h=f+a.helperProportions.height,i=b.offset.left,k=i+b.proportions.width,j=b.offset.top,l=j+b.proportions.height;switch(c){case"fit":return i<=e&&g<=k&&j<=f&&h<=l;case"intersect":return i<e+a.helperProportions.width/2&&g-a.helperProportions.width/2<k&&j<f+a.helperProportions.height/2&&h-a.helperProportions.height/2<l;case"pointer":return d.ui.isOver((a.positionAbs||a.position.absolute).top+(a.clickOffset||a.offset.click).top,(a.positionAbs||a.position.absolute).left+(a.clickOffset||a.offset.click).left,j,i,b.proportions.height,b.proportions.width);case"touch":return(f>=j&&f<=l||h>=j&&h<=l||f<j&&h>l)&&(e>=i&&e<=k||g>=i&&g<=k||e<i&&g>k);default:return false;}};d.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function prepareOffsets(a,b){var c=d.ui.ddmanager.droppables[a.options.scope]||[],e=b?b.type:null,g=(a.currentItem||a.element).find(":data(droppable)").andSelf(),f=0;a:for(;f<c.length;f++){if(!(c[f].options.disabled||a&&!c[f].accept.call(c[f].element[0],a.currentItem||a.element))){for(var h=0;h<g.length;h++){if(g[h]==c[f].element[0]){c[f].proportions.height=0;continue a;}}c[f].visible=c[f].element.css("display")!="none";if(c[f].visible){e=="mousedown"&&c[f]._activate.call(c[f],b);c[f].offset=c[f].element.offset();c[f].proportions={width:c[f].element[0].offsetWidth,height:c[f].element[0].offsetHeight};}}}},drop:function drop(a,b){var c=false;d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(this.options){if(!this.options.disabled&&this.visible&&d.ui.intersect(a,this,this.options.tolerance))c=c||this._drop.call(this,b);if(!this.options.disabled&&this.visible&&this.accept.call(this.element[0],a.currentItem||a.element)){this.isout=1;this.isover=0;this._deactivate.call(this,b);}}});return c;},dragStart:function dragStart(a,b){a.element.parents(":not(body,html)").bind("scroll.droppable",function(){a.options.refreshPositions||d.ui.ddmanager.prepareOffsets(a,b);});},drag:function drag(a,b){a.options.refreshPositions&&d.ui.ddmanager.prepareOffsets(a,b);d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(!(this.options.disabled||this.greedyChild||!this.visible)){var c=d.ui.intersect(a,this,this.options.tolerance);if(c=!c&&this.isover==1?"isout":c&&this.isover==0?"isover":null){var e;if(this.options.greedy){var g=this.element.parents(":data(droppable):eq(0)");if(g.length){e=d.data(g[0],"droppable");e.greedyChild=c=="isover"?1:0;}}if(e&&c=="isover"){e.isover=0;e.isout=1;e._out.call(e,b);}this[c]=1;this[c=="isout"?"isover":"isout"]=0;this[c=="isover"?"_over":"_out"].call(this,b);if(e&&c=="isout"){e.isout=0;e.isover=1;e._over.call(e,b);}}}});},dragStop:function dragStop(a,b){a.element.parents(":not(body,html)").unbind("scroll.droppable");a.options.refreshPositions||d.ui.ddmanager.prepareOffsets(a,b);}};})(jQuery);;/*
 * jQuery UI Resizable 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Resizables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */(function(e){e.widget("ui.resizable",e.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,containment:false,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1E3},_create:function _create(){var b=this,a=this.options;this.element.addClass("ui-resizable");e.extend(this,{_aspectRatio:!!a.aspectRatio,aspectRatio:a.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:a.helper||a.ghost||a.animate?a.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)){/relative/.test(this.element.css("position"))&&e.browser.opera&&this.element.css({position:"relative",top:"auto",left:"auto"});this.element.wrap(e('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("resizable",this.element.data("resizable"));this.elementIsWrapper=true;this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")});this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});this.originalResizeStyle=this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css({margin:this.originalElement.css("margin")});this._proportionallyResize();}this.handles=a.handles||(!e(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"});if(this.handles.constructor==String){if(this.handles=="all")this.handles="n,e,s,w,se,sw,ne,nw";var c=this.handles.split(",");this.handles={};for(var d=0;d<c.length;d++){var f=e.trim(c[d]),g=e('<div class="ui-resizable-handle '+("ui-resizable-"+f)+'"></div>');/sw|se|ne|nw/.test(f)&&g.css({zIndex:++a.zIndex});"se"==f&&g.addClass("ui-icon ui-icon-gripsmall-diagonal-se");this.handles[f]=".ui-resizable-"+f;this.element.append(g);}}this._renderAxis=function(h){h=h||this.element;for(var i in this.handles){if(this.handles[i].constructor==String)this.handles[i]=e(this.handles[i],this.element).show();if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var j=e(this.handles[i],this.element),l=0;l=/sw|ne|nw|se|n|s/.test(i)?j.outerHeight():j.outerWidth();j=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join("");h.css(j,l);this._proportionallyResize();}e(this.handles[i]);}};this._renderAxis(this.element);this._handles=e(".ui-resizable-handle",this.element).disableSelection();this._handles.mouseover(function(){if(!b.resizing){if(this.className)var h=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);b.axis=h&&h[1]?h[1]:"se";}});if(a.autoHide){this._handles.hide();e(this.element).addClass("ui-resizable-autohide").hover(function(){if(!a.disabled){e(this).removeClass("ui-resizable-autohide");b._handles.show();}},function(){if(!a.disabled)if(!b.resizing){e(this).addClass("ui-resizable-autohide");b._handles.hide();}});}this._mouseInit();},destroy:function destroy(){this._mouseDestroy();var b=function b(c){e(c).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove();};if(this.elementIsWrapper){b(this.element);var a=this.element;a.after(this.originalElement.css({position:a.css("position"),width:a.outerWidth(),height:a.outerHeight(),top:a.css("top"),left:a.css("left")})).remove();}this.originalElement.css("resize",this.originalResizeStyle);b(this.originalElement);return this;},_mouseCapture:function _mouseCapture(b){var a=false;for(var c in this.handles){if(e(this.handles[c])[0]==b.target)a=true;}return!this.options.disabled&&a;},_mouseStart:function _mouseStart(b){var a=this.options,c=this.element.position(),d=this.element;this.resizing=true;this.documentScroll={top:e(document).scrollTop(),left:e(document).scrollLeft()};if(d.is(".ui-draggable")||/absolute/.test(d.css("position")))d.css({position:"absolute",top:c.top,left:c.left});e.browser.opera&&/relative/.test(d.css("position"))&&d.css({position:"relative",top:"auto",left:"auto"});this._renderProxy();c=m(this.helper.css("left"));var f=m(this.helper.css("top"));if(a.containment){c+=e(a.containment).scrollLeft()||0;f+=e(a.containment).scrollTop()||0;}this.offset=this.helper.offset();this.position={left:c,top:f};this.size=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalSize=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalPosition={left:c,top:f};this.sizeDiff={width:d.outerWidth()-d.width(),height:d.outerHeight()-d.height()};this.originalMousePosition={left:b.pageX,top:b.pageY};this.aspectRatio=typeof a.aspectRatio=="number"?a.aspectRatio:this.originalSize.width/this.originalSize.height||1;a=e(".ui-resizable-"+this.axis).css("cursor");e("body").css("cursor",a=="auto"?this.axis+"-resize":a);d.addClass("ui-resizable-resizing");this._propagate("start",b);return true;},_mouseDrag:function _mouseDrag(b){var a=this.helper,c=this.originalMousePosition,d=this._change[this.axis];if(!d)return false;c=d.apply(this,[b,b.pageX-c.left||0,b.pageY-c.top||0]);this._updateVirtualBoundaries(b.shiftKey);if(this._aspectRatio||b.shiftKey)c=this._updateRatio(c,b);c=this._respectSize(c,b);this._propagate("resize",b);a.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize();this._updateCache(c);this._trigger("resize",b,this.ui());return false;},_mouseStop:function _mouseStop(b){this.resizing=false;var a=this.options,c=this;if(this._helper){var d=this._proportionallyResizeElements,f=d.length&&/textarea/i.test(d[0].nodeName);d=f&&e.ui.hasScroll(d[0],"left")?0:c.sizeDiff.height;f=f?0:c.sizeDiff.width;f={width:c.helper.width()-f,height:c.helper.height()-d};d=parseInt(c.element.css("left"),10)+(c.position.left-c.originalPosition.left)||null;var g=parseInt(c.element.css("top"),10)+(c.position.top-c.originalPosition.top)||null;a.animate||this.element.css(e.extend(f,{top:g,left:d}));c.helper.height(c.size.height);c.helper.width(c.size.width);this._helper&&!a.animate&&this._proportionallyResize();}e("body").css("cursor","auto");this.element.removeClass("ui-resizable-resizing");this._propagate("stop",b);this._helper&&this.helper.remove();return false;},_updateVirtualBoundaries:function _updateVirtualBoundaries(b){var a=this.options,c,d,f;a={minWidth:k(a.minWidth)?a.minWidth:0,maxWidth:k(a.maxWidth)?a.maxWidth:Infinity,minHeight:k(a.minHeight)?a.minHeight:0,maxHeight:k(a.maxHeight)?a.maxHeight:Infinity};if(this._aspectRatio||b){b=a.minHeight*this.aspectRatio;d=a.minWidth/this.aspectRatio;c=a.maxHeight*this.aspectRatio;f=a.maxWidth/this.aspectRatio;if(b>a.minWidth)a.minWidth=b;if(d>a.minHeight)a.minHeight=d;if(c<a.maxWidth)a.maxWidth=c;if(f<a.maxHeight)a.maxHeight=f;}this._vBoundaries=a;},_updateCache:function _updateCache(b){this.offset=this.helper.offset();if(k(b.left))this.position.left=b.left;if(k(b.top))this.position.top=b.top;if(k(b.height))this.size.height=b.height;if(k(b.width))this.size.width=b.width;},_updateRatio:function _updateRatio(b){var a=this.position,c=this.size,d=this.axis;if(k(b.height))b.width=b.height*this.aspectRatio;else if(k(b.width))b.height=b.width/this.aspectRatio;if(d=="sw"){b.left=a.left+(c.width-b.width);b.top=null;}if(d=="nw"){b.top=a.top+(c.height-b.height);b.left=a.left+(c.width-b.width);}return b;},_respectSize:function _respectSize(b){var a=this._vBoundaries,c=this.axis,d=k(b.width)&&a.maxWidth&&a.maxWidth<b.width,f=k(b.height)&&a.maxHeight&&a.maxHeight<b.height,g=k(b.width)&&a.minWidth&&a.minWidth>b.width,h=k(b.height)&&a.minHeight&&a.minHeight>b.height;if(g)b.width=a.minWidth;if(h)b.height=a.minHeight;if(d)b.width=a.maxWidth;if(f)b.height=a.maxHeight;var i=this.originalPosition.left+this.originalSize.width,j=this.position.top+this.size.height,l=/sw|nw|w/.test(c);c=/nw|ne|n/.test(c);if(g&&l)b.left=i-a.minWidth;if(d&&l)b.left=i-a.maxWidth;if(h&&c)b.top=j-a.minHeight;if(f&&c)b.top=j-a.maxHeight;if((a=!b.width&&!b.height)&&!b.left&&b.top)b.top=null;else if(a&&!b.top&&b.left)b.left=null;return b;},_proportionallyResize:function _proportionallyResize(){if(this._proportionallyResizeElements.length)for(var b=this.helper||this.element,a=0;a<this._proportionallyResizeElements.length;a++){var c=this._proportionallyResizeElements[a];if(!this.borderDif){var d=[c.css("borderTopWidth"),c.css("borderRightWidth"),c.css("borderBottomWidth"),c.css("borderLeftWidth")],f=[c.css("paddingTop"),c.css("paddingRight"),c.css("paddingBottom"),c.css("paddingLeft")];this.borderDif=e.map(d,function(g,h){g=parseInt(g,10)||0;h=parseInt(f[h],10)||0;return g+h;});}e.browser.msie&&(e(b).is(":hidden")||e(b).parents(":hidden").length)||c.css({height:b.height()-this.borderDif[0]-this.borderDif[2]||0,width:b.width()-this.borderDif[1]-this.borderDif[3]||0});}},_renderProxy:function _renderProxy(){var b=this.options;this.elementOffset=this.element.offset();if(this._helper){this.helper=this.helper||e('<div style="overflow:hidden;"></div>');var a=e.browser.msie&&e.browser.version<7,c=a?1:0;a=a?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+a,height:this.element.outerHeight()+a,position:"absolute",left:this.elementOffset.left-c+"px",top:this.elementOffset.top-c+"px",zIndex:++b.zIndex});this.helper.appendTo("body").disableSelection();}else this.helper=this.element;},_change:{e:function e(b,a){return{width:this.originalSize.width+a};},w:function w(b,a){return{left:this.originalPosition.left+a,width:this.originalSize.width-a};},n:function n(b,a,c){return{top:this.originalPosition.top+c,height:this.originalSize.height-c};},s:function s(b,a,c){return{height:this.originalSize.height+c};},se:function se(b,a,c){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[b,a,c]));},sw:function sw(b,a,c){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[b,a,c]));},ne:function ne(b,a,c){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[b,a,c]));},nw:function nw(b,a,c){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[b,a,c]));}},_propagate:function _propagate(b,a){e.ui.plugin.call(this,b,[a,this.ui()]);b!="resize"&&this._trigger(b,a,this.ui());},plugins:{},ui:function ui(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition};}});e.extend(e.ui.resizable,{version:"1.8.16"});e.ui.plugin.add("resizable","alsoResize",{start:function start(){var b=e(this).data("resizable").options,a=function a(c){e(c).each(function(){var d=e(this);d.data("resizable-alsoresize",{width:parseInt(d.width(),10),height:parseInt(d.height(),10),left:parseInt(d.css("left"),10),top:parseInt(d.css("top"),10),position:d.css("position")});});};if(_typeof(b.alsoResize)=="object"&&!b.alsoResize.parentNode){if(b.alsoResize.length){b.alsoResize=b.alsoResize[0];a(b.alsoResize);}else e.each(b.alsoResize,function(c){a(c);});}else a(b.alsoResize);},resize:function resize(b,a){var c=e(this).data("resizable");b=c.options;var d=c.originalSize,f=c.originalPosition,g={height:c.size.height-d.height||0,width:c.size.width-d.width||0,top:c.position.top-f.top||0,left:c.position.left-f.left||0},h=function h(i,j){e(i).each(function(){var l=e(this),q=e(this).data("resizable-alsoresize"),p={},r=j&&j.length?j:l.parents(a.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(r,function(n,o){if((n=(q[o]||0)+(g[o]||0))&&n>=0)p[o]=n||null;});if(e.browser.opera&&/relative/.test(l.css("position"))){c._revertToRelativePosition=true;l.css({position:"absolute",top:"auto",left:"auto"});}l.css(p);});};_typeof(b.alsoResize)=="object"&&!b.alsoResize.nodeType?e.each(b.alsoResize,function(i,j){h(i,j);}):h(b.alsoResize);},stop:function stop(){var b=e(this).data("resizable"),a=b.options,c=function c(d){e(d).each(function(){var f=e(this);f.css({position:f.data("resizable-alsoresize").position});});};if(b._revertToRelativePosition){b._revertToRelativePosition=false;_typeof(a.alsoResize)=="object"&&!a.alsoResize.nodeType?e.each(a.alsoResize,function(d){c(d);}):c(a.alsoResize);}e(this).removeData("resizable-alsoresize");}});e.ui.plugin.add("resizable","animate",{stop:function stop(b){var a=e(this).data("resizable"),c=a.options,d=a._proportionallyResizeElements,f=d.length&&/textarea/i.test(d[0].nodeName),g=f&&e.ui.hasScroll(d[0],"left")?0:a.sizeDiff.height;f={width:a.size.width-(f?0:a.sizeDiff.width),height:a.size.height-g};g=parseInt(a.element.css("left"),10)+(a.position.left-a.originalPosition.left)||null;var h=parseInt(a.element.css("top"),10)+(a.position.top-a.originalPosition.top)||null;a.element.animate(e.extend(f,h&&g?{top:h,left:g}:{}),{duration:c.animateDuration,easing:c.animateEasing,step:function step(){var i={width:parseInt(a.element.css("width"),10),height:parseInt(a.element.css("height"),10),top:parseInt(a.element.css("top"),10),left:parseInt(a.element.css("left"),10)};d&&d.length&&e(d[0]).css({width:i.width,height:i.height});a._updateCache(i);a._propagate("resize",b);}});}});e.ui.plugin.add("resizable","containment",{start:function start(){var b=e(this).data("resizable"),a=b.element,c=b.options.containment;if(a=c instanceof e?c.get(0):/parent/.test(c)?a.parent().get(0):c){b.containerElement=e(a);if(/document/.test(c)||c==document){b.containerOffset={left:0,top:0};b.containerPosition={left:0,top:0};b.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight};}else{var d=e(a),f=[];e(["Top","Right","Left","Bottom"]).each(function(i,j){f[i]=m(d.css("padding"+j));});b.containerOffset=d.offset();b.containerPosition=d.position();b.containerSize={height:d.innerHeight()-f[3],width:d.innerWidth()-f[1]};c=b.containerOffset;var g=b.containerSize.height,h=b.containerSize.width;h=e.ui.hasScroll(a,"left")?a.scrollWidth:h;g=e.ui.hasScroll(a)?a.scrollHeight:g;b.parentData={element:a,left:c.left,top:c.top,width:h,height:g};}}},resize:function resize(b){var a=e(this).data("resizable"),c=a.options,d=a.containerOffset,f=a.position;b=a._aspectRatio||b.shiftKey;var g={top:0,left:0},h=a.containerElement;if(h[0]!=document&&/static/.test(h.css("position")))g=d;if(f.left<(a._helper?d.left:0)){a.size.width+=a._helper?a.position.left-d.left:a.position.left-g.left;if(b)a.size.height=a.size.width/c.aspectRatio;a.position.left=c.helper?d.left:0;}if(f.top<(a._helper?d.top:0)){a.size.height+=a._helper?a.position.top-d.top:a.position.top;if(b)a.size.width=a.size.height*c.aspectRatio;a.position.top=a._helper?d.top:0;}a.offset.left=a.parentData.left+a.position.left;a.offset.top=a.parentData.top+a.position.top;c=Math.abs((a._helper?a.offset.left-g.left:a.offset.left-g.left)+a.sizeDiff.width);d=Math.abs((a._helper?a.offset.top-g.top:a.offset.top-d.top)+a.sizeDiff.height);f=a.containerElement.get(0)==a.element.parent().get(0);g=/relative|absolute/.test(a.containerElement.css("position"));if(f&&g)c-=a.parentData.left;if(c+a.size.width>=a.parentData.width){a.size.width=a.parentData.width-c;if(b)a.size.height=a.size.width/a.aspectRatio;}if(d+a.size.height>=a.parentData.height){a.size.height=a.parentData.height-d;if(b)a.size.width=a.size.height*a.aspectRatio;}},stop:function stop(){var b=e(this).data("resizable"),a=b.options,c=b.containerOffset,d=b.containerPosition,f=b.containerElement,g=e(b.helper),h=g.offset(),i=g.outerWidth()-b.sizeDiff.width;g=g.outerHeight()-b.sizeDiff.height;b._helper&&!a.animate&&/relative/.test(f.css("position"))&&e(this).css({left:h.left-d.left-c.left,width:i,height:g});b._helper&&!a.animate&&/static/.test(f.css("position"))&&e(this).css({left:h.left-d.left-c.left,width:i,height:g});}});e.ui.plugin.add("resizable","ghost",{start:function start(){var b=e(this).data("resizable"),a=b.options,c=b.size;b.ghost=b.originalElement.clone();b.ghost.css({opacity:0.25,display:"block",position:"relative",height:c.height,width:c.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof a.ghost=="string"?a.ghost:"");b.ghost.appendTo(b.helper);},resize:function resize(){var b=e(this).data("resizable");b.ghost&&b.ghost.css({position:"relative",height:b.size.height,width:b.size.width});},stop:function stop(){var b=e(this).data("resizable");b.ghost&&b.helper&&b.helper.get(0).removeChild(b.ghost.get(0));}});e.ui.plugin.add("resizable","grid",{resize:function resize(){var b=e(this).data("resizable"),a=b.options,c=b.size,d=b.originalSize,f=b.originalPosition,g=b.axis;a.grid=typeof a.grid=="number"?[a.grid,a.grid]:a.grid;var h=Math.round((c.width-d.width)/(a.grid[0]||1))*(a.grid[0]||1);a=Math.round((c.height-d.height)/(a.grid[1]||1))*(a.grid[1]||1);if(/^(se|s|e)$/.test(g)){b.size.width=d.width+h;b.size.height=d.height+a;}else if(/^(ne)$/.test(g)){b.size.width=d.width+h;b.size.height=d.height+a;b.position.top=f.top-a;}else{if(/^(sw)$/.test(g)){b.size.width=d.width+h;b.size.height=d.height+a;}else{b.size.width=d.width+h;b.size.height=d.height+a;b.position.top=f.top-a;}b.position.left=f.left-h;}}});var m=function m(b){return parseInt(b,10)||0;},k=function k(b){return!isNaN(parseInt(b,10));};})(jQuery);;/*
 * jQuery UI Selectable 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Selectables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */(function(e){e.widget("ui.selectable",e.ui.mouse,{options:{appendTo:"body",autoRefresh:true,distance:0,filter:"*",tolerance:"touch"},_create:function _create(){var c=this;this.element.addClass("ui-selectable");this.dragged=false;var f;this.refresh=function(){f=e(c.options.filter,c.element[0]);f.each(function(){var d=e(this),b=d.offset();e.data(this,"selectable-item",{element:this,$element:d,left:b.left,top:b.top,right:b.left+d.outerWidth(),bottom:b.top+d.outerHeight(),startselected:false,selected:d.hasClass("ui-selected"),selecting:d.hasClass("ui-selecting"),unselecting:d.hasClass("ui-unselecting")});});};this.refresh();this.selectees=f.addClass("ui-selectee");this._mouseInit();this.helper=e("<div class='ui-selectable-helper'></div>");},destroy:function destroy(){this.selectees.removeClass("ui-selectee").removeData("selectable-item");this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable");this._mouseDestroy();return this;},_mouseStart:function _mouseStart(c){var f=this;this.opos=[c.pageX,c.pageY];if(!this.options.disabled){var d=this.options;this.selectees=e(d.filter,this.element[0]);this._trigger("start",c);e(d.appendTo).append(this.helper);this.helper.css({left:c.clientX,top:c.clientY,width:0,height:0});d.autoRefresh&&this.refresh();this.selectees.filter(".ui-selected").each(function(){var b=e.data(this,"selectable-item");b.startselected=true;if(!c.metaKey){b.$element.removeClass("ui-selected");b.selected=false;b.$element.addClass("ui-unselecting");b.unselecting=true;f._trigger("unselecting",c,{unselecting:b.element});}});e(c.target).parents().andSelf().each(function(){var b=e.data(this,"selectable-item");if(b){var g=!c.metaKey||!b.$element.hasClass("ui-selected");b.$element.removeClass(g?"ui-unselecting":"ui-selected").addClass(g?"ui-selecting":"ui-unselecting");b.unselecting=!g;b.selecting=g;(b.selected=g)?f._trigger("selecting",c,{selecting:b.element}):f._trigger("unselecting",c,{unselecting:b.element});return false;}});}},_mouseDrag:function _mouseDrag(c){var f=this;this.dragged=true;if(!this.options.disabled){var d=this.options,b=this.opos[0],g=this.opos[1],h=c.pageX,i=c.pageY;if(b>h){var j=h;h=b;b=j;}if(g>i){j=i;i=g;g=j;}this.helper.css({left:b,top:g,width:h-b,height:i-g});this.selectees.each(function(){var a=e.data(this,"selectable-item");if(!(!a||a.element==f.element[0])){var k=false;if(d.tolerance=="touch")k=!(a.left>h||a.right<b||a.top>i||a.bottom<g);else if(d.tolerance=="fit")k=a.left>b&&a.right<h&&a.top>g&&a.bottom<i;if(k){if(a.selected){a.$element.removeClass("ui-selected");a.selected=false;}if(a.unselecting){a.$element.removeClass("ui-unselecting");a.unselecting=false;}if(!a.selecting){a.$element.addClass("ui-selecting");a.selecting=true;f._trigger("selecting",c,{selecting:a.element});}}else{if(a.selecting)if(c.metaKey&&a.startselected){a.$element.removeClass("ui-selecting");a.selecting=false;a.$element.addClass("ui-selected");a.selected=true;}else{a.$element.removeClass("ui-selecting");a.selecting=false;if(a.startselected){a.$element.addClass("ui-unselecting");a.unselecting=true;}f._trigger("unselecting",c,{unselecting:a.element});}if(a.selected)if(!c.metaKey&&!a.startselected){a.$element.removeClass("ui-selected");a.selected=false;a.$element.addClass("ui-unselecting");a.unselecting=true;f._trigger("unselecting",c,{unselecting:a.element});}}}});return false;}},_mouseStop:function _mouseStop(c){var f=this;this.dragged=false;e(".ui-unselecting",this.element[0]).each(function(){var d=e.data(this,"selectable-item");d.$element.removeClass("ui-unselecting");d.unselecting=false;d.startselected=false;f._trigger("unselected",c,{unselected:d.element});});e(".ui-selecting",this.element[0]).each(function(){var d=e.data(this,"selectable-item");d.$element.removeClass("ui-selecting").addClass("ui-selected");d.selecting=false;d.selected=true;d.startselected=true;f._trigger("selected",c,{selected:d.element});});this._trigger("stop",c);this.helper.remove();return false;}});e.extend(e.ui.selectable,{version:"1.8.16"});})(jQuery);;/*
 * jQuery UI Sortable 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Sortables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */(function(d){d.widget("ui.sortable",d.ui.mouse,{widgetEventPrefix:"sort",options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:"auto",cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1E3},_create:function _create(){var a=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?a.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):false;this.offset=this.element.offset();this._mouseInit();},destroy:function destroy(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable");this._mouseDestroy();for(var a=this.items.length-1;a>=0;a--){this.items[a].item.removeData("sortable-item");}return this;},_setOption:function _setOption(a,b){if(a==="disabled"){this.options[a]=b;this.widget()[b?"addClass":"removeClass"]("ui-sortable-disabled");}else d.Widget.prototype._setOption.apply(this,arguments);},_mouseCapture:function _mouseCapture(a,b){if(this.reverting)return false;if(this.options.disabled||this.options.type=="static")return false;this._refreshItems(a);var c=null,e=this;d(a.target).parents().each(function(){if(d.data(this,"sortable-item")==e){c=d(this);return false;}});if(d.data(a.target,"sortable-item")==e)c=d(a.target);if(!c)return false;if(this.options.handle&&!b){var f=false;d(this.options.handle,c).find("*").andSelf().each(function(){if(this==a.target)f=true;});if(!f)return false;}this.currentItem=c;this._removeCurrentsFromItems();return true;},_mouseStart:function _mouseStart(a,b,c){b=this.options;var e=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(a);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};this.helper[0]!=this.currentItem[0]&&this.currentItem.hide();this._createPlaceholder();b.containment&&this._setContainment();if(b.cursor){if(d("body").css("cursor"))this._storedCursor=d("body").css("cursor");d("body").css("cursor",b.cursor);}if(b.opacity){if(this.helper.css("opacity"))this._storedOpacity=this.helper.css("opacity");this.helper.css("opacity",b.opacity);}if(b.zIndex){if(this.helper.css("zIndex"))this._storedZIndex=this.helper.css("zIndex");this.helper.css("zIndex",b.zIndex);}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML")this.overflowOffset=this.scrollParent.offset();this._trigger("start",a,this._uiHash());this._preserveHelperProportions||this._cacheHelperProportions();if(!c)for(c=this.containers.length-1;c>=0;c--){this.containers[c]._trigger("activate",a,e._uiHash(this));}if(d.ui.ddmanager)d.ui.ddmanager.current=this;d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(a);return true;},_mouseDrag:function _mouseDrag(a){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs)this.lastPositionAbs=this.positionAbs;if(this.options.scroll){var b=this.options,c=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if(this.overflowOffset.top+this.scrollParent[0].offsetHeight-a.pageY<b.scrollSensitivity)this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop+b.scrollSpeed;else if(a.pageY-this.overflowOffset.top<b.scrollSensitivity)this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop-b.scrollSpeed;if(this.overflowOffset.left+this.scrollParent[0].offsetWidth-a.pageX<b.scrollSensitivity)this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft+b.scrollSpeed;else if(a.pageX-this.overflowOffset.left<b.scrollSensitivity)this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft-b.scrollSpeed;}else{if(a.pageY-d(document).scrollTop()<b.scrollSensitivity)c=d(document).scrollTop(d(document).scrollTop()-b.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<b.scrollSensitivity)c=d(document).scrollTop(d(document).scrollTop()+b.scrollSpeed);if(a.pageX-d(document).scrollLeft()<b.scrollSensitivity)c=d(document).scrollLeft(d(document).scrollLeft()-b.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<b.scrollSensitivity)c=d(document).scrollLeft(d(document).scrollLeft()+b.scrollSpeed);}c!==false&&d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(b=this.items.length-1;b>=0;b--){c=this.items[b];var e=c.item[0],f=this._intersectsWithPointer(c);if(f)if(e!=this.currentItem[0]&&this.placeholder[f==1?"next":"prev"]()[0]!=e&&!d.ui.contains(this.placeholder[0],e)&&(this.options.type=="semi-dynamic"?!d.ui.contains(this.element[0],e):true)){this.direction=f==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(c))this._rearrange(a,c);else break;this._trigger("change",a,this._uiHash());break;}}this._contactContainers(a);d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);this._trigger("sort",a,this._uiHash());this.lastPositionAbs=this.positionAbs;return false;},_mouseStop:function _mouseStop(a,b){if(a){d.ui.ddmanager&&!this.options.dropBehaviour&&d.ui.ddmanager.drop(this,a);if(this.options.revert){var c=this;b=c.placeholder.offset();c.reverting=true;d(this.helper).animate({left:b.left-this.offset.parent.left-c.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:b.top-this.offset.parent.top-c.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){c._clear(a);});}else this._clear(a,b);return false;}},cancel:function cancel(){var a=this;if(this.dragging){this._mouseUp({target:null});this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var b=this.containers.length-1;b>=0;b--){this.containers[b]._trigger("deactivate",null,a._uiHash(this));if(this.containers[b].containerCache.over){this.containers[b]._trigger("out",null,a._uiHash(this));this.containers[b].containerCache.over=0;}}}if(this.placeholder){this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove();d.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});this.domPosition.prev?d(this.domPosition.prev).after(this.currentItem):d(this.domPosition.parent).prepend(this.currentItem);}return this;},serialize:function serialize(a){var b=this._getItemsAsjQuery(a&&a.connected),c=[];a=a||{};d(b).each(function(){var e=(d(a.item||this).attr(a.attribute||"id")||"").match(a.expression||/(.+)[-=_](.+)/);if(e)c.push((a.key||e[1]+"[]")+"="+(a.key&&a.expression?e[1]:e[2]));});!c.length&&a.key&&c.push(a.key+"=");return c.join("&");},toArray:function toArray(a){var b=this._getItemsAsjQuery(a&&a.connected),c=[];a=a||{};b.each(function(){c.push(d(a.item||this).attr(a.attribute||"id")||"");});return c;},_intersectsWith:function _intersectsWith(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,e=this.positionAbs.top,f=e+this.helperProportions.height,g=a.left,h=g+a.width,i=a.top,k=i+a.height,j=this.offset.click.top,l=this.offset.click.left;j=e+j>i&&e+j<k&&b+l>g&&b+l<h;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?j:g<b+this.helperProportions.width/2&&c-this.helperProportions.width/2<h&&i<e+this.helperProportions.height/2&&f-this.helperProportions.height/2<k;},_intersectsWithPointer:function _intersectsWithPointer(a){var b=d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top,a.height);a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left,a.width);b=b&&a;a=this._getDragVerticalDirection();var c=this._getDragHorizontalDirection();if(!b)return false;return this.floating?c&&c=="right"||a=="down"?2:1:a&&(a=="down"?2:1);},_intersectsWithSides:function _intersectsWithSides(a){var b=d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top+a.height/2,a.height);a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left+a.width/2,a.width);var c=this._getDragVerticalDirection(),e=this._getDragHorizontalDirection();return this.floating&&e?e=="right"&&a||e=="left"&&!a:c&&(c=="down"&&b||c=="up"&&!b);},_getDragVerticalDirection:function _getDragVerticalDirection(){var a=this.positionAbs.top-this.lastPositionAbs.top;return a!=0&&(a>0?"down":"up");},_getDragHorizontalDirection:function _getDragHorizontalDirection(){var a=this.positionAbs.left-this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left");},refresh:function refresh(a){this._refreshItems(a);this.refreshPositions();return this;},_connectWith:function _connectWith(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith;},_getItemsAsjQuery:function _getItemsAsjQuery(a){var b=[],c=[],e=this._connectWith();if(e&&a)for(a=e.length-1;a>=0;a--){for(var f=d(e[a]),g=f.length-1;g>=0;g--){var h=d.data(f[g],"sortable");if(h&&h!=this&&!h.options.disabled)c.push([d.isFunction(h.options.items)?h.options.items.call(h.element):d(h.options.items,h.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),h]);}}c.push([d.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):d(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(a=c.length-1;a>=0;a--){c[a][0].each(function(){b.push(this);});}return d(b);},_removeCurrentsFromItems:function _removeCurrentsFromItems(){for(var a=this.currentItem.find(":data(sortable-item)"),b=0;b<this.items.length;b++){for(var c=0;c<a.length;c++){a[c]==this.items[b].item[0]&&this.items.splice(b,1);}}},_refreshItems:function _refreshItems(a){this.items=[];this.containers=[this];var b=this.items,c=[[d.isFunction(this.options.items)?this.options.items.call(this.element[0],a,{item:this.currentItem}):d(this.options.items,this.element),this]],e=this._connectWith();if(e)for(var f=e.length-1;f>=0;f--){for(var g=d(e[f]),h=g.length-1;h>=0;h--){var i=d.data(g[h],"sortable");if(i&&i!=this&&!i.options.disabled){c.push([d.isFunction(i.options.items)?i.options.items.call(i.element[0],a,{item:this.currentItem}):d(i.options.items,i.element),i]);this.containers.push(i);}}}for(f=c.length-1;f>=0;f--){a=c[f][1];e=c[f][0];h=0;for(g=e.length;h<g;h++){i=d(e[h]);i.data("sortable-item",a);b.push({item:i,instance:a,width:0,height:0,left:0,top:0});}}},refreshPositions:function refreshPositions(a){if(this.offsetParent&&this.helper)this.offset.parent=this._getParentOffset();for(var b=this.items.length-1;b>=0;b--){var c=this.items[b];if(!(c.instance!=this.currentContainer&&this.currentContainer&&c.item[0]!=this.currentItem[0])){var e=this.options.toleranceElement?d(this.options.toleranceElement,c.item):c.item;if(!a){c.width=e.outerWidth();c.height=e.outerHeight();}e=e.offset();c.left=e.left;c.top=e.top;}}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(b=this.containers.length-1;b>=0;b--){e=this.containers[b].element.offset();this.containers[b].containerCache.left=e.left;this.containers[b].containerCache.top=e.top;this.containers[b].containerCache.width=this.containers[b].element.outerWidth();this.containers[b].containerCache.height=this.containers[b].element.outerHeight();}return this;},_createPlaceholder:function _createPlaceholder(a){var b=a||this,c=b.options;if(!c.placeholder||c.placeholder.constructor==String){var e=c.placeholder;c.placeholder={element:function element(){var f=d(document.createElement(b.currentItem[0].nodeName)).addClass(e||b.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!e)f.style.visibility="hidden";return f;},update:function update(f,g){if(!(e&&!c.forcePlaceholderSize)){g.height()||g.height(b.currentItem.innerHeight()-parseInt(b.currentItem.css("paddingTop")||0,10)-parseInt(b.currentItem.css("paddingBottom")||0,10));g.width()||g.width(b.currentItem.innerWidth()-parseInt(b.currentItem.css("paddingLeft")||0,10)-parseInt(b.currentItem.css("paddingRight")||0,10));}}};}b.placeholder=d(c.placeholder.element.call(b.element,b.currentItem));b.currentItem.after(b.placeholder);c.placeholder.update(b,b.placeholder);},_contactContainers:function _contactContainers(a){for(var b=null,c=null,e=this.containers.length-1;e>=0;e--){if(!d.ui.contains(this.currentItem[0],this.containers[e].element[0]))if(this._intersectsWith(this.containers[e].containerCache)){if(!(b&&d.ui.contains(this.containers[e].element[0],b.element[0]))){b=this.containers[e];c=e;}}else if(this.containers[e].containerCache.over){this.containers[e]._trigger("out",a,this._uiHash(this));this.containers[e].containerCache.over=0;}}if(b)if(this.containers.length===1){this.containers[c]._trigger("over",a,this._uiHash(this));this.containers[c].containerCache.over=1;}else if(this.currentContainer!=this.containers[c]){b=1E4;e=null;for(var f=this.positionAbs[this.containers[c].floating?"left":"top"],g=this.items.length-1;g>=0;g--){if(d.ui.contains(this.containers[c].element[0],this.items[g].item[0])){var h=this.items[g][this.containers[c].floating?"left":"top"];if(Math.abs(h-f)<b){b=Math.abs(h-f);e=this.items[g];}}}if(e||this.options.dropOnEmpty){this.currentContainer=this.containers[c];e?this._rearrange(a,e,null,true):this._rearrange(a,null,this.containers[c].element,true);this._trigger("change",a,this._uiHash());this.containers[c]._trigger("change",a,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[c]._trigger("over",a,this._uiHash(this));this.containers[c].containerCache.over=1;}}},_createHelper:function _createHelper(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a,this.currentItem])):b.helper=="clone"?this.currentItem.clone():this.currentItem;a.parents("body").length||d(b.appendTo!="parent"?b.appendTo:this.currentItem[0].parentNode)[0].appendChild(a[0]);if(a[0]==this.currentItem[0])this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")};if(a[0].style.width==""||b.forceHelperSize)a.width(this.currentItem.width());if(a[0].style.height==""||b.forceHelperSize)a.height(this.currentItem.height());return a;},_adjustOffsetFromHelper:function _adjustOffsetFromHelper(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0],top:+a[1]||0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top;},_getParentOffset:function _getParentOffset(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop();}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)};},_getRelativeOffset:function _getRelativeOffset(){if(this.cssPosition=="relative"){var a=this.currentItem.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()};}else return{top:0,left:0};},_cacheMargins:function _cacheMargins(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0};},_cacheHelperProportions:function _cacheHelperProportions(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};},_setContainment:function _setContainment(){var a=this.options;if(a.containment=="parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)){var b=d(a.containment)[0];a=d(a.containment).offset();var c=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0)-this.margins.left,a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0)-this.margins.top,a.left+(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,a.top+(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top];}},_convertPositionTo:function _convertPositionTo(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(c[0].tagName);return{top:b.top+this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:c.scrollLeft())*a)};},_generatePosition:function _generatePosition(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(c[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0]))this.offset.relative=this._getRelativeOffset();var f=a.pageX,g=a.pageY;if(this.originalPosition){if(this.containment){if(a.pageX-this.offset.click.left<this.containment[0])f=this.containment[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<this.containment[1])g=this.containment[1]+this.offset.click.top;if(a.pageX-this.offset.click.left>this.containment[2])f=this.containment[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>this.containment[3])g=this.containment[3]+this.offset.click.top;}if(b.grid){g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1];g=this.containment?!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g;f=this.originalPageX+Math.round((f-this.originalPageX)/b.grid[0])*b.grid[0];f=this.containment?!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:!(f-this.offset.click.left<this.containment[0])?f-b.grid[0]:f+b.grid[0]:f;}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:c.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(d.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:c.scrollLeft())};},_rearrange:function _rearrange(a,b,c,e){c?c[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?b.item[0]:b.item[0].nextSibling);this.counter=this.counter?++this.counter:1;var f=this,g=this.counter;window.setTimeout(function(){g==f.counter&&f.refreshPositions(!e);},0);},_clear:function _clear(a,b){this.reverting=false;var c=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var e in this._storedCSS){if(this._storedCSS[e]=="auto"||this._storedCSS[e]=="static")this._storedCSS[e]="";}this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");}else this.currentItem.show();this.fromOutside&&!b&&c.push(function(f){this._trigger("receive",f,this._uiHash(this.fromOutside));});if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!b)c.push(function(f){this._trigger("update",f,this._uiHash());});if(!d.ui.contains(this.element[0],this.currentItem[0])){b||c.push(function(f){this._trigger("remove",f,this._uiHash());});for(e=this.containers.length-1;e>=0;e--){if(d.ui.contains(this.containers[e].element[0],this.currentItem[0])&&!b){c.push(function(f){return function(g){f._trigger("receive",g,this._uiHash(this));};}.call(this,this.containers[e]));c.push(function(f){return function(g){f._trigger("update",g,this._uiHash(this));};}.call(this,this.containers[e]));}}}for(e=this.containers.length-1;e>=0;e--){b||c.push(function(f){return function(g){f._trigger("deactivate",g,this._uiHash(this));};}.call(this,this.containers[e]));if(this.containers[e].containerCache.over){c.push(function(f){return function(g){f._trigger("out",g,this._uiHash(this));};}.call(this,this.containers[e]));this.containers[e].containerCache.over=0;}}this._storedCursor&&d("body").css("cursor",this._storedCursor);this._storedOpacity&&this.helper.css("opacity",this._storedOpacity);if(this._storedZIndex)this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex);this.dragging=false;if(this.cancelHelperRemoval){if(!b){this._trigger("beforeStop",a,this._uiHash());for(e=0;e<c.length;e++){c[e].call(this,a);}this._trigger("stop",a,this._uiHash());}return false;}b||this._trigger("beforeStop",a,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.helper[0]!=this.currentItem[0]&&this.helper.remove();this.helper=null;if(!b){for(e=0;e<c.length;e++){c[e].call(this,a);}this._trigger("stop",a,this._uiHash());}this.fromOutside=false;return true;},_trigger:function _trigger(){d.Widget.prototype._trigger.apply(this,arguments)===false&&this.cancel();},_uiHash:function _uiHash(a){var b=a||this;return{helper:b.helper,placeholder:b.placeholder||d([]),position:b.position,originalPosition:b.originalPosition,offset:b.positionAbs,item:b.currentItem,sender:a?a.element:null};}});d.extend(d.ui.sortable,{version:"1.8.16"});})(jQuery);;/*
 * jQuery UI Accordion 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Accordion
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */(function(c){c.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:true,clearStyle:false,collapsible:false,event:"click",fillSpace:false,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:false,navigationFilter:function navigationFilter(){return this.href.toLowerCase()===location.href.toLowerCase();}},_create:function _create(){var a=this,b=a.options;a.running=0;a.element.addClass("ui-accordion ui-widget ui-helper-reset").children("li").addClass("ui-accordion-li-fix");a.headers=a.element.find(b.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){b.disabled||c(this).addClass("ui-state-hover");}).bind("mouseleave.accordion",function(){b.disabled||c(this).removeClass("ui-state-hover");}).bind("focus.accordion",function(){b.disabled||c(this).addClass("ui-state-focus");}).bind("blur.accordion",function(){b.disabled||c(this).removeClass("ui-state-focus");});a.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");if(b.navigation){var d=a.element.find("a").filter(b.navigationFilter).eq(0);if(d.length){var h=d.closest(".ui-accordion-header");a.active=h.length?h:d.closest(".ui-accordion-content").prev();}}a.active=a._findActive(a.active||b.active).addClass("ui-state-default ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");a.active.next().addClass("ui-accordion-content-active");a._createIcons();a.resize();a.element.attr("role","tablist");a.headers.attr("role","tab").bind("keydown.accordion",function(f){return a._keydown(f);}).next().attr("role","tabpanel");a.headers.not(a.active||"").attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).next().hide();a.active.length?a.active.attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}):a.headers.eq(0).attr("tabIndex",0);c.browser.safari||a.headers.find("a").attr("tabIndex",-1);b.event&&a.headers.bind(b.event.split(" ").join(".accordion ")+".accordion",function(f){a._clickHandler.call(a,f,this);f.preventDefault();});},_createIcons:function _createIcons(){var a=this.options;if(a.icons){c("<span></span>").addClass("ui-icon "+a.icons.header).prependTo(this.headers);this.active.children(".ui-icon").toggleClass(a.icons.header).toggleClass(a.icons.headerSelected);this.element.addClass("ui-accordion-icons");}},_destroyIcons:function _destroyIcons(){this.headers.children(".ui-icon").remove();this.element.removeClass("ui-accordion-icons");},destroy:function destroy(){var a=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role");this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("tabIndex");this.headers.find("a").removeAttr("tabIndex");this._destroyIcons();var b=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled");if(a.autoHeight||a.fillHeight)b.css("height","");return c.Widget.prototype.destroy.call(this);},_setOption:function _setOption(a,b){c.Widget.prototype._setOption.apply(this,arguments);a=="active"&&this.activate(b);if(a=="icons"){this._destroyIcons();b&&this._createIcons();}if(a=="disabled")this.headers.add(this.headers.next())[b?"addClass":"removeClass"]("ui-accordion-disabled ui-state-disabled");},_keydown:function _keydown(a){if(!(this.options.disabled||a.altKey||a.ctrlKey)){var b=c.ui.keyCode,d=this.headers.length,h=this.headers.index(a.target),f=false;switch(a.keyCode){case b.RIGHT:case b.DOWN:f=this.headers[(h+1)%d];break;case b.LEFT:case b.UP:f=this.headers[(h-1+d)%d];break;case b.SPACE:case b.ENTER:this._clickHandler({target:a.target},a.target);a.preventDefault();}if(f){c(a.target).attr("tabIndex",-1);c(f).attr("tabIndex",0);f.focus();return false;}return true;}},resize:function resize(){var a=this.options,b;if(a.fillSpace){if(c.browser.msie){var d=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden");}b=this.element.parent().height();c.browser.msie&&this.element.parent().css("overflow",d);this.headers.each(function(){b-=c(this).outerHeight(true);});this.headers.next().each(function(){c(this).height(Math.max(0,b-c(this).innerHeight()+c(this).height()));}).css("overflow","auto");}else if(a.autoHeight){b=0;this.headers.next().each(function(){b=Math.max(b,c(this).height("").height());}).height(b);}return this;},activate:function activate(a){this.options.active=a;a=this._findActive(a)[0];this._clickHandler({target:a},a);return this;},_findActive:function _findActive(a){return a?typeof a==="number"?this.headers.filter(":eq("+a+")"):this.headers.not(this.headers.not(a)):a===false?c([]):this.headers.filter(":eq(0)");},_clickHandler:function _clickHandler(a,b){var d=this.options;if(!d.disabled)if(a.target){a=c(a.currentTarget||b);b=a[0]===this.active[0];d.active=d.collapsible&&b?false:this.headers.index(a);if(!(this.running||!d.collapsible&&b)){var h=this.active;j=a.next();g=this.active.next();e={options:d,newHeader:b&&d.collapsible?c([]):a,oldHeader:this.active,newContent:b&&d.collapsible?c([]):j,oldContent:g};var f=this.headers.index(this.active[0])>this.headers.index(a[0]);this.active=b?c([]):a;this._toggle(j,g,e,b,f);h.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header);if(!b){a.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").children(".ui-icon").removeClass(d.icons.header).addClass(d.icons.headerSelected);a.next().addClass("ui-accordion-content-active");}}}else if(d.collapsible){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header);this.active.next().addClass("ui-accordion-content-active");var g=this.active.next(),e={options:d,newHeader:c([]),oldHeader:d.active,newContent:c([]),oldContent:g},j=this.active=c([]);this._toggle(j,g,e);}},_toggle:function _toggle(a,b,d,h,f){var g=this,e=g.options;g.toShow=a;g.toHide=b;g.data=d;var j=function j(){if(g)return g._completed.apply(g,arguments);};g._trigger("changestart",null,g.data);g.running=b.size()===0?a.size():b.size();if(e.animated){d={};d=e.collapsible&&h?{toShow:c([]),toHide:b,complete:j,down:f,autoHeight:e.autoHeight||e.fillSpace}:{toShow:a,toHide:b,complete:j,down:f,autoHeight:e.autoHeight||e.fillSpace};if(!e.proxied)e.proxied=e.animated;if(!e.proxiedDuration)e.proxiedDuration=e.duration;e.animated=c.isFunction(e.proxied)?e.proxied(d):e.proxied;e.duration=c.isFunction(e.proxiedDuration)?e.proxiedDuration(d):e.proxiedDuration;h=c.ui.accordion.animations;var i=e.duration,k=e.animated;if(k&&!h[k]&&!c.easing[k])k="slide";h[k]||(h[k]=function(l){this.slide(l,{easing:k,duration:i||700});});h[k](d);}else{if(e.collapsible&&h)a.toggle();else{b.hide();a.show();}j(true);}b.prev().attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).blur();a.prev().attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}).focus();},_completed:function _completed(a){this.running=a?0:--this.running;if(!this.running){this.options.clearStyle&&this.toShow.add(this.toHide).css({height:"",overflow:""});this.toHide.removeClass("ui-accordion-content-active");if(this.toHide.length)this.toHide.parent()[0].className=this.toHide.parent()[0].className;this._trigger("change",null,this.data);}}});c.extend(c.ui.accordion,{version:"1.8.16",animations:{slide:function slide(a,b){a=c.extend({easing:"swing",duration:300},a,b);if(a.toHide.size()){if(a.toShow.size()){var d=a.toShow.css("overflow"),h=0,f={},g={},e;b=a.toShow;e=b[0].style.width;b.width(parseInt(b.parent().width(),10)-parseInt(b.css("paddingLeft"),10)-parseInt(b.css("paddingRight"),10)-(parseInt(b.css("borderLeftWidth"),10)||0)-(parseInt(b.css("borderRightWidth"),10)||0));c.each(["height","paddingTop","paddingBottom"],function(j,i){g[i]="hide";j=(""+c.css(a.toShow[0],i)).match(/^([\d+-.]+)(.*)$/);f[i]={value:j[1],unit:j[2]||"px"};});a.toShow.css({height:0,overflow:"hidden"}).show();a.toHide.filter(":hidden").each(a.complete).end().filter(":visible").animate(g,{step:function step(j,i){if(i.prop=="height")h=i.end-i.start===0?0:(i.now-i.start)/(i.end-i.start);a.toShow[0].style[i.prop]=h*f[i.prop].value+f[i.prop].unit;},duration:a.duration,easing:a.easing,complete:function complete(){a.autoHeight||a.toShow.css("height","");a.toShow.css({width:e,overflow:d});a.complete();}});}else a.toHide.animate({height:"hide",paddingTop:"hide",paddingBottom:"hide"},a);}else a.toShow.animate({height:"show",paddingTop:"show",paddingBottom:"show"},a);},bounceslide:function bounceslide(a){this.slide(a,{easing:a.down?"easeOutBounce":"swing",duration:a.down?1E3:200});}}});})(jQuery);;/*
 * jQuery UI Autocomplete 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Autocomplete
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 */(function(d){var e=0;d.widget("ui.autocomplete",{options:{appendTo:"body",autoFocus:false,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null},pending:0,_create:function _create(){var a=this,b=this.element[0].ownerDocument,g;this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(c){if(!(a.options.disabled||a.element.propAttr("readOnly"))){g=false;var f=d.ui.keyCode;switch(c.keyCode){case f.PAGE_UP:a._move("previousPage",c);break;case f.PAGE_DOWN:a._move("nextPage",c);break;case f.UP:a._move("previous",c);c.preventDefault();break;case f.DOWN:a._move("next",c);c.preventDefault();break;case f.ENTER:case f.NUMPAD_ENTER:if(a.menu.active){g=true;c.preventDefault();}case f.TAB:if(!a.menu.active)return;a.menu.select(c);break;case f.ESCAPE:a.element.val(a.term);a.close(c);break;default:clearTimeout(a.searching);a.searching=setTimeout(function(){if(a.term!=a.element.val()){a.selectedItem=null;a.search(null,c);}},a.options.delay);break;}}}).bind("keypress.autocomplete",function(c){if(g){g=false;c.preventDefault();}}).bind("focus.autocomplete",function(){if(!a.options.disabled){a.selectedItem=null;a.previous=a.element.val();}}).bind("blur.autocomplete",function(c){if(!a.options.disabled){clearTimeout(a.searching);a.closing=setTimeout(function(){a.close(c);a._change(c);},150);}});this._initSource();this.response=function(){return a._response.apply(a,arguments);};this.menu=d("<ul></ul>").addClass("ui-autocomplete").appendTo(d(this.options.appendTo||"body",b)[0]).mousedown(function(c){var f=a.menu.element[0];d(c.target).closest(".ui-menu-item").length||setTimeout(function(){d(document).one("mousedown",function(h){h.target!==a.element[0]&&h.target!==f&&!d.ui.contains(f,h.target)&&a.close();});},1);setTimeout(function(){clearTimeout(a.closing);},13);}).menu({focus:function focus(c,f){f=f.item.data("item.autocomplete");false!==a._trigger("focus",c,{item:f})&&/^key/.test(c.originalEvent.type)&&a.element.val(f.value);},selected:function selected(c,f){var h=f.item.data("item.autocomplete"),i=a.previous;if(a.element[0]!==b.activeElement){a.element.focus();a.previous=i;setTimeout(function(){a.previous=i;a.selectedItem=h;},1);}false!==a._trigger("select",c,{item:h})&&a.element.val(h.value);a.term=a.element.val();a.close(c);a.selectedItem=h;},blur:function blur(){a.menu.element.is(":visible")&&a.element.val()!==a.term&&a.element.val(a.term);}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu");d.fn.bgiframe&&this.menu.element.bgiframe();},destroy:function destroy(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup");this.menu.element.remove();d.Widget.prototype.destroy.call(this);},_setOption:function _setOption(a,b){d.Widget.prototype._setOption.apply(this,arguments);a==="source"&&this._initSource();if(a==="appendTo")this.menu.element.appendTo(d(b||"body",this.element[0].ownerDocument)[0]);a==="disabled"&&b&&this.xhr&&this.xhr.abort();},_initSource:function _initSource(){var a=this,b,g;if(d.isArray(this.options.source)){b=this.options.source;this.source=function(c,f){f(d.ui.autocomplete.filter(b,c.term));};}else if(typeof this.options.source==="string"){g=this.options.source;this.source=function(c,f){a.xhr&&a.xhr.abort();a.xhr=d.ajax({url:g,data:c,dataType:"json",autocompleteRequest:++e,success:function success(h){this.autocompleteRequest===e&&f(h);},error:function error(){this.autocompleteRequest===e&&f([]);}});};}else this.source=this.options.source;},search:function search(a,b){a=a!=null?a:this.element.val();this.term=this.element.val();if(a.length<this.options.minLength)return this.close(b);clearTimeout(this.closing);if(this._trigger("search",b)!==false)return this._search(a);},_search:function _search(a){this.pending++;this.element.addClass("ui-autocomplete-loading");this.source({term:a},this.response);},_response:function _response(a){if(!this.options.disabled&&a&&a.length){a=this._normalize(a);this._suggest(a);this._trigger("open");}else this.close();this.pending--;this.pending||this.element.removeClass("ui-autocomplete-loading");},close:function close(a){clearTimeout(this.closing);if(this.menu.element.is(":visible")){this.menu.element.hide();this.menu.deactivate();this._trigger("close",a);}},_change:function _change(a){this.previous!==this.element.val()&&this._trigger("change",a,{item:this.selectedItem});},_normalize:function _normalize(a){if(a.length&&a[0].label&&a[0].value)return a;return d.map(a,function(b){if(typeof b==="string")return{label:b,value:b};return d.extend({label:b.label||b.value,value:b.value||b.label},b);});},_suggest:function _suggest(a){var b=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(b,a);this.menu.deactivate();this.menu.refresh();b.show();this._resizeMenu();b.position(d.extend({of:this.element},this.options.position));this.options.autoFocus&&this.menu.next(new d.Event("mouseover"));},_resizeMenu:function _resizeMenu(){var a=this.menu.element;a.outerWidth(Math.max(a.width("").outerWidth(),this.element.outerWidth()));},_renderMenu:function _renderMenu(a,b){var g=this;d.each(b,function(c,f){g._renderItem(a,f);});},_renderItem:function _renderItem(a,b){return d("<li></li>").data("item.autocomplete",b).append(d("<a></a>").text(b.label)).appendTo(a);},_move:function _move(a,b){if(this.menu.element.is(":visible")){if(this.menu.first()&&/^previous/.test(a)||this.menu.last()&&/^next/.test(a)){this.element.val(this.term);this.menu.deactivate();}else this.menu[a](b);}else this.search(null,b);},widget:function widget(){return this.menu.element;}});d.extend(d.ui.autocomplete,{escapeRegex:function escapeRegex(a){return a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");},filter:function filter(a,b){var g=new RegExp(d.ui.autocomplete.escapeRegex(b),"i");return d.grep(a,function(c){return g.test(c.label||c.value||c);});}});})(jQuery);(function(d){d.widget("ui.menu",{_create:function _create(){var e=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).click(function(a){if(d(a.target).closest(".ui-menu-item a").length){a.preventDefault();e.select(a);}});this.refresh();},refresh:function refresh(){var e=this;this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem").children("a").addClass("ui-corner-all").attr("tabindex",-1).mouseenter(function(a){e.activate(a,d(this).parent());}).mouseleave(function(){e.deactivate();});},activate:function activate(e,a){this.deactivate();if(this.hasScroll()){var b=a.offset().top-this.element.offset().top,g=this.element.scrollTop(),c=this.element.height();if(b<0)this.element.scrollTop(g+b);else b>=c&&this.element.scrollTop(g+b-c+a.height());}this.active=a.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end();this._trigger("focus",e,{item:a});},deactivate:function deactivate(){if(this.active){this.active.children("a").removeClass("ui-state-hover").removeAttr("id");this._trigger("blur");this.active=null;}},next:function next(e){this.move("next",".ui-menu-item:first",e);},previous:function previous(e){this.move("prev",".ui-menu-item:last",e);},first:function first(){return this.active&&!this.active.prevAll(".ui-menu-item").length;},last:function last(){return this.active&&!this.active.nextAll(".ui-menu-item").length;},move:function move(e,a,b){if(this.active){e=this.active[e+"All"](".ui-menu-item").eq(0);e.length?this.activate(b,e):this.activate(b,this.element.children(a));}else this.activate(b,this.element.children(a));},nextPage:function nextPage(e){if(this.hasScroll()){if(!this.active||this.last())this.activate(e,this.element.children(".ui-menu-item:first"));else{var a=this.active.offset().top,b=this.element.height(),g=this.element.children(".ui-menu-item").filter(function(){var c=d(this).offset().top-a-b+d(this).height();return c<10&&c>-10;});g.length||(g=this.element.children(".ui-menu-item:last"));this.activate(e,g);}}else this.activate(e,this.element.children(".ui-menu-item").filter(!this.active||this.last()?":first":":last"));},previousPage:function previousPage(e){if(this.hasScroll()){if(!this.active||this.first())this.activate(e,this.element.children(".ui-menu-item:last"));else{var a=this.active.offset().top,b=this.element.height();result=this.element.children(".ui-menu-item").filter(function(){var g=d(this).offset().top-a+b-d(this).height();return g<10&&g>-10;});result.length||(result=this.element.children(".ui-menu-item:first"));this.activate(e,result);}}else this.activate(e,this.element.children(".ui-menu-item").filter(!this.active||this.first()?":last":":first"));},hasScroll:function hasScroll(){return this.element.height()<this.element[d.fn.prop?"prop":"attr"]("scrollHeight");},select:function select(e){this._trigger("selected",e,{item:this.active});}});})(jQuery);;/*
 * jQuery UI Button 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Button
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */(function(b){var h,i,j,g,l=function l(){var a=b(this).find(":ui-button");setTimeout(function(){a.button("refresh");},1);},k=function k(a){var c=a.name,e=a.form,f=b([]);if(c)f=e?b(e).find("[name='"+c+"']"):b("[name='"+c+"']",a.ownerDocument).filter(function(){return!this.form;});return f;};b.widget("ui.button",{options:{disabled:null,text:true,label:null,icons:{primary:null,secondary:null}},_create:function _create(){this.element.closest("form").unbind("reset.button").bind("reset.button",l);if(typeof this.options.disabled!=="boolean")this.options.disabled=this.element.propAttr("disabled");this._determineButtonType();this.hasTitle=!!this.buttonElement.attr("title");var a=this,c=this.options,e=this.type==="checkbox"||this.type==="radio",f="ui-state-hover"+(!e?" ui-state-active":"");if(c.label===null)c.label=this.buttonElement.html();if(this.element.is(":disabled"))c.disabled=true;this.buttonElement.addClass("ui-button ui-widget ui-state-default ui-corner-all").attr("role","button").bind("mouseenter.button",function(){if(!c.disabled){b(this).addClass("ui-state-hover");this===h&&b(this).addClass("ui-state-active");}}).bind("mouseleave.button",function(){c.disabled||b(this).removeClass(f);}).bind("click.button",function(d){if(c.disabled){d.preventDefault();d.stopImmediatePropagation();}});this.element.bind("focus.button",function(){a.buttonElement.addClass("ui-state-focus");}).bind("blur.button",function(){a.buttonElement.removeClass("ui-state-focus");});if(e){this.element.bind("change.button",function(){g||a.refresh();});this.buttonElement.bind("mousedown.button",function(d){if(!c.disabled){g=false;i=d.pageX;j=d.pageY;}}).bind("mouseup.button",function(d){if(!c.disabled)if(i!==d.pageX||j!==d.pageY)g=true;});}if(this.type==="checkbox")this.buttonElement.bind("click.button",function(){if(c.disabled||g)return false;b(this).toggleClass("ui-state-active");a.buttonElement.attr("aria-pressed",a.element[0].checked);});else if(this.type==="radio")this.buttonElement.bind("click.button",function(){if(c.disabled||g)return false;b(this).addClass("ui-state-active");a.buttonElement.attr("aria-pressed","true");var d=a.element[0];k(d).not(d).map(function(){return b(this).button("widget")[0];}).removeClass("ui-state-active").attr("aria-pressed","false");});else{this.buttonElement.bind("mousedown.button",function(){if(c.disabled)return false;b(this).addClass("ui-state-active");h=this;b(document).one("mouseup",function(){h=null;});}).bind("mouseup.button",function(){if(c.disabled)return false;b(this).removeClass("ui-state-active");}).bind("keydown.button",function(d){if(c.disabled)return false;if(d.keyCode==b.ui.keyCode.SPACE||d.keyCode==b.ui.keyCode.ENTER)b(this).addClass("ui-state-active");}).bind("keyup.button",function(){b(this).removeClass("ui-state-active");});this.buttonElement.is("a")&&this.buttonElement.keyup(function(d){d.keyCode===b.ui.keyCode.SPACE&&b(this).click();});}this._setOption("disabled",c.disabled);this._resetButton();},_determineButtonType:function _determineButtonType(){this.type=this.element.is(":checkbox")?"checkbox":this.element.is(":radio")?"radio":this.element.is("input")?"input":"button";if(this.type==="checkbox"||this.type==="radio"){var a=this.element.parents().filter(":last"),c="label[for='"+this.element.attr("id")+"']";this.buttonElement=a.find(c);if(!this.buttonElement.length){a=a.length?a.siblings():this.element.siblings();this.buttonElement=a.filter(c);if(!this.buttonElement.length)this.buttonElement=a.find(c);}this.element.addClass("ui-helper-hidden-accessible");(a=this.element.is(":checked"))&&this.buttonElement.addClass("ui-state-active");this.buttonElement.attr("aria-pressed",a);}else this.buttonElement=this.element;},widget:function widget(){return this.buttonElement;},destroy:function destroy(){this.element.removeClass("ui-helper-hidden-accessible");this.buttonElement.removeClass("ui-button ui-widget ui-state-default ui-corner-all ui-state-hover ui-state-active  ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only").removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html());this.hasTitle||this.buttonElement.removeAttr("title");b.Widget.prototype.destroy.call(this);},_setOption:function _setOption(a,c){b.Widget.prototype._setOption.apply(this,arguments);if(a==="disabled")c?this.element.propAttr("disabled",true):this.element.propAttr("disabled",false);else this._resetButton();},refresh:function refresh(){var a=this.element.is(":disabled");a!==this.options.disabled&&this._setOption("disabled",a);if(this.type==="radio")k(this.element[0]).each(function(){b(this).is(":checked")?b(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):b(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false");});else if(this.type==="checkbox")this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false");},_resetButton:function _resetButton(){if(this.type==="input")this.options.label&&this.element.val(this.options.label);else{var a=this.buttonElement.removeClass("ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only"),c=b("<span></span>").addClass("ui-button-text").html(this.options.label).appendTo(a.empty()).text(),e=this.options.icons,f=e.primary&&e.secondary,d=[];if(e.primary||e.secondary){if(this.options.text)d.push("ui-button-text-icon"+(f?"s":e.primary?"-primary":"-secondary"));e.primary&&a.prepend("<span class='ui-button-icon-primary ui-icon "+e.primary+"'></span>");e.secondary&&a.append("<span class='ui-button-icon-secondary ui-icon "+e.secondary+"'></span>");if(!this.options.text){d.push(f?"ui-button-icons-only":"ui-button-icon-only");this.hasTitle||a.attr("title",c);}}else d.push("ui-button-text-only");a.addClass(d.join(" "));}}});b.widget("ui.buttonset",{options:{items:":button, :submit, :reset, :checkbox, :radio, a, :data(button)"},_create:function _create(){this.element.addClass("ui-buttonset");},_init:function _init(){this.refresh();},_setOption:function _setOption(a,c){a==="disabled"&&this.buttons.button("option",a,c);b.Widget.prototype._setOption.apply(this,arguments);},refresh:function refresh(){var a=this.element.css("direction")==="ltr";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return b(this).button("widget")[0];}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(a?"ui-corner-left":"ui-corner-right").end().filter(":last").addClass(a?"ui-corner-right":"ui-corner-left").end().end();},destroy:function destroy(){this.element.removeClass("ui-buttonset");this.buttons.map(function(){return b(this).button("widget")[0];}).removeClass("ui-corner-left ui-corner-right").end().button("destroy");b.Widget.prototype.destroy.call(this);}});})(jQuery);;/*
 * jQuery UI Dialog 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *  jquery.ui.button.js
 *	jquery.ui.draggable.js
 *	jquery.ui.mouse.js
 *	jquery.ui.position.js
 *	jquery.ui.resizable.js
 */(function(c,l){var m={buttons:true,height:true,maxHeight:true,maxWidth:true,minHeight:true,minWidth:true,width:true},n={maxHeight:true,maxWidth:true,minHeight:true,minWidth:true},o=c.attrFn||{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true,click:true};c.widget("ui.dialog",{options:{autoOpen:true,buttons:{},closeOnEscape:true,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:{my:"center",at:"center",collision:"fit",using:function using(a){var b=c(this).css(a).offset().top;b<0&&c(this).css("top",a.top-b);}},resizable:true,show:null,stack:true,title:"",width:300,zIndex:1E3},_create:function _create(){this.originalTitle=this.element.attr("title");if(typeof this.originalTitle!=="string")this.originalTitle="";this.options.title=this.options.title||this.originalTitle;var a=this,b=a.options,d=b.title||"&#160;",e=c.ui.dialog.getTitleId(a.element),g=(a.uiDialog=c("<div></div>")).appendTo(document.body).hide().addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+b.dialogClass).css({zIndex:b.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(i){if(b.closeOnEscape&&!i.isDefaultPrevented()&&i.keyCode&&i.keyCode===c.ui.keyCode.ESCAPE){a.close(i);i.preventDefault();}}).attr({role:"dialog","aria-labelledby":e}).mousedown(function(i){a.moveToTop(false,i);});a.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g);var f=(a.uiDialogTitlebar=c("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g),h=c('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){h.addClass("ui-state-hover");},function(){h.removeClass("ui-state-hover");}).focus(function(){h.addClass("ui-state-focus");}).blur(function(){h.removeClass("ui-state-focus");}).click(function(i){a.close(i);return false;}).appendTo(f);(a.uiDialogTitlebarCloseText=c("<span></span>")).addClass("ui-icon ui-icon-closethick").text(b.closeText).appendTo(h);c("<span></span>").addClass("ui-dialog-title").attr("id",e).html(d).prependTo(f);if(c.isFunction(b.beforeclose)&&!c.isFunction(b.beforeClose))b.beforeClose=b.beforeclose;f.find("*").add(f).disableSelection();b.draggable&&c.fn.draggable&&a._makeDraggable();b.resizable&&c.fn.resizable&&a._makeResizable();a._createButtons(b.buttons);a._isOpen=false;c.fn.bgiframe&&g.bgiframe();},_init:function _init(){this.options.autoOpen&&this.open();},destroy:function destroy(){var a=this;a.overlay&&a.overlay.destroy();a.uiDialog.hide();a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");a.uiDialog.remove();a.originalTitle&&a.element.attr("title",a.originalTitle);return a;},widget:function widget(){return this.uiDialog;},close:function close(a){var b=this,d,e;if(false!==b._trigger("beforeClose",a)){b.overlay&&b.overlay.destroy();b.uiDialog.unbind("keypress.ui-dialog");b._isOpen=false;if(b.options.hide)b.uiDialog.hide(b.options.hide,function(){b._trigger("close",a);});else{b.uiDialog.hide();b._trigger("close",a);}c.ui.dialog.overlay.resize();if(b.options.modal){d=0;c(".ui-dialog").each(function(){if(this!==b.uiDialog[0]){e=c(this).css("z-index");isNaN(e)||(d=Math.max(d,e));}});c.ui.dialog.maxZ=d;}return b;}},isOpen:function isOpen(){return this._isOpen;},moveToTop:function moveToTop(a,b){var d=this,e=d.options;if(e.modal&&!a||!e.stack&&!e.modal)return d._trigger("focus",b);if(e.zIndex>c.ui.dialog.maxZ)c.ui.dialog.maxZ=e.zIndex;if(d.overlay){c.ui.dialog.maxZ+=1;d.overlay.$el.css("z-index",c.ui.dialog.overlay.maxZ=c.ui.dialog.maxZ);}a={scrollTop:d.element.scrollTop(),scrollLeft:d.element.scrollLeft()};c.ui.dialog.maxZ+=1;d.uiDialog.css("z-index",c.ui.dialog.maxZ);d.element.attr(a);d._trigger("focus",b);return d;},open:function open(){if(!this._isOpen){var a=this,b=a.options,d=a.uiDialog;a.overlay=b.modal?new c.ui.dialog.overlay(a):null;a._size();a._position(b.position);d.show(b.show);a.moveToTop(true);b.modal&&d.bind("keypress.ui-dialog",function(e){if(e.keyCode===c.ui.keyCode.TAB){var g=c(":tabbable",this),f=g.filter(":first");g=g.filter(":last");if(e.target===g[0]&&!e.shiftKey){f.focus(1);return false;}else if(e.target===f[0]&&e.shiftKey){g.focus(1);return false;}}});c(a.element.find(":tabbable").get().concat(d.find(".ui-dialog-buttonpane :tabbable").get().concat(d.get()))).eq(0).focus();a._isOpen=true;a._trigger("open");return a;}},_createButtons:function _createButtons(a){var b=this,d=false,e=c("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),g=c("<div></div>").addClass("ui-dialog-buttonset").appendTo(e);b.uiDialog.find(".ui-dialog-buttonpane").remove();(typeof a==="undefined"?"undefined":_typeof(a))==="object"&&a!==null&&c.each(a,function(){return!(d=true);});if(d){c.each(a,function(f,h){h=c.isFunction(h)?{click:h,text:f}:h;var i=c('<button type="button"></button>').click(function(){h.click.apply(b.element[0],arguments);}).appendTo(g);c.each(h,function(j,k){if(j!=="click")j in o?i[j](k):i.attr(j,k);});c.fn.button&&i.button();});e.appendTo(b.uiDialog);}},_makeDraggable:function _makeDraggable(){function a(f){return{position:f.position,offset:f.offset};}var b=this,d=b.options,e=c(document),g;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function start(f,h){g=d.height==="auto"?"auto":c(this).height();c(this).height(c(this).height()).addClass("ui-dialog-dragging");b._trigger("dragStart",f,a(h));},drag:function drag(f,h){b._trigger("drag",f,a(h));},stop:function stop(f,h){d.position=[h.position.left-e.scrollLeft(),h.position.top-e.scrollTop()];c(this).removeClass("ui-dialog-dragging").height(g);b._trigger("dragStop",f,a(h));c.ui.dialog.overlay.resize();}});},_makeResizable:function _makeResizable(a){function b(f){return{originalPosition:f.originalPosition,originalSize:f.originalSize,position:f.position,size:f.size};}a=a===l?this.options.resizable:a;var d=this,e=d.options,g=d.uiDialog.css("position");a=typeof a==="string"?a:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:a,start:function start(f,h){c(this).addClass("ui-dialog-resizing");d._trigger("resizeStart",f,b(h));},resize:function resize(f,h){d._trigger("resize",f,b(h));},stop:function stop(f,h){c(this).removeClass("ui-dialog-resizing");e.height=c(this).height();e.width=c(this).width();d._trigger("resizeStop",f,b(h));c.ui.dialog.overlay.resize();}}).css("position",g).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se");},_minHeight:function _minHeight(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height);},_position:function _position(a){var b=[],d=[0,0],e;if(a){if(typeof a==="string"||(typeof a==="undefined"?"undefined":_typeof(a))==="object"&&"0"in a){b=a.split?a.split(" "):[a[0],a[1]];if(b.length===1)b[1]=b[0];c.each(["left","top"],function(g,f){if(+b[g]===b[g]){d[g]=b[g];b[g]=f;}});a={my:b.join(" "),at:b.join(" "),offset:d.join(" ")};}a=c.extend({},c.ui.dialog.prototype.options.position,a);}else a=c.ui.dialog.prototype.options.position;(e=this.uiDialog.is(":visible"))||this.uiDialog.show();this.uiDialog.css({top:0,left:0}).position(c.extend({of:window},a));e||this.uiDialog.hide();},_setOptions:function _setOptions(a){var b=this,d={},e=false;c.each(a,function(g,f){b._setOption(g,f);if(g in m)e=true;if(g in n)d[g]=f;});e&&this._size();this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option",d);},_setOption:function _setOption(a,b){var d=this,e=d.uiDialog;switch(a){case"beforeclose":a="beforeClose";break;case"buttons":d._createButtons(b);break;case"closeText":d.uiDialogTitlebarCloseText.text(""+b);break;case"dialogClass":e.removeClass(d.options.dialogClass).addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+b);break;case"disabled":b?e.addClass("ui-dialog-disabled"):e.removeClass("ui-dialog-disabled");break;case"draggable":var g=e.is(":data(draggable)");g&&!b&&e.draggable("destroy");!g&&b&&d._makeDraggable();break;case"position":d._position(b);break;case"resizable":(g=e.is(":data(resizable)"))&&!b&&e.resizable("destroy");g&&typeof b==="string"&&e.resizable("option","handles",b);!g&&b!==false&&d._makeResizable(b);break;case"title":c(".ui-dialog-title",d.uiDialogTitlebar).html(""+(b||"&#160;"));break;}c.Widget.prototype._setOption.apply(d,arguments);},_size:function _size(){var a=this.options,b,d,e=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0});if(a.minWidth>a.width)a.width=a.minWidth;b=this.uiDialog.css({height:"auto",width:a.width}).height();d=Math.max(0,a.minHeight-b);if(a.height==="auto"){if(c.support.minHeight)this.element.css({minHeight:d,height:"auto"});else{this.uiDialog.show();a=this.element.css("height","auto").height();e||this.uiDialog.hide();this.element.height(Math.max(a,d));}}else this.element.height(Math.max(a.height-b,0));this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight());}});c.extend(c.ui.dialog,{version:"1.8.16",uuid:0,maxZ:0,getTitleId:function getTitleId(a){a=a.attr("id");if(!a){this.uuid+=1;a=this.uuid;}return"ui-dialog-title-"+a;},overlay:function overlay(a){this.$el=c.ui.dialog.overlay.create(a);}});c.extend(c.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay";}).join(" "),create:function create(a){if(this.instances.length===0){setTimeout(function(){c.ui.dialog.overlay.instances.length&&c(document).bind(c.ui.dialog.overlay.events,function(d){if(c(d.target).zIndex()<c.ui.dialog.overlay.maxZ)return false;});},1);c(document).bind("keydown.dialog-overlay",function(d){if(a.options.closeOnEscape&&!d.isDefaultPrevented()&&d.keyCode&&d.keyCode===c.ui.keyCode.ESCAPE){a.close(d);d.preventDefault();}});c(window).bind("resize.dialog-overlay",c.ui.dialog.overlay.resize);}var b=(this.oldInstances.pop()||c("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});c.fn.bgiframe&&b.bgiframe();this.instances.push(b);return b;},destroy:function destroy(a){var b=c.inArray(a,this.instances);b!=-1&&this.oldInstances.push(this.instances.splice(b,1)[0]);this.instances.length===0&&c([document,window]).unbind(".dialog-overlay");a.remove();var d=0;c.each(this.instances,function(){d=Math.max(d,this.css("z-index"));});this.maxZ=d;},height:function height(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);b=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);return a<b?c(window).height()+"px":a+"px";}else return c(document).height()+"px";},width:function width(){var a,b;if(c.browser.msie){a=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);b=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);return a<b?c(window).width()+"px":a+"px";}else return c(document).width()+"px";},resize:function resize(){var a=c([]);c.each(c.ui.dialog.overlay.instances,function(){a=a.add(this);});a.css({width:0,height:0}).css({width:c.ui.dialog.overlay.width(),height:c.ui.dialog.overlay.height()});}});c.extend(c.ui.dialog.overlay.prototype,{destroy:function destroy(){c.ui.dialog.overlay.destroy(this.$el);}});})(jQuery);;/*
 * jQuery UI Slider 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */(function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function _create(){var a=this,b=this.options,c=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),f=b.values&&b.values.length||1,e=[];this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all"+(b.disabled?" ui-slider-disabled ui-disabled":""));this.range=d([]);if(b.range){if(b.range===true){if(!b.values)b.values=[this._valueMin(),this._valueMin()];if(b.values.length&&b.values.length!==2)b.values=[b.values[0],b.values[0]];}this.range=d("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(b.range==="min"||b.range==="max"?" ui-slider-range-"+b.range:""));}for(var j=c.length;j<f;j+=1){e.push("<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>");}this.handles=c.add(d(e.join("")).appendTo(a.element));this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(g){g.preventDefault();}).hover(function(){b.disabled||d(this).addClass("ui-state-hover");},function(){d(this).removeClass("ui-state-hover");}).focus(function(){if(b.disabled)d(this).blur();else{d(".ui-slider .ui-state-focus").removeClass("ui-state-focus");d(this).addClass("ui-state-focus");}}).blur(function(){d(this).removeClass("ui-state-focus");});this.handles.each(function(g){d(this).data("index.ui-slider-handle",g);});this.handles.keydown(function(g){var k=true,l=d(this).data("index.ui-slider-handle"),i,h,m;if(!a.options.disabled){switch(g.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:k=false;if(!a._keySliding){a._keySliding=true;d(this).addClass("ui-state-active");i=a._start(g,l);if(i===false)return;}break;}m=a.options.step;i=a.options.values&&a.options.values.length?h=a.values(l):h=a.value();switch(g.keyCode){case d.ui.keyCode.HOME:h=a._valueMin();break;case d.ui.keyCode.END:h=a._valueMax();break;case d.ui.keyCode.PAGE_UP:h=a._trimAlignValue(i+(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.PAGE_DOWN:h=a._trimAlignValue(i-(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:if(i===a._valueMax())return;h=a._trimAlignValue(i+m);break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(i===a._valueMin())return;h=a._trimAlignValue(i-m);break;}a._slide(g,l,h);return k;}}).keyup(function(g){var k=d(this).data("index.ui-slider-handle");if(a._keySliding){a._keySliding=false;a._stop(g,k);a._change(g,k);d(this).removeClass("ui-state-active");}});this._refreshValue();this._animateOff=false;},destroy:function destroy(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");this._mouseDestroy();return this;},_mouseCapture:function _mouseCapture(a){var b=this.options,c,f,e,j,g;if(b.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();c=this._normValueFromMouse({x:a.pageX,y:a.pageY});f=this._valueMax()-this._valueMin()+1;j=this;this.handles.each(function(k){var l=Math.abs(c-j.values(k));if(f>l){f=l;e=d(this);g=k;}});if(b.range===true&&this.values(1)===b.min){g+=1;e=d(this.handles[g]);}if(this._start(a,g)===false)return false;this._mouseSliding=true;j._handleIndex=g;e.addClass("ui-state-active").focus();b=e.offset();this._clickOffset=!d(a.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:a.pageX-b.left-e.width()/2,top:a.pageY-b.top-e.height()/2-(parseInt(e.css("borderTopWidth"),10)||0)-(parseInt(e.css("borderBottomWidth"),10)||0)+(parseInt(e.css("marginTop"),10)||0)};this.handles.hasClass("ui-state-hover")||this._slide(a,g,c);return this._animateOff=true;},_mouseStart:function _mouseStart(){return true;},_mouseDrag:function _mouseDrag(a){var b=this._normValueFromMouse({x:a.pageX,y:a.pageY});this._slide(a,this._handleIndex,b);return false;},_mouseStop:function _mouseStop(a){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(a,this._handleIndex);this._change(a,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false;},_detectOrientation:function _detectOrientation(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal";},_normValueFromMouse:function _normValueFromMouse(a){var b;if(this.orientation==="horizontal"){b=this.elementSize.width;a=a.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0);}else{b=this.elementSize.height;a=a.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0);}b=a/b;if(b>1)b=1;if(b<0)b=0;if(this.orientation==="vertical")b=1-b;a=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+b*a);},_start:function _start(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values();}return this._trigger("start",a,c);},_slide:function _slide(a,b,c){var f;if(this.options.values&&this.options.values.length){f=this.values(b?0:1);if(this.options.values.length===2&&this.options.range===true&&(b===0&&c>f||b===1&&c<f))c=f;if(c!==this.values(b)){f=this.values();f[b]=c;a=this._trigger("slide",a,{handle:this.handles[b],value:c,values:f});this.values(b?0:1);a!==false&&this.values(b,c,true);}}else if(c!==this.value()){a=this._trigger("slide",a,{handle:this.handles[b],value:c});a!==false&&this.value(c);}},_stop:function _stop(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values();}this._trigger("stop",a,c);},_change:function _change(a,b){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values();}this._trigger("change",a,c);}},value:function value(a){if(arguments.length){this.options.value=this._trimAlignValue(a);this._refreshValue();this._change(null,0);}else return this._value();},values:function values(a,b){var c,f,e;if(arguments.length>1){this.options.values[a]=this._trimAlignValue(b);this._refreshValue();this._change(null,a);}else if(arguments.length){if(d.isArray(arguments[0])){c=this.options.values;f=arguments[0];for(e=0;e<c.length;e+=1){c[e]=this._trimAlignValue(f[e]);this._change(null,e);}this._refreshValue();}else return this.options.values&&this.options.values.length?this._values(a):this.value();}else return this._values();},_setOption:function _setOption(a,b){var c,f=0;if(d.isArray(this.options.values))f=this.options.values.length;d.Widget.prototype._setOption.apply(this,arguments);switch(a){case"disabled":if(b){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.propAttr("disabled",true);this.element.addClass("ui-disabled");}else{this.handles.propAttr("disabled",false);this.element.removeClass("ui-disabled");}break;case"orientation":this._detectOrientation();this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue();break;case"value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case"values":this._animateOff=true;this._refreshValue();for(c=0;c<f;c+=1){this._change(null,c);}this._animateOff=false;break;}},_value:function _value(){var a=this.options.value;return a=this._trimAlignValue(a);},_values:function _values(a){var b,c;if(arguments.length){b=this.options.values[a];return b=this._trimAlignValue(b);}else{b=this.options.values.slice();for(c=0;c<b.length;c+=1){b[c]=this._trimAlignValue(b[c]);}return b;}},_trimAlignValue:function _trimAlignValue(a){if(a<=this._valueMin())return this._valueMin();if(a>=this._valueMax())return this._valueMax();var b=this.options.step>0?this.options.step:1,c=(a-this._valueMin())%b;a=a-c;if(Math.abs(c)*2>=b)a+=c>0?b:-b;return parseFloat(a.toFixed(5));},_valueMin:function _valueMin(){return this.options.min;},_valueMax:function _valueMax(){return this.options.max;},_refreshValue:function _refreshValue(){var a=this.options.range,b=this.options,c=this,f=!this._animateOff?b.animate:false,e,j={},g,k,l,i;if(this.options.values&&this.options.values.length)this.handles.each(function(h){e=(c.values(h)-c._valueMin())/(c._valueMax()-c._valueMin())*100;j[c.orientation==="horizontal"?"left":"bottom"]=e+"%";d(this).stop(1,1)[f?"animate":"css"](j,b.animate);if(c.options.range===true)if(c.orientation==="horizontal"){if(h===0)c.range.stop(1,1)[f?"animate":"css"]({left:e+"%"},b.animate);if(h===1)c.range[f?"animate":"css"]({width:e-g+"%"},{queue:false,duration:b.animate});}else{if(h===0)c.range.stop(1,1)[f?"animate":"css"]({bottom:e+"%"},b.animate);if(h===1)c.range[f?"animate":"css"]({height:e-g+"%"},{queue:false,duration:b.animate});}g=e;});else{k=this.value();l=this._valueMin();i=this._valueMax();e=i!==l?(k-l)/(i-l)*100:0;j[c.orientation==="horizontal"?"left":"bottom"]=e+"%";this.handle.stop(1,1)[f?"animate":"css"](j,b.animate);if(a==="min"&&this.orientation==="horizontal")this.range.stop(1,1)[f?"animate":"css"]({width:e+"%"},b.animate);if(a==="max"&&this.orientation==="horizontal")this.range[f?"animate":"css"]({width:100-e+"%"},{queue:false,duration:b.animate});if(a==="min"&&this.orientation==="vertical")this.range.stop(1,1)[f?"animate":"css"]({height:e+"%"},b.animate);if(a==="max"&&this.orientation==="vertical")this.range[f?"animate":"css"]({height:100-e+"%"},{queue:false,duration:b.animate});}}});d.extend(d.ui.slider,{version:"1.8.16"});})(jQuery);;/*
 * jQuery UI Tabs 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */(function(d,p){function u(){return++v;}function w(){return++x;}var v=0,x=0;d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading&#8230;</em>",tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},_create:function _create(){this._tabify(true);},_setOption:function _setOption(b,e){if(b=="selected")this.options.collapsible&&e==this.options.selected||this.select(e);else{this.options[b]=e;this._tabify();}},_tabId:function _tabId(b){return b.title&&b.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+u();},_sanitizeSelector:function _sanitizeSelector(b){return b.replace(/:/g,"\\:");},_cookie:function _cookie(){var b=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+w());return d.cookie.apply(null,[b].concat(d.makeArray(arguments)));},_ui:function _ui(b,e){return{tab:b,panel:e,index:this.anchors.index(b)};},_cleanup:function _cleanup(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var b=d(this);b.html(b.data("label.tabs")).removeData("label.tabs");});},_tabify:function _tabify(b){function e(g,f){g.css("display","");!d.support.opacity&&f.opacity&&g[0].style.removeAttribute("filter");}var a=this,c=this.options,h=/^#.+/;this.list=this.element.find("ol,ul").eq(0);this.lis=d(" > li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0];});this.panels=d([]);this.anchors.each(function(g,f){var i=d(f).attr("href"),l=i.split("#")[0],q;if(l&&(l===location.toString().split("#")[0]||(q=d("base")[0])&&l===q.href)){i=f.hash;f.href=i;}if(h.test(i))a.panels=a.panels.add(a.element.find(a._sanitizeSelector(i)));else if(i&&i!=="#"){d.data(f,"href.tabs",i);d.data(f,"load.tabs",i.replace(/#.*$/,""));i=a._tabId(f);f.href="#"+i;f=a.element.find("#"+i);if(!f.length){f=d(c.panelTemplate).attr("id",i).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(a.panels[g-1]||a.list);f.data("destroy.tabs",true);}a.panels=a.panels.add(f);}else c.disabled.push(g);});if(b){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(c.selected===p){location.hash&&this.anchors.each(function(g,f){if(f.hash==location.hash){c.selected=g;return false;}});if(typeof c.selected!=="number"&&c.cookie)c.selected=parseInt(a._cookie(),10);if(typeof c.selected!=="number"&&this.lis.filter(".ui-tabs-selected").length)c.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"));c.selected=c.selected||(this.lis.length?0:-1);}else if(c.selected===null)c.selected=-1;c.selected=c.selected>=0&&this.anchors[c.selected]||c.selected<0?c.selected:0;c.disabled=d.unique(c.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(g){return a.lis.index(g);}))).sort();d.inArray(c.selected,c.disabled)!=-1&&c.disabled.splice(d.inArray(c.selected,c.disabled),1);this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");if(c.selected>=0&&this.anchors.length){a.element.find(a._sanitizeSelector(a.anchors[c.selected].hash)).removeClass("ui-tabs-hide");this.lis.eq(c.selected).addClass("ui-tabs-selected ui-state-active");a.element.queue("tabs",function(){a._trigger("show",null,a._ui(a.anchors[c.selected],a.element.find(a._sanitizeSelector(a.anchors[c.selected].hash))[0]));});this.load(c.selected);}d(window).bind("unload",function(){a.lis.add(a.anchors).unbind(".tabs");a.lis=a.anchors=a.panels=null;});}else c.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"));this.element[c.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible");c.cookie&&this._cookie(c.selected,c.cookie);b=0;for(var j;j=this.lis[b];b++){d(j)[d.inArray(b,c.disabled)!=-1&&!d(j).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");}c.cache===false&&this.anchors.removeData("cache.tabs");this.lis.add(this.anchors).unbind(".tabs");if(c.event!=="mouseover"){var k=function k(g,f){f.is(":not(.ui-state-disabled)")&&f.addClass("ui-state-"+g);},n=function n(g,f){f.removeClass("ui-state-"+g);};this.lis.bind("mouseover.tabs",function(){k("hover",d(this));});this.lis.bind("mouseout.tabs",function(){n("hover",d(this));});this.anchors.bind("focus.tabs",function(){k("focus",d(this).closest("li"));});this.anchors.bind("blur.tabs",function(){n("focus",d(this).closest("li"));});}var m,o;if(c.fx)if(d.isArray(c.fx)){m=c.fx[0];o=c.fx[1];}else m=o=c.fx;var r=o?function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.hide().removeClass("ui-tabs-hide").animate(o,o.duration||"normal",function(){e(f,o);a._trigger("show",null,a._ui(g,f[0]));});}:function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");a._trigger("show",null,a._ui(g,f[0]));},s=m?function(g,f){f.animate(m,m.duration||"normal",function(){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");e(f,m);a.element.dequeue("tabs");});}:function(g,f){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");a.element.dequeue("tabs");};this.anchors.bind(c.event+".tabs",function(){var g=this,f=d(g).closest("li"),i=a.panels.filter(":not(.ui-tabs-hide)"),l=a.element.find(a._sanitizeSelector(g.hash));if(f.hasClass("ui-tabs-selected")&&!c.collapsible||f.hasClass("ui-state-disabled")||f.hasClass("ui-state-processing")||a.panels.filter(":animated").length||a._trigger("select",null,a._ui(this,l[0]))===false){this.blur();return false;}c.selected=a.anchors.index(this);a.abort();if(c.collapsible)if(f.hasClass("ui-tabs-selected")){c.selected=-1;c.cookie&&a._cookie(c.selected,c.cookie);a.element.queue("tabs",function(){s(g,i);}).dequeue("tabs");this.blur();return false;}else if(!i.length){c.cookie&&a._cookie(c.selected,c.cookie);a.element.queue("tabs",function(){r(g,l);});a.load(a.anchors.index(this));this.blur();return false;}c.cookie&&a._cookie(c.selected,c.cookie);if(l.length){i.length&&a.element.queue("tabs",function(){s(g,i);});a.element.queue("tabs",function(){r(g,l);});a.load(a.anchors.index(this));}else throw"jQuery UI Tabs: Mismatching fragment identifier.";d.browser.msie&&this.blur();});this.anchors.bind("click.tabs",function(){return false;});},_getIndex:function _getIndex(b){if(typeof b=="string")b=this.anchors.index(this.anchors.filter("[href$="+b+"]"));return b;},destroy:function destroy(){var b=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var e=d.data(this,"href.tabs");if(e)this.href=e;var a=d(this).unbind(".tabs");d.each(["href","load","cache"],function(c,h){a.removeData(h+".tabs");});});this.lis.unbind(".tabs").add(this.panels).each(function(){d.data(this,"destroy.tabs")?d(this).remove():d(this).removeClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-hover ui-state-focus ui-state-disabled ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");});b.cookie&&this._cookie(null,b.cookie);return this;},add:function add(b,e,a){if(a===p)a=this.anchors.length;var c=this,h=this.options;e=d(h.tabTemplate.replace(/#\{href\}/g,b).replace(/#\{label\}/g,e));b=!b.indexOf("#")?b.replace("#",""):this._tabId(d("a",e)[0]);e.addClass("ui-state-default ui-corner-top").data("destroy.tabs",true);var j=c.element.find("#"+b);j.length||(j=d(h.panelTemplate).attr("id",b).data("destroy.tabs",true));j.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(a>=this.lis.length){e.appendTo(this.list);j.appendTo(this.list[0].parentNode);}else{e.insertBefore(this.lis[a]);j.insertBefore(this.panels[a]);}h.disabled=d.map(h.disabled,function(k){return k>=a?++k:k;});this._tabify();if(this.anchors.length==1){h.selected=0;e.addClass("ui-tabs-selected ui-state-active");j.removeClass("ui-tabs-hide");this.element.queue("tabs",function(){c._trigger("show",null,c._ui(c.anchors[0],c.panels[0]));});this.load(0);}this._trigger("add",null,this._ui(this.anchors[a],this.panels[a]));return this;},remove:function remove(b){b=this._getIndex(b);var e=this.options,a=this.lis.eq(b).remove(),c=this.panels.eq(b).remove();if(a.hasClass("ui-tabs-selected")&&this.anchors.length>1)this.select(b+(b+1<this.anchors.length?1:-1));e.disabled=d.map(d.grep(e.disabled,function(h){return h!=b;}),function(h){return h>=b?--h:h;});this._tabify();this._trigger("remove",null,this._ui(a.find("a")[0],c[0]));return this;},enable:function enable(b){b=this._getIndex(b);var e=this.options;if(d.inArray(b,e.disabled)!=-1){this.lis.eq(b).removeClass("ui-state-disabled");e.disabled=d.grep(e.disabled,function(a){return a!=b;});this._trigger("enable",null,this._ui(this.anchors[b],this.panels[b]));return this;}},disable:function disable(b){b=this._getIndex(b);var e=this.options;if(b!=e.selected){this.lis.eq(b).addClass("ui-state-disabled");e.disabled.push(b);e.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[b],this.panels[b]));}return this;},select:function select(b){b=this._getIndex(b);if(b==-1)if(this.options.collapsible&&this.options.selected!=-1)b=this.options.selected;else return this;this.anchors.eq(b).trigger(this.options.event+".tabs");return this;},load:function load(b){b=this._getIndex(b);var e=this,a=this.options,c=this.anchors.eq(b)[0],h=d.data(c,"load.tabs");this.abort();if(!h||this.element.queue("tabs").length!==0&&d.data(c,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(b).addClass("ui-state-processing");if(a.spinner){var j=d("span",c);j.data("label.tabs",j.html()).html(a.spinner);}this.xhr=d.ajax(d.extend({},a.ajaxOptions,{url:h,success:function success(k,n){e.element.find(e._sanitizeSelector(c.hash)).html(k);e._cleanup();a.cache&&d.data(c,"cache.tabs",true);e._trigger("load",null,e._ui(e.anchors[b],e.panels[b]));try{a.ajaxOptions.success(k,n);}catch(m){}},error:function error(k,n){e._cleanup();e._trigger("load",null,e._ui(e.anchors[b],e.panels[b]));try{a.ajaxOptions.error(k,n,b,c);}catch(m){}}}));e.element.dequeue("tabs");return this;}},abort:function abort(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr;}this._cleanup();return this;},url:function url(b,e){this.anchors.eq(b).removeData("cache.tabs").data("load.tabs",e);return this;},length:function length(){return this.anchors.length;}});d.extend(d.ui.tabs,{version:"1.8.16"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function rotate(b,e){var a=this,c=this.options,h=a._rotate||(a._rotate=function(j){clearTimeout(a.rotation);a.rotation=setTimeout(function(){var k=c.selected;a.select(++k<a.anchors.length?k:0);},b);j&&j.stopPropagation();});e=a._unrotate||(a._unrotate=!e?function(j){j.clientX&&a.rotate(null);}:function(){t=c.selected;h();});if(b){this.element.bind("tabsshow",h);this.anchors.bind(c.event+".tabs",e);h();}else{clearTimeout(a.rotation);this.element.unbind("tabsshow",h);this.anchors.unbind(c.event+".tabs",e);delete this._rotate;delete this._unrotate;}return this;}});})(jQuery);;/*
 * jQuery UI Datepicker 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	jquery.ui.core.js
 */(function(d,C){function M(){this.debug=false;this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._inDialog=this._datepickerShowing=false;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current-day";this._dayOverClass="ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:false,showMonthAfterYear:false,yearSuffix:""};this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,gotoCurrent:false,changeMonth:false,changeYear:false,yearRange:"c-10:c+10",showOtherMonths:false,selectOtherMonths:false,showWeek:false,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:true,showButtonPanel:false,autoSize:false,disabled:false};d.extend(this._defaults,this.regional[""]);this.dpDiv=N(d('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'));}function N(a){return a.bind("mouseout",function(b){b=d(b.target).closest("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a");b.length&&b.removeClass("ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover");}).bind("mouseover",function(b){b=d(b.target).closest("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a");if(!(d.datepicker._isDisabledDatepicker(J.inline?a.parent()[0]:J.input[0])||!b.length)){b.parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");b.addClass("ui-state-hover");b.hasClass("ui-datepicker-prev")&&b.addClass("ui-datepicker-prev-hover");b.hasClass("ui-datepicker-next")&&b.addClass("ui-datepicker-next-hover");}});}function H(a,b){d.extend(a,b);for(var c in b){if(b[c]==null||b[c]==C)a[c]=b[c];}return a;}d.extend(d.ui,{datepicker:{version:"1.8.16"}});var B=new Date().getTime(),J;d.extend(M.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function log(){this.debug&&console.log.apply("",arguments);},_widgetDatepicker:function _widgetDatepicker(){return this.dpDiv;},setDefaults:function setDefaults(a){H(this._defaults,a||{});return this;},_attachDatepicker:function _attachDatepicker(a,b){var c=null;for(var e in this._defaults){var f=a.getAttribute("date:"+e);if(f){c=c||{};try{c[e]=eval(f);}catch(h){c[e]=f;}}}e=a.nodeName.toLowerCase();f=e=="div"||e=="span";if(!a.id){this.uuid+=1;a.id="dp"+this.uuid;}var i=this._newInst(d(a),f);i.settings=d.extend({},b||{},c||{});if(e=="input")this._connectDatepicker(a,i);else f&&this._inlineDatepicker(a,i);},_newInst:function _newInst(a,b){return{id:a[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1"),input:a,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:b,dpDiv:!b?this.dpDiv:N(d('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};},_connectDatepicker:function _connectDatepicker(a,b){var c=d(a);b.append=d([]);b.trigger=d([]);if(!c.hasClass(this.markerClassName)){this._attachments(c,b);c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(e,f,h){b.settings[f]=h;}).bind("getData.datepicker",function(e,f){return this._get(b,f);});this._autoSize(b);d.data(a,"datepicker",b);b.settings.disabled&&this._disableDatepicker(a);}},_attachments:function _attachments(a,b){var c=this._get(b,"appendText"),e=this._get(b,"isRTL");b.append&&b.append.remove();if(c){b.append=d('<span class="'+this._appendClass+'">'+c+"</span>");a[e?"before":"after"](b.append);}a.unbind("focus",this._showDatepicker);b.trigger&&b.trigger.remove();c=this._get(b,"showOn");if(c=="focus"||c=="both")a.focus(this._showDatepicker);if(c=="button"||c=="both"){c=this._get(b,"buttonText");var f=this._get(b,"buttonImage");b.trigger=d(this._get(b,"buttonImageOnly")?d("<img/>").addClass(this._triggerClass).attr({src:f,alt:c,title:c}):d('<button type="button"></button>').addClass(this._triggerClass).html(f==""?c:d("<img/>").attr({src:f,alt:c,title:c})));a[e?"before":"after"](b.trigger);b.trigger.click(function(){d.datepicker._datepickerShowing&&d.datepicker._lastInput==a[0]?d.datepicker._hideDatepicker():d.datepicker._showDatepicker(a[0]);return false;});}},_autoSize:function _autoSize(a){if(this._get(a,"autoSize")&&!a.inline){var b=new Date(2009,11,20),c=this._get(a,"dateFormat");if(c.match(/[DM]/)){var e=function e(f){for(var h=0,i=0,g=0;g<f.length;g++){if(f[g].length>h){h=f[g].length;i=g;}}return i;};b.setMonth(e(this._get(a,c.match(/MM/)?"monthNames":"monthNamesShort")));b.setDate(e(this._get(a,c.match(/DD/)?"dayNames":"dayNamesShort"))+20-b.getDay());}a.input.attr("size",this._formatDate(a,b).length);}},_inlineDatepicker:function _inlineDatepicker(a,b){var c=d(a);if(!c.hasClass(this.markerClassName)){c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function(e,f,h){b.settings[f]=h;}).bind("getData.datepicker",function(e,f){return this._get(b,f);});d.data(a,"datepicker",b);this._setDate(b,this._getDefaultDate(b),true);this._updateDatepicker(b);this._updateAlternate(b);b.settings.disabled&&this._disableDatepicker(a);b.dpDiv.css("display","block");}},_dialogDatepicker:function _dialogDatepicker(a,b,c,e,f){a=this._dialogInst;if(!a){this.uuid+=1;this._dialogInput=d('<input type="text" id="'+("dp"+this.uuid)+'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>');this._dialogInput.keydown(this._doKeyDown);d("body").append(this._dialogInput);a=this._dialogInst=this._newInst(this._dialogInput,false);a.settings={};d.data(this._dialogInput[0],"datepicker",a);}H(a.settings,e||{});b=b&&b.constructor==Date?this._formatDate(a,b):b;this._dialogInput.val(b);this._pos=f?f.length?f:[f.pageX,f.pageY]:null;if(!this._pos)this._pos=[document.documentElement.clientWidth/2-100+(document.documentElement.scrollLeft||document.body.scrollLeft),document.documentElement.clientHeight/2-150+(document.documentElement.scrollTop||document.body.scrollTop)];this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px");a.settings.onSelect=c;this._inDialog=true;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]);d.blockUI&&d.blockUI(this.dpDiv);d.data(this._dialogInput[0],"datepicker",a);return this;},_destroyDatepicker:function _destroyDatepicker(a){var b=d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();d.removeData(a,"datepicker");if(e=="input"){c.append.remove();c.trigger.remove();b.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp);}else if(e=="div"||e=="span")b.removeClass(this.markerClassName).empty();}},_enableDatepicker:function _enableDatepicker(a){var b=d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();if(e=="input"){a.disabled=false;c.trigger.filter("button").each(function(){this.disabled=false;}).end().filter("img").css({opacity:"1.0",cursor:""});}else if(e=="div"||e=="span"){b=b.children("."+this._inlineClass);b.children().removeClass("ui-state-disabled");b.find("select.ui-datepicker-month, select.ui-datepicker-year").removeAttr("disabled");}this._disabledInputs=d.map(this._disabledInputs,function(f){return f==a?null:f;});}},_disableDatepicker:function _disableDatepicker(a){var b=d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();if(e=="input"){a.disabled=true;c.trigger.filter("button").each(function(){this.disabled=true;}).end().filter("img").css({opacity:"0.5",cursor:"default"});}else if(e=="div"||e=="span"){b=b.children("."+this._inlineClass);b.children().addClass("ui-state-disabled");b.find("select.ui-datepicker-month, select.ui-datepicker-year").attr("disabled","disabled");}this._disabledInputs=d.map(this._disabledInputs,function(f){return f==a?null:f;});this._disabledInputs[this._disabledInputs.length]=a;}},_isDisabledDatepicker:function _isDisabledDatepicker(a){if(!a)return false;for(var b=0;b<this._disabledInputs.length;b++){if(this._disabledInputs[b]==a)return true;}return false;},_getInst:function _getInst(a){try{return d.data(a,"datepicker");}catch(b){throw"Missing instance data for this datepicker";}},_optionDatepicker:function _optionDatepicker(a,b,c){var e=this._getInst(a);if(arguments.length==2&&typeof b=="string")return b=="defaults"?d.extend({},d.datepicker._defaults):e?b=="all"?d.extend({},e.settings):this._get(e,b):null;var f=b||{};if(typeof b=="string"){f={};f[b]=c;}if(e){this._curInst==e&&this._hideDatepicker();var h=this._getDateDatepicker(a,true),i=this._getMinMaxDate(e,"min"),g=this._getMinMaxDate(e,"max");H(e.settings,f);if(i!==null&&f.dateFormat!==C&&f.minDate===C)e.settings.minDate=this._formatDate(e,i);if(g!==null&&f.dateFormat!==C&&f.maxDate===C)e.settings.maxDate=this._formatDate(e,g);this._attachments(d(a),e);this._autoSize(e);this._setDate(e,h);this._updateAlternate(e);this._updateDatepicker(e);}},_changeDatepicker:function _changeDatepicker(a,b,c){this._optionDatepicker(a,b,c);},_refreshDatepicker:function _refreshDatepicker(a){(a=this._getInst(a))&&this._updateDatepicker(a);},_setDateDatepicker:function _setDateDatepicker(a,b){if(a=this._getInst(a)){this._setDate(a,b);this._updateDatepicker(a);this._updateAlternate(a);}},_getDateDatepicker:function _getDateDatepicker(a,b){(a=this._getInst(a))&&!a.inline&&this._setDateFromField(a,b);return a?this._getDate(a):null;},_doKeyDown:function _doKeyDown(a){var b=d.datepicker._getInst(a.target),c=true,e=b.dpDiv.is(".ui-datepicker-rtl");b._keyEvent=true;if(d.datepicker._datepickerShowing)switch(a.keyCode){case 9:d.datepicker._hideDatepicker();c=false;break;case 13:c=d("td."+d.datepicker._dayOverClass+":not(."+d.datepicker._currentClass+")",b.dpDiv);c[0]&&d.datepicker._selectDay(a.target,b.selectedMonth,b.selectedYear,c[0]);if(a=d.datepicker._get(b,"onSelect")){c=d.datepicker._formatDate(b);a.apply(b.input?b.input[0]:null,[c,b]);}else d.datepicker._hideDatepicker();return false;case 27:d.datepicker._hideDatepicker();break;case 33:d.datepicker._adjustDate(a.target,a.ctrlKey?-d.datepicker._get(b,"stepBigMonths"):-d.datepicker._get(b,"stepMonths"),"M");break;case 34:d.datepicker._adjustDate(a.target,a.ctrlKey?+d.datepicker._get(b,"stepBigMonths"):+d.datepicker._get(b,"stepMonths"),"M");break;case 35:if(a.ctrlKey||a.metaKey)d.datepicker._clearDate(a.target);c=a.ctrlKey||a.metaKey;break;case 36:if(a.ctrlKey||a.metaKey)d.datepicker._gotoToday(a.target);c=a.ctrlKey||a.metaKey;break;case 37:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,e?+1:-1,"D");c=a.ctrlKey||a.metaKey;if(a.originalEvent.altKey)d.datepicker._adjustDate(a.target,a.ctrlKey?-d.datepicker._get(b,"stepBigMonths"):-d.datepicker._get(b,"stepMonths"),"M");break;case 38:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,-7,"D");c=a.ctrlKey||a.metaKey;break;case 39:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,e?-1:+1,"D");c=a.ctrlKey||a.metaKey;if(a.originalEvent.altKey)d.datepicker._adjustDate(a.target,a.ctrlKey?+d.datepicker._get(b,"stepBigMonths"):+d.datepicker._get(b,"stepMonths"),"M");break;case 40:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,+7,"D");c=a.ctrlKey||a.metaKey;break;default:c=false;}else if(a.keyCode==36&&a.ctrlKey)d.datepicker._showDatepicker(this);else c=false;if(c){a.preventDefault();a.stopPropagation();}},_doKeyPress:function _doKeyPress(a){var b=d.datepicker._getInst(a.target);if(d.datepicker._get(b,"constrainInput")){b=d.datepicker._possibleChars(d.datepicker._get(b,"dateFormat"));var c=String.fromCharCode(a.charCode==C?a.keyCode:a.charCode);return a.ctrlKey||a.metaKey||c<" "||!b||b.indexOf(c)>-1;}},_doKeyUp:function _doKeyUp(a){a=d.datepicker._getInst(a.target);if(a.input.val()!=a.lastVal)try{if(d.datepicker.parseDate(d.datepicker._get(a,"dateFormat"),a.input?a.input.val():null,d.datepicker._getFormatConfig(a))){d.datepicker._setDateFromField(a);d.datepicker._updateAlternate(a);d.datepicker._updateDatepicker(a);}}catch(b){d.datepicker.log(b);}return true;},_showDatepicker:function _showDatepicker(a){a=a.target||a;if(a.nodeName.toLowerCase()!="input")a=d("input",a.parentNode)[0];if(!(d.datepicker._isDisabledDatepicker(a)||d.datepicker._lastInput==a)){var b=d.datepicker._getInst(a);if(d.datepicker._curInst&&d.datepicker._curInst!=b){d.datepicker._datepickerShowing&&d.datepicker._triggerOnClose(d.datepicker._curInst);d.datepicker._curInst.dpDiv.stop(true,true);}var c=d.datepicker._get(b,"beforeShow");c=c?c.apply(a,[a,b]):{};if(c!==false){H(b.settings,c);b.lastVal=null;d.datepicker._lastInput=a;d.datepicker._setDateFromField(b);if(d.datepicker._inDialog)a.value="";if(!d.datepicker._pos){d.datepicker._pos=d.datepicker._findPos(a);d.datepicker._pos[1]+=a.offsetHeight;}var e=false;d(a).parents().each(function(){e|=d(this).css("position")=="fixed";return!e;});if(e&&d.browser.opera){d.datepicker._pos[0]-=document.documentElement.scrollLeft;d.datepicker._pos[1]-=document.documentElement.scrollTop;}c={left:d.datepicker._pos[0],top:d.datepicker._pos[1]};d.datepicker._pos=null;b.dpDiv.empty();b.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});d.datepicker._updateDatepicker(b);c=d.datepicker._checkOffset(b,c,e);b.dpDiv.css({position:d.datepicker._inDialog&&d.blockUI?"static":e?"fixed":"absolute",display:"none",left:c.left+"px",top:c.top+"px"});if(!b.inline){c=d.datepicker._get(b,"showAnim");var f=d.datepicker._get(b,"duration"),h=function h(){var i=b.dpDiv.find("iframe.ui-datepicker-cover");if(i.length){var g=d.datepicker._getBorders(b.dpDiv);i.css({left:-g[0],top:-g[1],width:b.dpDiv.outerWidth(),height:b.dpDiv.outerHeight()});}};b.dpDiv.zIndex(d(a).zIndex()+1);d.datepicker._datepickerShowing=true;d.effects&&d.effects[c]?b.dpDiv.show(c,d.datepicker._get(b,"showOptions"),f,h):b.dpDiv[c||"show"](c?f:null,h);if(!c||!f)h();b.input.is(":visible")&&!b.input.is(":disabled")&&b.input.focus();d.datepicker._curInst=b;}}}},_updateDatepicker:function _updateDatepicker(a){this.maxRows=4;var b=d.datepicker._getBorders(a.dpDiv);J=a;a.dpDiv.empty().append(this._generateHTML(a));var c=a.dpDiv.find("iframe.ui-datepicker-cover");c.length&&c.css({left:-b[0],top:-b[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()});a.dpDiv.find("."+this._dayOverClass+" a").mouseover();b=this._getNumberOfMonths(a);c=b[1];a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");c>1&&a.dpDiv.addClass("ui-datepicker-multi-"+c).css("width",17*c+"em");a.dpDiv[(b[0]!=1||b[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi");a.dpDiv[(this._get(a,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl");a==d.datepicker._curInst&&d.datepicker._datepickerShowing&&a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&a.input[0]!=document.activeElement&&a.input.focus();if(a.yearshtml){var e=a.yearshtml;setTimeout(function(){e===a.yearshtml&&a.yearshtml&&a.dpDiv.find("select.ui-datepicker-year:first").replaceWith(a.yearshtml);e=a.yearshtml=null;},0);}},_getBorders:function _getBorders(a){var b=function b(c){return{thin:1,medium:2,thick:3}[c]||c;};return[parseFloat(b(a.css("border-left-width"))),parseFloat(b(a.css("border-top-width")))];},_checkOffset:function _checkOffset(a,b,c){var e=a.dpDiv.outerWidth(),f=a.dpDiv.outerHeight(),h=a.input?a.input.outerWidth():0,i=a.input?a.input.outerHeight():0,g=document.documentElement.clientWidth+d(document).scrollLeft(),j=document.documentElement.clientHeight+d(document).scrollTop();b.left-=this._get(a,"isRTL")?e-h:0;b.left-=c&&b.left==a.input.offset().left?d(document).scrollLeft():0;b.top-=c&&b.top==a.input.offset().top+i?d(document).scrollTop():0;b.left-=Math.min(b.left,b.left+e>g&&g>e?Math.abs(b.left+e-g):0);b.top-=Math.min(b.top,b.top+f>j&&j>f?Math.abs(f+i):0);return b;},_findPos:function _findPos(a){for(var b=this._get(this._getInst(a),"isRTL");a&&(a.type=="hidden"||a.nodeType!=1||d.expr.filters.hidden(a));){a=a[b?"previousSibling":"nextSibling"];}a=d(a).offset();return[a.left,a.top];},_triggerOnClose:function _triggerOnClose(a){var b=this._get(a,"onClose");if(b)b.apply(a.input?a.input[0]:null,[a.input?a.input.val():"",a]);},_hideDatepicker:function _hideDatepicker(a){var b=this._curInst;if(!(!b||a&&b!=d.data(a,"datepicker")))if(this._datepickerShowing){a=this._get(b,"showAnim");var c=this._get(b,"duration"),e=function e(){d.datepicker._tidyDialog(b);this._curInst=null;};d.effects&&d.effects[a]?b.dpDiv.hide(a,d.datepicker._get(b,"showOptions"),c,e):b.dpDiv[a=="slideDown"?"slideUp":a=="fadeIn"?"fadeOut":"hide"](a?c:null,e);a||e();d.datepicker._triggerOnClose(b);this._datepickerShowing=false;this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if(d.blockUI){d.unblockUI();d("body").append(this.dpDiv);}}this._inDialog=false;}},_tidyDialog:function _tidyDialog(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");},_checkExternalClick:function _checkExternalClick(a){if(d.datepicker._curInst){a=d(a.target);a[0].id!=d.datepicker._mainDivId&&a.parents("#"+d.datepicker._mainDivId).length==0&&!a.hasClass(d.datepicker.markerClassName)&&!a.hasClass(d.datepicker._triggerClass)&&d.datepicker._datepickerShowing&&!(d.datepicker._inDialog&&d.blockUI)&&d.datepicker._hideDatepicker();}},_adjustDate:function _adjustDate(a,b,c){a=d(a);var e=this._getInst(a[0]);if(!this._isDisabledDatepicker(a[0])){this._adjustInstDate(e,b+(c=="M"?this._get(e,"showCurrentAtPos"):0),c);this._updateDatepicker(e);}},_gotoToday:function _gotoToday(a){a=d(a);var b=this._getInst(a[0]);if(this._get(b,"gotoCurrent")&&b.currentDay){b.selectedDay=b.currentDay;b.drawMonth=b.selectedMonth=b.currentMonth;b.drawYear=b.selectedYear=b.currentYear;}else{var c=new Date();b.selectedDay=c.getDate();b.drawMonth=b.selectedMonth=c.getMonth();b.drawYear=b.selectedYear=c.getFullYear();}this._notifyChange(b);this._adjustDate(a);},_selectMonthYear:function _selectMonthYear(a,b,c){a=d(a);var e=this._getInst(a[0]);e["selected"+(c=="M"?"Month":"Year")]=e["draw"+(c=="M"?"Month":"Year")]=parseInt(b.options[b.selectedIndex].value,10);this._notifyChange(e);this._adjustDate(a);},_selectDay:function _selectDay(a,b,c,e){var f=d(a);if(!(d(e).hasClass(this._unselectableClass)||this._isDisabledDatepicker(f[0]))){f=this._getInst(f[0]);f.selectedDay=f.currentDay=d("a",e).html();f.selectedMonth=f.currentMonth=b;f.selectedYear=f.currentYear=c;this._selectDate(a,this._formatDate(f,f.currentDay,f.currentMonth,f.currentYear));}},_clearDate:function _clearDate(a){a=d(a);this._getInst(a[0]);this._selectDate(a,"");},_selectDate:function _selectDate(a,b){a=this._getInst(d(a)[0]);b=b!=null?b:this._formatDate(a);a.input&&a.input.val(b);this._updateAlternate(a);var c=this._get(a,"onSelect");if(c)c.apply(a.input?a.input[0]:null,[b,a]);else a.input&&a.input.trigger("change");if(a.inline)this._updateDatepicker(a);else{this._hideDatepicker();this._lastInput=a.input[0];_typeof(a.input[0])!="object"&&a.input.focus();this._lastInput=null;}},_updateAlternate:function _updateAlternate(a){var b=this._get(a,"altField");if(b){var c=this._get(a,"altFormat")||this._get(a,"dateFormat"),e=this._getDate(a),f=this.formatDate(c,e,this._getFormatConfig(a));d(b).each(function(){d(this).val(f);});}},noWeekends:function noWeekends(a){a=a.getDay();return[a>0&&a<6,""];},iso8601Week:function iso8601Week(a){a=new Date(a.getTime());a.setDate(a.getDate()+4-(a.getDay()||7));var b=a.getTime();a.setMonth(0);a.setDate(1);return Math.floor(Math.round((b-a)/864E5)/7)+1;},parseDate:function parseDate(a,b,c){if(a==null||b==null)throw"Invalid arguments";b=(typeof b==="undefined"?"undefined":_typeof(b))=="object"?b.toString():b+"";if(b=="")return null;var e=(c?c.shortYearCutoff:null)||this._defaults.shortYearCutoff;e=typeof e!="string"?e:new Date().getFullYear()%100+parseInt(e,10);for(var f=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,h=(c?c.dayNames:null)||this._defaults.dayNames,i=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,g=(c?c.monthNames:null)||this._defaults.monthNames,j=c=-1,l=-1,u=-1,k=false,o=function o(p){(p=A+1<a.length&&a.charAt(A+1)==p)&&A++;return p;},m=function m(p){var D=o(p);p=new RegExp("^\\d{1,"+(p=="@"?14:p=="!"?20:p=="y"&&D?4:p=="o"?3:2)+"}");p=b.substring(q).match(p);if(!p)throw"Missing number at position "+q;q+=p[0].length;return parseInt(p[0],10);},n=function n(p,D,K){p=d.map(o(p)?K:D,function(w,x){return[[x,w]];}).sort(function(w,x){return-(w[1].length-x[1].length);});var E=-1;d.each(p,function(w,x){w=x[1];if(b.substr(q,w.length).toLowerCase()==w.toLowerCase()){E=x[0];q+=w.length;return false;}});if(E!=-1)return E+1;else throw"Unknown name at position "+q;},s=function s(){if(b.charAt(q)!=a.charAt(A))throw"Unexpected literal at position "+q;q++;},q=0,A=0;A<a.length;A++){if(k){if(a.charAt(A)=="'"&&!o("'"))k=false;else s();}else switch(a.charAt(A)){case"d":l=m("d");break;case"D":n("D",f,h);break;case"o":u=m("o");break;case"m":j=m("m");break;case"M":j=n("M",i,g);break;case"y":c=m("y");break;case"@":var v=new Date(m("@"));c=v.getFullYear();j=v.getMonth()+1;l=v.getDate();break;case"!":v=new Date((m("!")-this._ticksTo1970)/1E4);c=v.getFullYear();j=v.getMonth()+1;l=v.getDate();break;case"'":if(o("'"))s();else k=true;break;default:s();}}if(q<b.length)throw"Extra/unparsed characters found in date: "+b.substring(q);if(c==-1)c=new Date().getFullYear();else if(c<100)c+=new Date().getFullYear()-new Date().getFullYear()%100+(c<=e?0:-100);if(u>-1){j=1;l=u;do{e=this._getDaysInMonth(c,j-1);if(l<=e)break;j++;l-=e;}while(1);}v=this._daylightSavingAdjust(new Date(c,j-1,l));if(v.getFullYear()!=c||v.getMonth()+1!=j||v.getDate()!=l)throw"Invalid date";return v;},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1E7,formatDate:function formatDate(a,b,c){if(!b)return"";var e=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,f=(c?c.dayNames:null)||this._defaults.dayNames,h=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort;c=(c?c.monthNames:null)||this._defaults.monthNames;var i=function i(o){(o=k+1<a.length&&a.charAt(k+1)==o)&&k++;return o;},g=function g(o,m,n){m=""+m;if(i(o))for(;m.length<n;){m="0"+m;}return m;},j=function j(o,m,n,s){return i(o)?s[m]:n[m];},l="",u=false;if(b)for(var k=0;k<a.length;k++){if(u){if(a.charAt(k)=="'"&&!i("'"))u=false;else l+=a.charAt(k);}else switch(a.charAt(k)){case"d":l+=g("d",b.getDate(),2);break;case"D":l+=j("D",b.getDay(),e,f);break;case"o":l+=g("o",Math.round((new Date(b.getFullYear(),b.getMonth(),b.getDate()).getTime()-new Date(b.getFullYear(),0,0).getTime())/864E5),3);break;case"m":l+=g("m",b.getMonth()+1,2);break;case"M":l+=j("M",b.getMonth(),h,c);break;case"y":l+=i("y")?b.getFullYear():(b.getYear()%100<10?"0":"")+b.getYear()%100;break;case"@":l+=b.getTime();break;case"!":l+=b.getTime()*1E4+this._ticksTo1970;break;case"'":if(i("'"))l+="'";else u=true;break;default:l+=a.charAt(k);}}return l;},_possibleChars:function _possibleChars(a){for(var b="",c=false,e=function e(h){(h=f+1<a.length&&a.charAt(f+1)==h)&&f++;return h;},f=0;f<a.length;f++){if(c){if(a.charAt(f)=="'"&&!e("'"))c=false;else b+=a.charAt(f);}else switch(a.charAt(f)){case"d":case"m":case"y":case"@":b+="0123456789";break;case"D":case"M":return null;case"'":if(e("'"))b+="'";else c=true;break;default:b+=a.charAt(f);}}return b;},_get:function _get(a,b){return a.settings[b]!==C?a.settings[b]:this._defaults[b];},_setDateFromField:function _setDateFromField(a,b){if(a.input.val()!=a.lastVal){var c=this._get(a,"dateFormat"),e=a.lastVal=a.input?a.input.val():null,f,h;f=h=this._getDefaultDate(a);var i=this._getFormatConfig(a);try{f=this.parseDate(c,e,i)||h;}catch(g){this.log(g);e=b?"":e;}a.selectedDay=f.getDate();a.drawMonth=a.selectedMonth=f.getMonth();a.drawYear=a.selectedYear=f.getFullYear();a.currentDay=e?f.getDate():0;a.currentMonth=e?f.getMonth():0;a.currentYear=e?f.getFullYear():0;this._adjustInstDate(a);}},_getDefaultDate:function _getDefaultDate(a){return this._restrictMinMax(a,this._determineDate(a,this._get(a,"defaultDate"),new Date()));},_determineDate:function _determineDate(a,b,c){var e=function e(h){var i=new Date();i.setDate(i.getDate()+h);return i;},f=function f(h){try{return d.datepicker.parseDate(d.datepicker._get(a,"dateFormat"),h,d.datepicker._getFormatConfig(a));}catch(i){}var g=(h.toLowerCase().match(/^c/)?d.datepicker._getDate(a):null)||new Date(),j=g.getFullYear(),l=g.getMonth();g=g.getDate();for(var u=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,k=u.exec(h);k;){switch(k[2]||"d"){case"d":case"D":g+=parseInt(k[1],10);break;case"w":case"W":g+=parseInt(k[1],10)*7;break;case"m":case"M":l+=parseInt(k[1],10);g=Math.min(g,d.datepicker._getDaysInMonth(j,l));break;case"y":case"Y":j+=parseInt(k[1],10);g=Math.min(g,d.datepicker._getDaysInMonth(j,l));break;}k=u.exec(h);}return new Date(j,l,g);};if(b=(b=b==null||b===""?c:typeof b=="string"?f(b):typeof b=="number"?isNaN(b)?c:e(b):new Date(b.getTime()))&&b.toString()=="Invalid Date"?c:b){b.setHours(0);b.setMinutes(0);b.setSeconds(0);b.setMilliseconds(0);}return this._daylightSavingAdjust(b);},_daylightSavingAdjust:function _daylightSavingAdjust(a){if(!a)return null;a.setHours(a.getHours()>12?a.getHours()+2:0);return a;},_setDate:function _setDate(a,b,c){var e=!b,f=a.selectedMonth,h=a.selectedYear;b=this._restrictMinMax(a,this._determineDate(a,b,new Date()));a.selectedDay=a.currentDay=b.getDate();a.drawMonth=a.selectedMonth=a.currentMonth=b.getMonth();a.drawYear=a.selectedYear=a.currentYear=b.getFullYear();if((f!=a.selectedMonth||h!=a.selectedYear)&&!c)this._notifyChange(a);this._adjustInstDate(a);if(a.input)a.input.val(e?"":this._formatDate(a));},_getDate:function _getDate(a){return!a.currentYear||a.input&&a.input.val()==""?null:this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));},_generateHTML:function _generateHTML(a){var b=new Date();b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate()));var c=this._get(a,"isRTL"),e=this._get(a,"showButtonPanel"),f=this._get(a,"hideIfNoPrevNext"),h=this._get(a,"navigationAsDateFormat"),i=this._getNumberOfMonths(a),g=this._get(a,"showCurrentAtPos"),j=this._get(a,"stepMonths"),l=i[0]!=1||i[1]!=1,u=this._daylightSavingAdjust(!a.currentDay?new Date(9999,9,9):new Date(a.currentYear,a.currentMonth,a.currentDay)),k=this._getMinMaxDate(a,"min"),o=this._getMinMaxDate(a,"max");g=a.drawMonth-g;var m=a.drawYear;if(g<0){g+=12;m--;}if(o){var n=this._daylightSavingAdjust(new Date(o.getFullYear(),o.getMonth()-i[0]*i[1]+1,o.getDate()));for(n=k&&n<k?k:n;this._daylightSavingAdjust(new Date(m,g,1))>n;){g--;if(g<0){g=11;m--;}}}a.drawMonth=g;a.drawYear=m;n=this._get(a,"prevText");n=!h?n:this.formatDate(n,this._daylightSavingAdjust(new Date(m,g-j,1)),this._getFormatConfig(a));n=this._canAdjustMonth(a,-1,m,g)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_'+B+".datepicker._adjustDate('#"+a.id+"', -"+j+", 'M');\" title=\""+n+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+n+"</span></a>":f?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+n+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+n+"</span></a>";var s=this._get(a,"nextText");s=!h?s:this.formatDate(s,this._daylightSavingAdjust(new Date(m,g+j,1)),this._getFormatConfig(a));f=this._canAdjustMonth(a,+1,m,g)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_'+B+".datepicker._adjustDate('#"+a.id+"', +"+j+", 'M');\" title=\""+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>":f?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>";j=this._get(a,"currentText");s=this._get(a,"gotoCurrent")&&a.currentDay?u:b;j=!h?j:this.formatDate(j,s,this._getFormatConfig(a));h=!a.inline?'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_'+B+'.datepicker._hideDatepicker();">'+this._get(a,"closeText")+"</button>":"";e=e?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(c?h:"")+(this._isInRange(a,s)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_'+B+".datepicker._gotoToday('#"+a.id+"');\">"+j+"</button>":"")+(c?"":h)+"</div>":"";h=parseInt(this._get(a,"firstDay"),10);h=isNaN(h)?0:h;j=this._get(a,"showWeek");s=this._get(a,"dayNames");this._get(a,"dayNamesShort");var q=this._get(a,"dayNamesMin"),A=this._get(a,"monthNames"),v=this._get(a,"monthNamesShort"),p=this._get(a,"beforeShowDay"),D=this._get(a,"showOtherMonths"),K=this._get(a,"selectOtherMonths");this._get(a,"calculateWeek");for(var E=this._getDefaultDate(a),w="",x=0;x<i[0];x++){var O="";this.maxRows=4;for(var G=0;G<i[1];G++){var P=this._daylightSavingAdjust(new Date(m,g,a.selectedDay)),t=" ui-corner-all",y="";if(l){y+='<div class="ui-datepicker-group';if(i[1]>1)switch(G){case 0:y+=" ui-datepicker-group-first";t=" ui-corner-"+(c?"right":"left");break;case i[1]-1:y+=" ui-datepicker-group-last";t=" ui-corner-"+(c?"left":"right");break;default:y+=" ui-datepicker-group-middle";t="";break;}y+='">';}y+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+t+'">'+(/all|left/.test(t)&&x==0?c?f:n:"")+(/all|right/.test(t)&&x==0?c?n:f:"")+this._generateMonthYearHeader(a,g,m,k,o,x>0||G>0,A,v)+'</div><table class="ui-datepicker-calendar"><thead><tr>';var z=j?'<th class="ui-datepicker-week-col">'+this._get(a,"weekHeader")+"</th>":"";for(t=0;t<7;t++){var r=(t+h)%7;z+="<th"+((t+h+6)%7>=5?' class="ui-datepicker-week-end"':"")+'><span title="'+s[r]+'">'+q[r]+"</span></th>";}y+=z+"</tr></thead><tbody>";z=this._getDaysInMonth(m,g);if(m==a.selectedYear&&g==a.selectedMonth)a.selectedDay=Math.min(a.selectedDay,z);t=(this._getFirstDayOfMonth(m,g)-h+7)%7;z=Math.ceil((t+z)/7);this.maxRows=z=l?this.maxRows>z?this.maxRows:z:z;r=this._daylightSavingAdjust(new Date(m,g,1-t));for(var Q=0;Q<z;Q++){y+="<tr>";var R=!j?"":'<td class="ui-datepicker-week-col">'+this._get(a,"calculateWeek")(r)+"</td>";for(t=0;t<7;t++){var I=p?p.apply(a.input?a.input[0]:null,[r]):[true,""],F=r.getMonth()!=g,L=F&&!K||!I[0]||k&&r<k||o&&r>o;R+='<td class="'+((t+h+6)%7>=5?" ui-datepicker-week-end":"")+(F?" ui-datepicker-other-month":"")+(r.getTime()==P.getTime()&&g==a.selectedMonth&&a._keyEvent||E.getTime()==r.getTime()&&E.getTime()==P.getTime()?" "+this._dayOverClass:"")+(L?" "+this._unselectableClass+" ui-state-disabled":"")+(F&&!D?"":" "+I[1]+(r.getTime()==u.getTime()?" "+this._currentClass:"")+(r.getTime()==b.getTime()?" ui-datepicker-today":""))+'"'+((!F||D)&&I[2]?' title="'+I[2]+'"':"")+(L?"":' onclick="DP_jQuery_'+B+".datepicker._selectDay('#"+a.id+"',"+r.getMonth()+","+r.getFullYear()+', this);return false;"')+">"+(F&&!D?"&#xa0;":L?'<span class="ui-state-default">'+r.getDate()+"</span>":'<a class="ui-state-default'+(r.getTime()==b.getTime()?" ui-state-highlight":"")+(r.getTime()==u.getTime()?" ui-state-active":"")+(F?" ui-priority-secondary":"")+'" href="#">'+r.getDate()+"</a>")+"</td>";r.setDate(r.getDate()+1);r=this._daylightSavingAdjust(r);}y+=R+"</tr>";}g++;if(g>11){g=0;m++;}y+="</tbody></table>"+(l?"</div>"+(i[0]>0&&G==i[1]-1?'<div class="ui-datepicker-row-break"></div>':""):"");O+=y;}w+=O;}w+=e+(d.browser.msie&&parseInt(d.browser.version,10)<7&&!a.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':"");a._keyEvent=false;return w;},_generateMonthYearHeader:function _generateMonthYearHeader(a,b,c,e,f,h,i,g){var j=this._get(a,"changeMonth"),l=this._get(a,"changeYear"),u=this._get(a,"showMonthAfterYear"),k='<div class="ui-datepicker-title">',o="";if(h||!j)o+='<span class="ui-datepicker-month">'+i[b]+"</span>";else{i=e&&e.getFullYear()==c;var m=f&&f.getFullYear()==c;o+='<select class="ui-datepicker-month" onchange="DP_jQuery_'+B+".datepicker._selectMonthYear('#"+a.id+"', this, 'M');\" >";for(var n=0;n<12;n++){if((!i||n>=e.getMonth())&&(!m||n<=f.getMonth()))o+='<option value="'+n+'"'+(n==b?' selected="selected"':"")+">"+g[n]+"</option>";}o+="</select>";}u||(k+=o+(h||!(j&&l)?"&#xa0;":""));if(!a.yearshtml){a.yearshtml="";if(h||!l)k+='<span class="ui-datepicker-year">'+c+"</span>";else{g=this._get(a,"yearRange").split(":");var s=new Date().getFullYear();i=function i(q){q=q.match(/c[+-].*/)?c+parseInt(q.substring(1),10):q.match(/[+-].*/)?s+parseInt(q,10):parseInt(q,10);return isNaN(q)?s:q;};b=i(g[0]);g=Math.max(b,i(g[1]||""));b=e?Math.max(b,e.getFullYear()):b;g=f?Math.min(g,f.getFullYear()):g;for(a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+B+".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');\" >";b<=g;b++){a.yearshtml+='<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";}a.yearshtml+="</select>";k+=a.yearshtml;a.yearshtml=null;}}k+=this._get(a,"yearSuffix");if(u)k+=(h||!(j&&l)?"&#xa0;":"")+o;k+="</div>";return k;},_adjustInstDate:function _adjustInstDate(a,b,c){var e=a.drawYear+(c=="Y"?b:0),f=a.drawMonth+(c=="M"?b:0);b=Math.min(a.selectedDay,this._getDaysInMonth(e,f))+(c=="D"?b:0);e=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(e,f,b)));a.selectedDay=e.getDate();a.drawMonth=a.selectedMonth=e.getMonth();a.drawYear=a.selectedYear=e.getFullYear();if(c=="M"||c=="Y")this._notifyChange(a);},_restrictMinMax:function _restrictMinMax(a,b){var c=this._getMinMaxDate(a,"min");a=this._getMinMaxDate(a,"max");b=c&&b<c?c:b;return b=a&&b>a?a:b;},_notifyChange:function _notifyChange(a){var b=this._get(a,"onChangeMonthYear");if(b)b.apply(a.input?a.input[0]:null,[a.selectedYear,a.selectedMonth+1,a]);},_getNumberOfMonths:function _getNumberOfMonths(a){a=this._get(a,"numberOfMonths");return a==null?[1,1]:typeof a=="number"?[1,a]:a;},_getMinMaxDate:function _getMinMaxDate(a,b){return this._determineDate(a,this._get(a,b+"Date"),null);},_getDaysInMonth:function _getDaysInMonth(a,b){return 32-this._daylightSavingAdjust(new Date(a,b,32)).getDate();},_getFirstDayOfMonth:function _getFirstDayOfMonth(a,b){return new Date(a,b,1).getDay();},_canAdjustMonth:function _canAdjustMonth(a,b,c,e){var f=this._getNumberOfMonths(a);c=this._daylightSavingAdjust(new Date(c,e+(b<0?b:f[0]*f[1]),1));b<0&&c.setDate(this._getDaysInMonth(c.getFullYear(),c.getMonth()));return this._isInRange(a,c);},_isInRange:function _isInRange(a,b){var c=this._getMinMaxDate(a,"min");a=this._getMinMaxDate(a,"max");return(!c||b.getTime()>=c.getTime())&&(!a||b.getTime()<=a.getTime());},_getFormatConfig:function _getFormatConfig(a){var b=this._get(a,"shortYearCutoff");b=typeof b!="string"?b:new Date().getFullYear()%100+parseInt(b,10);return{shortYearCutoff:b,dayNamesShort:this._get(a,"dayNamesShort"),dayNames:this._get(a,"dayNames"),monthNamesShort:this._get(a,"monthNamesShort"),monthNames:this._get(a,"monthNames")};},_formatDate:function _formatDate(a,b,c,e){if(!b){a.currentDay=a.selectedDay;a.currentMonth=a.selectedMonth;a.currentYear=a.selectedYear;}b=b?(typeof b==="undefined"?"undefined":_typeof(b))=="object"?b:this._daylightSavingAdjust(new Date(e,c,b)):this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return this.formatDate(this._get(a,"dateFormat"),b,this._getFormatConfig(a));}});d.fn.datepicker=function(a){if(!this.length)return this;if(!d.datepicker.initialized){d(document).mousedown(d.datepicker._checkExternalClick).find("body").append(d.datepicker.dpDiv);d.datepicker.initialized=true;}var b=Array.prototype.slice.call(arguments,1);if(typeof a=="string"&&(a=="isDisabled"||a=="getDate"||a=="widget"))return d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this[0]].concat(b));if(a=="option"&&arguments.length==2&&typeof arguments[1]=="string")return d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this[0]].concat(b));return this.each(function(){typeof a=="string"?d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this].concat(b)):d.datepicker._attachDatepicker(this,a);});};d.datepicker=new M();d.datepicker.initialized=false;d.datepicker.uuid=new Date().getTime();d.datepicker.version="1.8.16";window["DP_jQuery_"+B]=d;})(jQuery);;/*
 * jQuery UI Progressbar 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Progressbar
 *
 * Depends:
 *   jquery.ui.core.js
 *   jquery.ui.widget.js
 */(function(b,d){b.widget("ui.progressbar",{options:{value:0,max:100},min:0,_create:function _create(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min,"aria-valuemax":this.options.max,"aria-valuenow":this._value()});this.valueDiv=b("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element);this.oldValue=this._value();this._refreshValue();},destroy:function destroy(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow");this.valueDiv.remove();b.Widget.prototype.destroy.apply(this,arguments);},value:function value(a){if(a===d)return this._value();this._setOption("value",a);return this;},_setOption:function _setOption(a,c){if(a==="value"){this.options.value=c;this._refreshValue();this._value()===this.options.max&&this._trigger("complete");}b.Widget.prototype._setOption.apply(this,arguments);},_value:function _value(){var a=this.options.value;if(typeof a!=="number")a=0;return Math.min(this.options.max,Math.max(this.min,a));},_percentage:function _percentage(){return 100*this._value()/this.options.max;},_refreshValue:function _refreshValue(){var a=this.value(),c=this._percentage();if(this.oldValue!==a){this.oldValue=a;this._trigger("change");}this.valueDiv.toggle(a>this.min).toggleClass("ui-corner-right",a===this.options.max).width(c.toFixed(0)+"%");this.element.attr("aria-valuenow",a);}});b.extend(b.ui.progressbar,{version:"1.8.16"});})(jQuery);;/*
 * jQuery UI Effects 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/
 */jQuery.effects||function(f,j){function m(c){var a;if(c&&c.constructor==Array&&c.length==3)return c;if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)];if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55];if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))return[parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],16)];if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)];if(/rgba\(0, 0, 0, 0\)/.exec(c))return n.transparent;return n[f.trim(c).toLowerCase()];}function s(c,a){var b;do{b=f.curCSS(c,a);if(b!=""&&b!="transparent"||f.nodeName(c,"body"))break;a="backgroundColor";}while(c=c.parentNode);return m(b);}function o(){var c=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle,a={},b,d;if(c&&c.length&&c[0]&&c[c[0]])for(var e=c.length;e--;){b=c[e];if(typeof c[b]=="string"){d=b.replace(/\-(\w)/g,function(g,h){return h.toUpperCase();});a[d]=c[b];}}else for(b in c){if(typeof c[b]==="string")a[b]=c[b];}return a;}function p(c){var a,b;for(a in c){b=c[a];if(b==null||f.isFunction(b)||a in t||/scrollbar/.test(a)||!/color/i.test(a)&&isNaN(parseFloat(b)))delete c[a];}return c;}function u(c,a){var b={_:0},d;for(d in a){if(c[d]!=a[d])b[d]=a[d];}return b;}function k(c,a,b,d){if((typeof c==="undefined"?"undefined":_typeof(c))=="object"){d=a;b=null;a=c;c=a.effect;}if(f.isFunction(a)){d=a;b=null;a={};}if(typeof a=="number"||f.fx.speeds[a]){d=b;b=a;a={};}if(f.isFunction(b)){d=b;b=null;}a=a||{};b=b||a.duration;b=f.fx.off?0:typeof b=="number"?b:b in f.fx.speeds?f.fx.speeds[b]:f.fx.speeds._default;d=d||a.complete;return[c,a,b,d];}function l(c){if(!c||typeof c==="number"||f.fx.speeds[c])return true;if(typeof c==="string"&&!f.effects[c])return true;return false;}f.effects={};f.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(c,a){f.fx.step[a]=function(b){if(!b.colorInit){b.start=s(b.elem,a);b.end=m(b.end);b.colorInit=true;}b.elem.style[a]="rgb("+Math.max(Math.min(parseInt(b.pos*(b.end[0]-b.start[0])+b.start[0],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[1]-b.start[1])+b.start[1],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[2]-b.start[2])+b.start[2],10),255),0)+")";};});var n={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},q=["add","remove","toggle"],t={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};f.effects.animateClass=function(c,a,b,d){if(f.isFunction(b)){d=b;b=null;}return this.queue(function(){var e=f(this),g=e.attr("style")||" ",h=p(o.call(this)),r,v=e.attr("class");f.each(q,function(w,i){c[i]&&e[i+"Class"](c[i]);});r=p(o.call(this));e.attr("class",v);e.animate(u(h,r),{queue:false,duration:a,easing:b,complete:function complete(){f.each(q,function(w,i){c[i]&&e[i+"Class"](c[i]);});if(_typeof(e.attr("style"))=="object"){e.attr("style").cssText="";e.attr("style").cssText=g;}else e.attr("style",g);d&&d.apply(this,arguments);f.dequeue(this);}});});};f.fn.extend({_addClass:f.fn.addClass,addClass:function addClass(c,a,b,d){return a?f.effects.animateClass.apply(this,[{add:c},a,b,d]):this._addClass(c);},_removeClass:f.fn.removeClass,removeClass:function removeClass(c,a,b,d){return a?f.effects.animateClass.apply(this,[{remove:c},a,b,d]):this._removeClass(c);},_toggleClass:f.fn.toggleClass,toggleClass:function toggleClass(c,a,b,d,e){return typeof a=="boolean"||a===j?b?f.effects.animateClass.apply(this,[a?{add:c}:{remove:c},b,d,e]):this._toggleClass(c,a):f.effects.animateClass.apply(this,[{toggle:c},a,b,d]);},switchClass:function switchClass(c,a,b,d,e){return f.effects.animateClass.apply(this,[{add:a,remove:c},b,d,e]);}});f.extend(f.effects,{version:"1.8.16",save:function save(c,a){for(var b=0;b<a.length;b++){a[b]!==null&&c.data("ec.storage."+a[b],c[0].style[a[b]]);}},restore:function restore(c,a){for(var b=0;b<a.length;b++){a[b]!==null&&c.css(a[b],c.data("ec.storage."+a[b]));}},setMode:function setMode(c,a){if(a=="toggle")a=c.is(":hidden")?"show":"hide";return a;},getBaseline:function getBaseline(c,a){var b;switch(c[0]){case"top":b=0;break;case"middle":b=0.5;break;case"bottom":b=1;break;default:b=c[0]/a.height;}switch(c[1]){case"left":c=0;break;case"center":c=0.5;break;case"right":c=1;break;default:c=c[1]/a.width;}return{x:c,y:b};},createWrapper:function createWrapper(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent();var a={width:c.outerWidth(true),height:c.outerHeight(true),"float":c.css("float")},b=f("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),d=document.activeElement;c.wrap(b);if(c[0]===d||f.contains(c[0],d))f(d).focus();b=c.parent();if(c.css("position")=="static"){b.css({position:"relative"});c.css({position:"relative"});}else{f.extend(a,{position:c.css("position"),zIndex:c.css("z-index")});f.each(["top","left","bottom","right"],function(e,g){a[g]=c.css(g);if(isNaN(parseInt(a[g],10)))a[g]="auto";});c.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"});}return b.css(a).show();},removeWrapper:function removeWrapper(c){var a,b=document.activeElement;if(c.parent().is(".ui-effects-wrapper")){a=c.parent().replaceWith(c);if(c[0]===b||f.contains(c[0],b))f(b).focus();return a;}return c;},setTransition:function setTransition(c,a,b,d){d=d||{};f.each(a,function(e,g){unit=c.cssUnit(g);if(unit[0]>0)d[g]=unit[0]*b+unit[1];});return d;}});f.fn.extend({effect:function effect(c){var a=k.apply(this,arguments),b={options:a[1],duration:a[2],callback:a[3]};a=b.options.mode;var d=f.effects[c];if(f.fx.off||!d)return a?this[a](b.duration,b.callback):this.each(function(){b.callback&&b.callback.call(this);});return d.call(this,b);},_show:f.fn.show,show:function show(c){if(l(c))return this._show.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="show";return this.effect.apply(this,a);}},_hide:f.fn.hide,hide:function hide(c){if(l(c))return this._hide.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="hide";return this.effect.apply(this,a);}},__toggle:f.fn.toggle,toggle:function toggle(c){if(l(c)||typeof c==="boolean"||f.isFunction(c))return this.__toggle.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="toggle";return this.effect.apply(this,a);}},cssUnit:function cssUnit(c){var a=this.css(c),b=[];f.each(["em","px","%","pt"],function(d,e){if(a.indexOf(e)>0)b=[parseFloat(a),e];});return b;}});f.easing.jswing=f.easing.swing;f.extend(f.easing,{def:"easeOutQuad",swing:function swing(c,a,b,d,e){return f.easing[f.easing.def](c,a,b,d,e);},easeInQuad:function easeInQuad(c,a,b,d,e){return d*(a/=e)*a+b;},easeOutQuad:function easeOutQuad(c,a,b,d,e){return-d*(a/=e)*(a-2)+b;},easeInOutQuad:function easeInOutQuad(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a+b;return-d/2*(--a*(a-2)-1)+b;},easeInCubic:function easeInCubic(c,a,b,d,e){return d*(a/=e)*a*a+b;},easeOutCubic:function easeOutCubic(c,a,b,d,e){return d*((a=a/e-1)*a*a+1)+b;},easeInOutCubic:function easeInOutCubic(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a+b;return d/2*((a-=2)*a*a+2)+b;},easeInQuart:function easeInQuart(c,a,b,d,e){return d*(a/=e)*a*a*a+b;},easeOutQuart:function easeOutQuart(c,a,b,d,e){return-d*((a=a/e-1)*a*a*a-1)+b;},easeInOutQuart:function easeInOutQuart(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a+b;return-d/2*((a-=2)*a*a*a-2)+b;},easeInQuint:function easeInQuint(c,a,b,d,e){return d*(a/=e)*a*a*a*a+b;},easeOutQuint:function easeOutQuint(c,a,b,d,e){return d*((a=a/e-1)*a*a*a*a+1)+b;},easeInOutQuint:function easeInOutQuint(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a*a+b;return d/2*((a-=2)*a*a*a*a+2)+b;},easeInSine:function easeInSine(c,a,b,d,e){return-d*Math.cos(a/e*(Math.PI/2))+d+b;},easeOutSine:function easeOutSine(c,a,b,d,e){return d*Math.sin(a/e*(Math.PI/2))+b;},easeInOutSine:function easeInOutSine(c,a,b,d,e){return-d/2*(Math.cos(Math.PI*a/e)-1)+b;},easeInExpo:function easeInExpo(c,a,b,d,e){return a==0?b:d*Math.pow(2,10*(a/e-1))+b;},easeOutExpo:function easeOutExpo(c,a,b,d,e){return a==e?b+d:d*(-Math.pow(2,-10*a/e)+1)+b;},easeInOutExpo:function easeInOutExpo(c,a,b,d,e){if(a==0)return b;if(a==e)return b+d;if((a/=e/2)<1)return d/2*Math.pow(2,10*(a-1))+b;return d/2*(-Math.pow(2,-10*--a)+2)+b;},easeInCirc:function easeInCirc(c,a,b,d,e){return-d*(Math.sqrt(1-(a/=e)*a)-1)+b;},easeOutCirc:function easeOutCirc(c,a,b,d,e){return d*Math.sqrt(1-(a=a/e-1)*a)+b;},easeInOutCirc:function easeInOutCirc(c,a,b,d,e){if((a/=e/2)<1)return-d/2*(Math.sqrt(1-a*a)-1)+b;return d/2*(Math.sqrt(1-(a-=2)*a)+1)+b;},easeInElastic:function easeInElastic(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4;}else c=g/(2*Math.PI)*Math.asin(d/h);return-(h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g))+b;},easeOutElastic:function easeOutElastic(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4;}else c=g/(2*Math.PI)*Math.asin(d/h);return h*Math.pow(2,-10*a)*Math.sin((a*e-c)*2*Math.PI/g)+d+b;},easeInOutElastic:function easeInOutElastic(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e/2)==2)return b+d;g||(g=e*0.3*1.5);if(h<Math.abs(d)){h=d;c=g/4;}else c=g/(2*Math.PI)*Math.asin(d/h);if(a<1)return-0.5*h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)+b;return h*Math.pow(2,-10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)*0.5+d+b;},easeInBack:function easeInBack(c,a,b,d,e,g){if(g==j)g=1.70158;return d*(a/=e)*a*((g+1)*a-g)+b;},easeOutBack:function easeOutBack(c,a,b,d,e,g){if(g==j)g=1.70158;return d*((a=a/e-1)*a*((g+1)*a+g)+1)+b;},easeInOutBack:function easeInOutBack(c,a,b,d,e,g){if(g==j)g=1.70158;if((a/=e/2)<1)return d/2*a*a*(((g*=1.525)+1)*a-g)+b;return d/2*((a-=2)*a*(((g*=1.525)+1)*a+g)+2)+b;},easeInBounce:function easeInBounce(c,a,b,d,e){return d-f.easing.easeOutBounce(c,e-a,0,d,e)+b;},easeOutBounce:function easeOutBounce(c,a,b,d,e){return(a/=e)<1/2.75?d*7.5625*a*a+b:a<2/2.75?d*(7.5625*(a-=1.5/2.75)*a+0.75)+b:a<2.5/2.75?d*(7.5625*(a-=2.25/2.75)*a+0.9375)+b:d*(7.5625*(a-=2.625/2.75)*a+0.984375)+b;},easeInOutBounce:function easeInOutBounce(c,a,b,d,e){if(a<e/2)return f.easing.easeInBounce(c,a*2,0,d,e)*0.5+b;return f.easing.easeOutBounce(c,a*2-e,0,d,e)*0.5+d*0.5+b;}});}(jQuery);;/*
 * jQuery UI Effects Blind 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Blind
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(b){b.effects.blind=function(c){return this.queue(function(){var a=b(this),g=["position","top","bottom","left","right"],f=b.effects.setMode(a,c.options.mode||"hide"),d=c.options.direction||"vertical";b.effects.save(a,g);a.show();var e=b.effects.createWrapper(a).css({overflow:"hidden"}),h=d=="vertical"?"height":"width";d=d=="vertical"?e.height():e.width();f=="show"&&e.css(h,0);var i={};i[h]=f=="show"?d:0;e.animate(i,c.duration,c.options.easing,function(){f=="hide"&&a.hide();b.effects.restore(a,g);b.effects.removeWrapper(a);c.callback&&c.callback.apply(a[0],arguments);a.dequeue();});});};})(jQuery);;/*
 * jQuery UI Effects Bounce 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Bounce
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(e){e.effects.bounce=function(b){return this.queue(function(){var a=e(this),l=["position","top","bottom","left","right"],h=e.effects.setMode(a,b.options.mode||"effect"),d=b.options.direction||"up",c=b.options.distance||20,m=b.options.times||5,i=b.duration||250;/show|hide/.test(h)&&l.push("opacity");e.effects.save(a,l);a.show();e.effects.createWrapper(a);var f=d=="up"||d=="down"?"top":"left";d=d=="up"||d=="left"?"pos":"neg";c=b.options.distance||(f=="top"?a.outerHeight({margin:true})/3:a.outerWidth({margin:true})/3);if(h=="show")a.css("opacity",0).css(f,d=="pos"?-c:c);if(h=="hide")c/=m*2;h!="hide"&&m--;if(h=="show"){var g={opacity:1};g[f]=(d=="pos"?"+=":"-=")+c;a.animate(g,i/2,b.options.easing);c/=2;m--;}for(g=0;g<m;g++){var j={},k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing);c=h=="hide"?c*2:c/2;}if(h=="hide"){g={opacity:0};g[f]=(d=="pos"?"-=":"+=")+c;a.animate(g,i/2,b.options.easing,function(){a.hide();e.effects.restore(a,l);e.effects.removeWrapper(a);b.callback&&b.callback.apply(this,arguments);});}else{j={};k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing,function(){e.effects.restore(a,l);e.effects.removeWrapper(a);b.callback&&b.callback.apply(this,arguments);});}a.queue("fx",function(){a.dequeue();});a.dequeue();});};})(jQuery);;/*
 * jQuery UI Effects Clip 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Clip
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(b){b.effects.clip=function(e){return this.queue(function(){var a=b(this),i=["position","top","bottom","left","right","height","width"],f=b.effects.setMode(a,e.options.mode||"hide"),c=e.options.direction||"vertical";b.effects.save(a,i);a.show();var d=b.effects.createWrapper(a).css({overflow:"hidden"});d=a[0].tagName=="IMG"?d:a;var g={size:c=="vertical"?"height":"width",position:c=="vertical"?"top":"left"};c=c=="vertical"?d.height():d.width();if(f=="show"){d.css(g.size,0);d.css(g.position,c/2);}var h={};h[g.size]=f=="show"?c:0;h[g.position]=f=="show"?0:c/2;d.animate(h,{queue:false,duration:e.duration,easing:e.options.easing,complete:function complete(){f=="hide"&&a.hide();b.effects.restore(a,i);b.effects.removeWrapper(a);e.callback&&e.callback.apply(a[0],arguments);a.dequeue();}});});};})(jQuery);;/*
 * jQuery UI Effects Drop 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Drop
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(c){c.effects.drop=function(d){return this.queue(function(){var a=c(this),h=["position","top","bottom","left","right","opacity"],e=c.effects.setMode(a,d.options.mode||"hide"),b=d.options.direction||"left";c.effects.save(a,h);a.show();c.effects.createWrapper(a);var f=b=="up"||b=="down"?"top":"left";b=b=="up"||b=="left"?"pos":"neg";var g=d.options.distance||(f=="top"?a.outerHeight({margin:true})/2:a.outerWidth({margin:true})/2);if(e=="show")a.css("opacity",0).css(f,b=="pos"?-g:g);var i={opacity:e=="show"?1:0};i[f]=(e=="show"?b=="pos"?"+=":"-=":b=="pos"?"-=":"+=")+g;a.animate(i,{queue:false,duration:d.duration,easing:d.options.easing,complete:function complete(){e=="hide"&&a.hide();c.effects.restore(a,h);c.effects.removeWrapper(a);d.callback&&d.callback.apply(this,arguments);a.dequeue();}});});};})(jQuery);;/*
 * jQuery UI Effects Explode 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Explode
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(j){j.effects.explode=function(a){return this.queue(function(){var c=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3,d=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3;a.options.mode=a.options.mode=="toggle"?j(this).is(":visible")?"hide":"show":a.options.mode;var b=j(this).show().css("visibility","hidden"),g=b.offset();g.top-=parseInt(b.css("marginTop"),10)||0;g.left-=parseInt(b.css("marginLeft"),10)||0;for(var h=b.outerWidth(true),i=b.outerHeight(true),e=0;e<c;e++){for(var f=0;f<d;f++){b.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-f*(h/d),top:-e*(i/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:h/d,height:i/c,left:g.left+f*(h/d)+(a.options.mode=="show"?(f-Math.floor(d/2))*(h/d):0),top:g.top+e*(i/c)+(a.options.mode=="show"?(e-Math.floor(c/2))*(i/c):0),opacity:a.options.mode=="show"?0:1}).animate({left:g.left+f*(h/d)+(a.options.mode=="show"?0:(f-Math.floor(d/2))*(h/d)),top:g.top+e*(i/c)+(a.options.mode=="show"?0:(e-Math.floor(c/2))*(i/c)),opacity:a.options.mode=="show"?1:0},a.duration||500);}}setTimeout(function(){a.options.mode=="show"?b.css({visibility:"visible"}):b.css({visibility:"visible"}).hide();a.callback&&a.callback.apply(b[0]);b.dequeue();j("div.ui-effects-explode").remove();},a.duration||500);});};})(jQuery);;/*
 * jQuery UI Effects Fade 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Fade
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(b){b.effects.fade=function(a){return this.queue(function(){var c=b(this),d=b.effects.setMode(c,a.options.mode||"hide");c.animate({opacity:d},{queue:false,duration:a.duration,easing:a.options.easing,complete:function complete(){a.callback&&a.callback.apply(this,arguments);c.dequeue();}});});};})(jQuery);;/*
 * jQuery UI Effects Fold 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Fold
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(c){c.effects.fold=function(a){return this.queue(function(){var b=c(this),j=["position","top","bottom","left","right"],d=c.effects.setMode(b,a.options.mode||"hide"),g=a.options.size||15,h=!!a.options.horizFirst,k=a.duration?a.duration/2:c.fx.speeds._default/2;c.effects.save(b,j);b.show();var e=c.effects.createWrapper(b).css({overflow:"hidden"}),f=d=="show"!=h,l=f?["width","height"]:["height","width"];f=f?[e.width(),e.height()]:[e.height(),e.width()];var i=/([0-9]+)%/.exec(g);if(i)g=parseInt(i[1],10)/100*f[d=="hide"?0:1];if(d=="show")e.css(h?{height:0,width:g}:{height:g,width:0});h={};i={};h[l[0]]=d=="show"?f[0]:g;i[l[1]]=d=="show"?f[1]:0;e.animate(h,k,a.options.easing).animate(i,k,a.options.easing,function(){d=="hide"&&b.hide();c.effects.restore(b,j);c.effects.removeWrapper(b);a.callback&&a.callback.apply(b[0],arguments);b.dequeue();});});};})(jQuery);;/*
 * jQuery UI Effects Highlight 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Highlight
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(b){b.effects.highlight=function(c){return this.queue(function(){var a=b(this),e=["backgroundImage","backgroundColor","opacity"],d=b.effects.setMode(a,c.options.mode||"show"),f={backgroundColor:a.css("backgroundColor")};if(d=="hide")f.opacity=0;b.effects.save(a,e);a.show().css({backgroundImage:"none",backgroundColor:c.options.color||"#ffff99"}).animate(f,{queue:false,duration:c.duration,easing:c.options.easing,complete:function complete(){d=="hide"&&a.hide();b.effects.restore(a,e);d=="show"&&!b.support.opacity&&this.style.removeAttribute("filter");c.callback&&c.callback.apply(this,arguments);a.dequeue();}});});};})(jQuery);;/*
 * jQuery UI Effects Pulsate 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Pulsate
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(d){d.effects.pulsate=function(a){return this.queue(function(){var b=d(this),c=d.effects.setMode(b,a.options.mode||"show");times=(a.options.times||5)*2-1;duration=a.duration?a.duration/2:d.fx.speeds._default/2;isVisible=b.is(":visible");animateTo=0;if(!isVisible){b.css("opacity",0).show();animateTo=1;}if(c=="hide"&&isVisible||c=="show"&&!isVisible)times--;for(c=0;c<times;c++){b.animate({opacity:animateTo},duration,a.options.easing);animateTo=(animateTo+1)%2;}b.animate({opacity:animateTo},duration,a.options.easing,function(){animateTo==0&&b.hide();a.callback&&a.callback.apply(this,arguments);});b.queue("fx",function(){b.dequeue();}).dequeue();});};})(jQuery);;/*
 * jQuery UI Effects Scale 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Scale
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(c){c.effects.puff=function(b){return this.queue(function(){var a=c(this),e=c.effects.setMode(a,b.options.mode||"hide"),g=parseInt(b.options.percent,10)||150,h=g/100,i={height:a.height(),width:a.width()};c.extend(b.options,{fade:true,mode:e,percent:e=="hide"?g:100,from:e=="hide"?i:{height:i.height*h,width:i.width*h}});a.effect("scale",b.options,b.duration,b.callback);a.dequeue();});};c.effects.scale=function(b){return this.queue(function(){var a=c(this),e=c.extend(true,{},b.options),g=c.effects.setMode(a,b.options.mode||"effect"),h=parseInt(b.options.percent,10)||(parseInt(b.options.percent,10)==0?0:g=="hide"?0:100),i=b.options.direction||"both",f=b.options.origin;if(g!="effect"){e.origin=f||["middle","center"];e.restore=true;}f={height:a.height(),width:a.width()};a.from=b.options.from||(g=="show"?{height:0,width:0}:f);h={y:i!="horizontal"?h/100:1,x:i!="vertical"?h/100:1};a.to={height:f.height*h.y,width:f.width*h.x};if(b.options.fade){if(g=="show"){a.from.opacity=0;a.to.opacity=1;}if(g=="hide"){a.from.opacity=1;a.to.opacity=0;}}e.from=a.from;e.to=a.to;e.mode=g;a.effect("size",e,b.duration,b.callback);a.dequeue();});};c.effects.size=function(b){return this.queue(function(){var a=c(this),e=["position","top","bottom","left","right","width","height","overflow","opacity"],g=["position","top","bottom","left","right","overflow","opacity"],h=["width","height","overflow"],i=["fontSize"],f=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],k=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=c.effects.setMode(a,b.options.mode||"effect"),n=b.options.restore||false,m=b.options.scale||"both",l=b.options.origin,j={height:a.height(),width:a.width()};a.from=b.options.from||j;a.to=b.options.to||j;if(l){l=c.effects.getBaseline(l,j);a.from.top=(j.height-a.from.height)*l.y;a.from.left=(j.width-a.from.width)*l.x;a.to.top=(j.height-a.to.height)*l.y;a.to.left=(j.width-a.to.width)*l.x;}var d={from:{y:a.from.height/j.height,x:a.from.width/j.width},to:{y:a.to.height/j.height,x:a.to.width/j.width}};if(m=="box"||m=="both"){if(d.from.y!=d.to.y){e=e.concat(f);a.from=c.effects.setTransition(a,f,d.from.y,a.from);a.to=c.effects.setTransition(a,f,d.to.y,a.to);}if(d.from.x!=d.to.x){e=e.concat(k);a.from=c.effects.setTransition(a,k,d.from.x,a.from);a.to=c.effects.setTransition(a,k,d.to.x,a.to);}}if(m=="content"||m=="both")if(d.from.y!=d.to.y){e=e.concat(i);a.from=c.effects.setTransition(a,i,d.from.y,a.from);a.to=c.effects.setTransition(a,i,d.to.y,a.to);}c.effects.save(a,n?e:g);a.show();c.effects.createWrapper(a);a.css("overflow","hidden").css(a.from);if(m=="content"||m=="both"){f=f.concat(["marginTop","marginBottom"]).concat(i);k=k.concat(["marginLeft","marginRight"]);h=e.concat(f).concat(k);a.find("*[width]").each(function(){child=c(this);n&&c.effects.save(child,h);var o={height:child.height(),width:child.width()};child.from={height:o.height*d.from.y,width:o.width*d.from.x};child.to={height:o.height*d.to.y,width:o.width*d.to.x};if(d.from.y!=d.to.y){child.from=c.effects.setTransition(child,f,d.from.y,child.from);child.to=c.effects.setTransition(child,f,d.to.y,child.to);}if(d.from.x!=d.to.x){child.from=c.effects.setTransition(child,k,d.from.x,child.from);child.to=c.effects.setTransition(child,k,d.to.x,child.to);}child.css(child.from);child.animate(child.to,b.duration,b.options.easing,function(){n&&c.effects.restore(child,h);});});}a.animate(a.to,{queue:false,duration:b.duration,easing:b.options.easing,complete:function complete(){a.to.opacity===0&&a.css("opacity",a.from.opacity);p=="hide"&&a.hide();c.effects.restore(a,n?e:g);c.effects.removeWrapper(a);b.callback&&b.callback.apply(this,arguments);a.dequeue();}});});};})(jQuery);;/*
 * jQuery UI Effects Shake 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Shake
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(d){d.effects.shake=function(a){return this.queue(function(){var b=d(this),j=["position","top","bottom","left","right"];d.effects.setMode(b,a.options.mode||"effect");var c=a.options.direction||"left",e=a.options.distance||20,l=a.options.times||3,f=a.duration||a.options.duration||140;d.effects.save(b,j);b.show();d.effects.createWrapper(b);var g=c=="up"||c=="down"?"top":"left",h=c=="up"||c=="left"?"pos":"neg";c={};var i={},k={};c[g]=(h=="pos"?"-=":"+=")+e;i[g]=(h=="pos"?"+=":"-=")+e*2;k[g]=(h=="pos"?"-=":"+=")+e*2;b.animate(c,f,a.options.easing);for(e=1;e<l;e++){b.animate(i,f,a.options.easing).animate(k,f,a.options.easing);}b.animate(i,f,a.options.easing).animate(c,f/2,a.options.easing,function(){d.effects.restore(b,j);d.effects.removeWrapper(b);a.callback&&a.callback.apply(this,arguments);});b.queue("fx",function(){b.dequeue();});b.dequeue();});};})(jQuery);;/*
 * jQuery UI Effects Slide 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Slide
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(c){c.effects.slide=function(d){return this.queue(function(){var a=c(this),h=["position","top","bottom","left","right"],f=c.effects.setMode(a,d.options.mode||"show"),b=d.options.direction||"left";c.effects.save(a,h);a.show();c.effects.createWrapper(a).css({overflow:"hidden"});var g=b=="up"||b=="down"?"top":"left";b=b=="up"||b=="left"?"pos":"neg";var e=d.options.distance||(g=="top"?a.outerHeight({margin:true}):a.outerWidth({margin:true}));if(f=="show")a.css(g,b=="pos"?isNaN(e)?"-"+e:-e:e);var i={};i[g]=(f=="show"?b=="pos"?"+=":"-=":b=="pos"?"-=":"+=")+e;a.animate(i,{queue:false,duration:d.duration,easing:d.options.easing,complete:function complete(){f=="hide"&&a.hide();c.effects.restore(a,h);c.effects.removeWrapper(a);d.callback&&d.callback.apply(this,arguments);a.dequeue();}});});};})(jQuery);;/*
 * jQuery UI Effects Transfer 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Transfer
 *
 * Depends:
 *	jquery.effects.core.js
 */(function(e){e.effects.transfer=function(a){return this.queue(function(){var b=e(this),c=e(a.options.to),d=c.offset();c={top:d.top,left:d.left,height:c.innerHeight(),width:c.innerWidth()};d=b.offset();var f=e('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(a.options.className).css({top:d.top,left:d.left,height:b.innerHeight(),width:b.innerWidth(),position:"absolute"}).animate(c,a.duration,a.options.easing,function(){f.remove();a.callback&&a.callback.apply(b[0],arguments);b.dequeue();});});};})(jQuery);;},{}],3:[function(require,module,exports){(function($){$.toJSON=function(o){if((typeof JSON==="undefined"?"undefined":_typeof(JSON))=='object'&&JSON.stringify)return JSON.stringify(o);var type=typeof o==="undefined"?"undefined":_typeof(o);if(o===null)return"null";if(type=="undefined")return undefined;if(type=="number"||type=="boolean")return o+"";if(type=="string")return $.quoteString(o);if(type=='object'){if(typeof o.toJSON=="function")return $.toJSON(o.toJSON());if(o.constructor===Date){var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}if(o.constructor===Array){var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i])||"null");}return"["+ret.join(",")+"]";}var pairs=[];for(var k in o){var name;var type=typeof k==="undefined"?"undefined":_typeof(k);if(type=="number")name='"'+k+'"';else if(type=="string")name=$.quoteString(k);else continue;if(typeof o[k]=="function")continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src){if((typeof JSON==="undefined"?"undefined":_typeof(JSON))=='object'&&JSON.parse)return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src){if((typeof JSON==="undefined"?"undefined":_typeof(JSON))=='object'&&JSON.parse)return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))return eval("("+src+")");else throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string){if(string.match(_escapeable)){return'"'+string.replace(_escapeable,function(a){var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return"\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);},{}],4:[function(require,module,exports){/**
 * sprintf and vsprintf for jQuery
 * somewhat based on http://jan.moesen.nu/code/javascript/sprintf-and-printf-in-javascript/
 * 
 * Copyright (c) 2008 Sabin Iacob (m0n5t3r) <iacobs@m0n5t3r.info>
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details. 
 *
 * @license http://www.gnu.org/licenses/gpl.html 
 * @project jquery.sprintf
 */(function($){var formats={'b':function b(val){return parseInt(val,10).toString(2);},'c':function c(val){return String.fromCharCode(parseInt(val,10));},'d':function d(val){return parseInt(val,10);},'u':function u(val){return Math.abs(val);},'f':function f(val,p){p=parseInt(p,10);val=parseFloat(val);if(isNaN(p&&val)){return NaN;}return p&&val.toFixed(p)||val;},'o':function o(val){return parseInt(val,10).toString(8);},'s':function s(val){return val;},'x':function x(val){return(''+parseInt(val,10).toString(16)).toLowerCase();},'X':function X(val){return(''+parseInt(val,10).toString(16)).toUpperCase();}};var re=/%(?:(\d+)?(?:\.(\d+))?|\(([^)]+)\))([%bcdufosxX])/g;var dispatch=function dispatch(data){if(data.length==1&&_typeof(data[0])=='object'){//python-style printf
data=data[0];return function(match,w,p,lbl,fmt,off,str){return formats[fmt](data[lbl]);};}else{// regular, somewhat incomplete, printf
var idx=0;return function(match,w,p,lbl,fmt,off,str){if(fmt=='%'){return'%';}return formats[fmt](data[idx++],p);};}};$.extend({sprintf:function sprintf(format){var argv=Array.apply(null,arguments).slice(1);return format.replace(re,dispatch(argv));},vsprintf:function vsprintf(format,data){return format.replace(re,dispatch(data));}});})(jQuery);},{}],5:[function(require,module,exports){/* http://keith-wood.name/svg.html
   SVG for jQuery v1.4.3.
   Written by Keith Wood (kbwood{at}iinet.com.au) August 2007.
   Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and 
   MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. 
   Please attribute the author if you use it. */(function($){function SVGManager(){this._settings=[];this._extensions=[];this.regional=[];this.regional['']={errorLoadingText:'Error loading',notSupportedText:'This browser does not support SVG'};this.local=this.regional[''];this._uuid=new Date().getTime();this._renesis=detectActiveX('RenesisX.RenesisCtrl');}function detectActiveX(a){try{return!!(window.ActiveXObject&&new ActiveXObject(a));}catch(e){return false;}}var p='svgwrapper';$.extend(SVGManager.prototype,{markerClassName:'hasSVG',svgNS:'http://www.w3.org/2000/svg',xlinkNS:'http://www.w3.org/1999/xlink',_wrapperClass:SVGWrapper,_attrNames:{class_:'class',in_:'in',alignmentBaseline:'alignment-baseline',baselineShift:'baseline-shift',clipPath:'clip-path',clipRule:'clip-rule',colorInterpolation:'color-interpolation',colorInterpolationFilters:'color-interpolation-filters',colorRendering:'color-rendering',dominantBaseline:'dominant-baseline',enableBackground:'enable-background',fillOpacity:'fill-opacity',fillRule:'fill-rule',floodColor:'flood-color',floodOpacity:'flood-opacity',fontFamily:'font-family',fontSize:'font-size',fontSizeAdjust:'font-size-adjust',fontStretch:'font-stretch',fontStyle:'font-style',fontVariant:'font-variant',fontWeight:'font-weight',glyphOrientationHorizontal:'glyph-orientation-horizontal',glyphOrientationVertical:'glyph-orientation-vertical',horizAdvX:'horiz-adv-x',horizOriginX:'horiz-origin-x',imageRendering:'image-rendering',letterSpacing:'letter-spacing',lightingColor:'lighting-color',markerEnd:'marker-end',markerMid:'marker-mid',markerStart:'marker-start',stopColor:'stop-color',stopOpacity:'stop-opacity',strikethroughPosition:'strikethrough-position',strikethroughThickness:'strikethrough-thickness',strokeDashArray:'stroke-dasharray',strokeDashOffset:'stroke-dashoffset',strokeLineCap:'stroke-linecap',strokeLineJoin:'stroke-linejoin',strokeMiterLimit:'stroke-miterlimit',strokeOpacity:'stroke-opacity',strokeWidth:'stroke-width',textAnchor:'text-anchor',textDecoration:'text-decoration',textRendering:'text-rendering',underlinePosition:'underline-position',underlineThickness:'underline-thickness',vertAdvY:'vert-adv-y',vertOriginY:'vert-origin-y',wordSpacing:'word-spacing',writingMode:'writing-mode'},_attachSVG:function _attachSVG(a,b){var c=a.namespaceURI==this.svgNS?a:null;var a=c?null:a;if($(a||c).hasClass(this.markerClassName)){return;}if(typeof b=='string'){b={loadURL:b};}else if(typeof b=='function'){b={onLoad:b};}$(a||c).addClass(this.markerClassName);try{if(!c){c=document.createElementNS(this.svgNS,'svg');c.setAttribute('version','1.1');c.setAttribute('width',a.clientWidth);c.setAttribute('height',a.clientHeight);a.appendChild(c);}this._afterLoad(a,c,b||{});}catch(e){if($.browser.msie){if(!a.id){a.id='svg'+this._uuid++;}this._settings[a.id]=b;a.innerHTML='<embed type="image/svg+xml" width="100%" '+'height="100%" src="'+(b.initPath||'')+'blank.svg"/>';}else{a.innerHTML='<p class="svg_error">'+this.local.notSupportedText+'</p>';}}},_registerSVG:function _registerSVG(){for(var i=0;i<document.embeds.length;i++){var a=document.embeds[i].parentNode;if(!$(a).hasClass($.svg.markerClassName)||$.data(a,p)){continue;}var b=null;try{b=document.embeds[i].getSVGDocument();}catch(e){setTimeout($.svg._registerSVG,250);return;}b=b?b.documentElement:null;if(b){$.svg._afterLoad(a,b);}}},_afterLoad:function _afterLoad(a,b,c){var c=c||this._settings[a.id];this._settings[a?a.id:'']=null;var d=new this._wrapperClass(b,a);$.data(a||b,p,d);try{if(c.loadURL){d.load(c.loadURL,c);}if(c.settings){d.configure(c.settings);}if(c.onLoad&&!c.loadURL){c.onLoad.apply(a||b,[d]);}}catch(e){alert(e);}},_getSVG:function _getSVG(a){a=typeof a=='string'?$(a)[0]:a.jquery?a[0]:a;return $.data(a,p);},_destroySVG:function _destroySVG(a){var b=$(a);if(!b.hasClass(this.markerClassName)){return;}b.removeClass(this.markerClassName);if(a.namespaceURI!=this.svgNS){b.empty();}$.removeData(a,p);},addExtension:function addExtension(a,b){this._extensions.push([a,b]);}});function SVGWrapper(a,b){this._svg=a;this._container=b;for(var i=0;i<$.svg._extensions.length;i++){var c=$.svg._extensions[i];this[c[0]]=new c[1](this);}}$.extend(SVGWrapper.prototype,{_width:function _width(){return this._container?this._container.clientWidth:this._svg.width;},_height:function _height(){return this._container?this._container.clientHeight:this._svg.height;},root:function root(){return this._svg;},configure:function configure(a,b){if(b){for(var i=this._svg.attributes.length-1;i>=0;i--){var c=this._svg.attributes.item(i);if(!(c.nodeName=='onload'||c.nodeName=='version'||c.nodeName.substring(0,5)=='xmlns')){this._svg.attributes.removeNamedItem(c.nodeName);}}}for(var d in a){this._svg.setAttribute(d,a[d]);}return this;},getElementById:function getElementById(a){return this._svg.ownerDocument.getElementById(a);},change:function change(a,b){if(a){for(var c in b){if(b[c]==null){a.removeAttribute(c);}else{a.setAttribute(c,b[c]);}}}return this;},_args:function _args(b,c,d){c.splice(0,0,'parent');c.splice(c.length,0,'settings');var e={};var f=0;if(b[0]!=null&&b[0].jquery){b[0]=b[0][0];}if(b[0]!=null&&!(_typeof(b[0])=='object'&&b[0].nodeName)){e['parent']=null;f=1;}for(var i=0;i<b.length;i++){e[c[i+f]]=b[i];}if(d){$.each(d,function(i,a){if(_typeof(e[a])=='object'){e.settings=e[a];e[a]=null;}});}return e;},title:function title(a,b,c){var d=this._args(arguments,['text']);var e=this._makeNode(d.parent,'title',d.settings||{});e.appendChild(this._svg.ownerDocument.createTextNode(d.text));return e;},describe:function describe(a,b,c){var d=this._args(arguments,['text']);var e=this._makeNode(d.parent,'desc',d.settings||{});e.appendChild(this._svg.ownerDocument.createTextNode(d.text));return e;},defs:function defs(a,b,c){var d=this._args(arguments,['id'],['id']);return this._makeNode(d.parent,'defs',$.extend(d.id?{id:d.id}:{},d.settings||{}));},symbol:function symbol(a,b,c,d,e,f,g){var h=this._args(arguments,['id','x1','y1','width','height']);return this._makeNode(h.parent,'symbol',$.extend({id:h.id,viewBox:h.x1+' '+h.y1+' '+h.width+' '+h.height},h.settings||{}));},marker:function marker(a,b,c,d,e,f,g,h){var i=this._args(arguments,['id','refX','refY','mWidth','mHeight','orient'],['orient']);return this._makeNode(i.parent,'marker',$.extend({id:i.id,refX:i.refX,refY:i.refY,markerWidth:i.mWidth,markerHeight:i.mHeight,orient:i.orient||'auto'},i.settings||{}));},style:function style(a,b,c){var d=this._args(arguments,['styles']);var e=this._makeNode(d.parent,'style',$.extend({type:'text/css'},d.settings||{}));e.appendChild(this._svg.ownerDocument.createTextNode(d.styles));if($.browser.opera){$('head').append('<style type="text/css">'+d.styles+'</style>');}return e;},script:function script(a,b,c,d){var e=this._args(arguments,['script','type'],['type']);var f=this._makeNode(e.parent,'script',$.extend({type:e.type||'text/javascript'},e.settings||{}));f.appendChild(this._svg.ownerDocument.createTextNode(this._escapeXML(e.script)));if(!$.browser.mozilla){$.globalEval(e.script);}return f;},linearGradient:function linearGradient(a,b,c,d,e,f,g,h){var i=this._args(arguments,['id','stops','x1','y1','x2','y2'],['x1']);var j=$.extend({id:i.id},i.x1!=null?{x1:i.x1,y1:i.y1,x2:i.x2,y2:i.y2}:{});return this._gradient(i.parent,'linearGradient',$.extend(j,i.settings||{}),i.stops);},radialGradient:function radialGradient(a,b,c,d,e,r,f,g,h){var i=this._args(arguments,['id','stops','cx','cy','r','fx','fy'],['cx']);var j=$.extend({id:i.id},i.cx!=null?{cx:i.cx,cy:i.cy,r:i.r,fx:i.fx,fy:i.fy}:{});return this._gradient(i.parent,'radialGradient',$.extend(j,i.settings||{}),i.stops);},_gradient:function _gradient(a,b,c,d){var e=this._makeNode(a,b,c);for(var i=0;i<d.length;i++){var f=d[i];this._makeNode(e,'stop',$.extend({offset:f[0],stopColor:f[1]},f[2]!=null?{stopOpacity:f[2]}:{}));}return e;},pattern:function pattern(a,b,x,y,c,d,e,f,g,h,i){var j=this._args(arguments,['id','x','y','width','height','vx','vy','vwidth','vheight'],['vx']);var k=$.extend({id:j.id,x:j.x,y:j.y,width:j.width,height:j.height},j.vx!=null?{viewBox:j.vx+' '+j.vy+' '+j.vwidth+' '+j.vheight}:{});return this._makeNode(j.parent,'pattern',$.extend(k,j.settings||{}));},mask:function mask(a,b,x,y,c,d,e){var f=this._args(arguments,['id','x','y','width','height']);return this._makeNode(f.parent,'mask',$.extend({id:f.id,x:f.x,y:f.y,width:f.width,height:f.height},f.settings||{}));},createPath:function createPath(){return new SVGPath();},createText:function createText(){return new SVGText();},svg:function svg(a,x,y,b,c,d,e,f,g,h){var i=this._args(arguments,['x','y','width','height','vx','vy','vwidth','vheight'],['vx']);var j=$.extend({x:i.x,y:i.y,width:i.width,height:i.height},i.vx!=null?{viewBox:i.vx+' '+i.vy+' '+i.vwidth+' '+i.vheight}:{});return this._makeNode(i.parent,'svg',$.extend(j,i.settings||{}));},group:function group(a,b,c){var d=this._args(arguments,['id'],['id']);return this._makeNode(d.parent,'g',$.extend({id:d.id},d.settings||{}));},use:function use(a,x,y,b,c,d,e){var f=this._args(arguments,['x','y','width','height','ref']);if(typeof f.x=='string'){f.ref=f.x;f.settings=f.y;f.x=f.y=f.width=f.height=null;}var g=this._makeNode(f.parent,'use',$.extend({x:f.x,y:f.y,width:f.width,height:f.height},f.settings||{}));g.setAttributeNS($.svg.xlinkNS,'href',f.ref);return g;},link:function link(a,b,c){var d=this._args(arguments,['ref']);var e=this._makeNode(d.parent,'a',d.settings);e.setAttributeNS($.svg.xlinkNS,'href',d.ref);return e;},image:function image(a,x,y,b,c,d,e){var f=this._args(arguments,['x','y','width','height','ref']);var g=this._makeNode(f.parent,'image',$.extend({x:f.x,y:f.y,width:f.width,height:f.height},f.settings||{}));g.setAttributeNS($.svg.xlinkNS,'href',f.ref);return g;},path:function path(a,b,c){var d=this._args(arguments,['path']);return this._makeNode(d.parent,'path',$.extend({d:d.path.path?d.path.path():d.path},d.settings||{}));},rect:function rect(a,x,y,b,c,d,e,f){var g=this._args(arguments,['x','y','width','height','rx','ry'],['rx']);return this._makeNode(g.parent,'rect',$.extend({x:g.x,y:g.y,width:g.width,height:g.height},g.rx?{rx:g.rx,ry:g.ry}:{},g.settings||{}));},circle:function circle(a,b,c,r,d){var e=this._args(arguments,['cx','cy','r']);return this._makeNode(e.parent,'circle',$.extend({cx:e.cx,cy:e.cy,r:e.r},e.settings||{}));},ellipse:function ellipse(a,b,c,d,e,f){var g=this._args(arguments,['cx','cy','rx','ry']);return this._makeNode(g.parent,'ellipse',$.extend({cx:g.cx,cy:g.cy,rx:g.rx,ry:g.ry},g.settings||{}));},line:function line(a,b,c,d,e,f){var g=this._args(arguments,['x1','y1','x2','y2']);return this._makeNode(g.parent,'line',$.extend({x1:g.x1,y1:g.y1,x2:g.x2,y2:g.y2},g.settings||{}));},polyline:function polyline(a,b,c){var d=this._args(arguments,['points']);return this._poly(d.parent,'polyline',d.points,d.settings);},polygon:function polygon(a,b,c){var d=this._args(arguments,['points']);return this._poly(d.parent,'polygon',d.points,d.settings);},_poly:function _poly(a,b,c,d){var e='';for(var i=0;i<c.length;i++){e+=c[i].join()+' ';}return this._makeNode(a,b,$.extend({points:$.trim(e)},d||{}));},text:function text(a,x,y,b,c){var d=this._args(arguments,['x','y','value']);if(typeof d.x=='string'&&arguments.length<4){d.value=d.x;d.settings=d.y;d.x=d.y=null;}return this._text(d.parent,'text',d.value,$.extend({x:d.x&&isArray(d.x)?d.x.join(' '):d.x,y:d.y&&isArray(d.y)?d.y.join(' '):d.y},d.settings||{}));},textpath:function textpath(a,b,c,d){var e=this._args(arguments,['path','value']);var f=this._text(e.parent,'textPath',e.value,e.settings||{});f.setAttributeNS($.svg.xlinkNS,'href',e.path);return f;},_text:function _text(a,b,c,d){var e=this._makeNode(a,b,d);if(typeof c=='string'){e.appendChild(e.ownerDocument.createTextNode(c));}else{for(var i=0;i<c._parts.length;i++){var f=c._parts[i];if(f[0]=='tspan'){var g=this._makeNode(e,f[0],f[2]);g.appendChild(e.ownerDocument.createTextNode(f[1]));e.appendChild(g);}else if(f[0]=='tref'){var g=this._makeNode(e,f[0],f[2]);g.setAttributeNS($.svg.xlinkNS,'href',f[1]);e.appendChild(g);}else if(f[0]=='textpath'){var h=$.extend({},f[2]);h.href=null;var g=this._makeNode(e,f[0],h);g.setAttributeNS($.svg.xlinkNS,'href',f[2].href);g.appendChild(e.ownerDocument.createTextNode(f[1]));e.appendChild(g);}else{e.appendChild(e.ownerDocument.createTextNode(f[1]));}}}return e;},other:function other(a,b,c){var d=this._args(arguments,['name']);return this._makeNode(d.parent,d.name,d.settings||{});},_makeNode:function _makeNode(a,b,c){a=a||this._svg;var d=this._svg.ownerDocument.createElementNS($.svg.svgNS,b);for(var b in c){var e=c[b];if(e!=null&&e!=null&&(typeof e!='string'||e!='')){d.setAttribute($.svg._attrNames[b]||b,e);}}a.appendChild(d);return d;},add:function add(b,c){var d=this._args(arguments.length==1?[null,b]:arguments,['node']);var f=this;d.parent=d.parent||this._svg;try{if($.svg._renesis){throw'Force traversal';}d.parent.appendChild(d.node.cloneNode(true));}catch(e){d.node=d.node.jquery?d.node:$(d.node);d.node.each(function(){var a=f._cloneAsSVG(this);if(a){d.parent.appendChild(a);}});}return this;},_cloneAsSVG:function _cloneAsSVG(a){var b=null;if(a.nodeType==1){b=this._svg.ownerDocument.createElementNS($.svg.svgNS,this._checkName(a.nodeName));for(var i=0;i<a.attributes.length;i++){var c=a.attributes.item(i);if(c.nodeName!='xmlns'&&c.nodeValue){if(c.prefix=='xlink'){b.setAttributeNS($.svg.xlinkNS,c.localName,c.nodeValue);}else{b.setAttribute(this._checkName(c.nodeName),c.nodeValue);}}}for(var i=0;i<a.childNodes.length;i++){var d=this._cloneAsSVG(a.childNodes[i]);if(d){b.appendChild(d);}}}else if(a.nodeType==3){if($.trim(a.nodeValue)){b=this._svg.ownerDocument.createTextNode(a.nodeValue);}}else if(a.nodeType==4){if($.trim(a.nodeValue)){try{b=this._svg.ownerDocument.createCDATASection(a.nodeValue);}catch(e){b=this._svg.ownerDocument.createTextNode(a.nodeValue.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'));}}}return b;},_checkName:function _checkName(a){a=a.substring(0,1)>='A'&&a.substring(0,1)<='Z'?a.toLowerCase():a;return a.substring(0,4)=='svg:'?a.substring(4):a;},load:function load(h,j){j=typeof j=='boolean'?{addTo:j}:typeof j=='function'?{onLoad:j}:j||{};if(!j.addTo){this.clear(false);}var k=[this._svg.getAttribute('width'),this._svg.getAttribute('height')];var l=this;var m=function m(a){a=$.svg.local.errorLoadingText+': '+a;if(j.onLoad){j.onLoad.apply(l._container||l._svg,[l,a]);}else{l.text(null,10,20,a);}};var n=function n(a){var b=new ActiveXObject('Microsoft.XMLDOM');b.validateOnParse=false;b.resolveExternals=false;b.async=false;b.loadXML(a);if(b.parseError.errorCode!=0){m(b.parseError.reason);return null;}return b;};var o=function o(a){if(!a){return;}if(a.documentElement.nodeName!='svg'){var b=a.getElementsByTagName('parsererror');var c=b.length?b[0].getElementsByTagName('div'):[];m(!b.length?'???':(c.length?c[0]:b[0]).firstChild.nodeValue);return;}var d={};for(var i=0;i<a.documentElement.attributes.length;i++){var f=a.documentElement.attributes.item(i);if(!(f.nodeName=='version'||f.nodeName.substring(0,5)=='xmlns')){d[f.nodeName]=f.nodeValue;}}l.configure(d,true);var g=a.documentElement.childNodes;for(var i=0;i<g.length;i++){try{if($.svg._renesis){throw'Force traversal';}l._svg.appendChild(g[i].cloneNode(true));if(g[i].nodeName=='script'){$.globalEval(g[i].textContent);}}catch(e){l.add(null,g[i]);}}if(!j.changeSize){l.configure({width:k[0],height:k[1]});}if(j.onLoad){j.onLoad.apply(l._container||l._svg,[l]);}};if(h.match('<svg')){o($.browser.msie?n(h):new DOMParser().parseFromString(h,'text/xml'));}else{$.ajax({url:h,dataType:$.browser.msie?'text':'xml',success:function success(a){o($.browser.msie?n(a):a);},error:function error(a,b,c){m(b+(c?' '+c.message:''));}});}return this;},remove:function remove(a){a=a.jquery?a[0]:a;a.parentNode.removeChild(a);return this;},clear:function clear(a){if(a){this.configure({},true);}while(this._svg.firstChild){this._svg.removeChild(this._svg.firstChild);}return this;},toSVG:function toSVG(a){a=a||this._svg;return typeof XMLSerializer=='undefined'?this._toSVG(a):new XMLSerializer().serializeToString(a);},_toSVG:function _toSVG(a){var b='';if(!a){return b;}if(a.nodeType==3){b=a.nodeValue;}else if(a.nodeType==4){b='<![CDATA['+a.nodeValue+']]>';}else{b='<'+a.nodeName;if(a.attributes){for(var i=0;i<a.attributes.length;i++){var c=a.attributes.item(i);if(!($.trim(c.nodeValue)==''||c.nodeValue.match(/^\[object/)||c.nodeValue.match(/^function/))){b+=' '+(c.namespaceURI==$.svg.xlinkNS?'xlink:':'')+c.nodeName+'="'+c.nodeValue+'"';}}}if(a.firstChild){b+='>';var d=a.firstChild;while(d){b+=this._toSVG(d);d=d.nextSibling;}b+='</'+a.nodeName+'>';}else{b+='/>';}}return b;},_escapeXML:function _escapeXML(a){a=a.replace(/&/g,'&amp;');a=a.replace(/</g,'&lt;');a=a.replace(/>/g,'&gt;');return a;}});function SVGPath(){this._path='';}$.extend(SVGPath.prototype,{reset:function reset(){this._path='';return this;},move:function move(x,y,a){a=isArray(x)?y:a;return this._coords(a?'m':'M',x,y);},line:function line(x,y,a){a=isArray(x)?y:a;return this._coords(a?'l':'L',x,y);},horiz:function horiz(x,a){this._path+=(a?'h':'H')+(isArray(x)?x.join(' '):x);return this;},vert:function vert(y,a){this._path+=(a?'v':'V')+(isArray(y)?y.join(' '):y);return this;},curveC:function curveC(a,b,c,d,x,y,e){e=isArray(a)?b:e;return this._coords(e?'c':'C',a,b,c,d,x,y);},smoothC:function smoothC(a,b,x,y,c){c=isArray(a)?b:c;return this._coords(c?'s':'S',a,b,x,y);},curveQ:function curveQ(a,b,x,y,c){c=isArray(a)?b:c;return this._coords(c?'q':'Q',a,b,x,y);},smoothQ:function smoothQ(x,y,a){a=isArray(x)?y:a;return this._coords(a?'t':'T',x,y);},_coords:function _coords(a,b,c,d,e,f,g){if(isArray(b)){for(var i=0;i<b.length;i++){var h=b[i];this._path+=(i==0?a:' ')+h[0]+','+h[1]+(h.length<4?'':' '+h[2]+','+h[3]+(h.length<6?'':' '+h[4]+','+h[5]));}}else{this._path+=a+b+','+c+(d==null?'':' '+d+','+e+(f==null?'':' '+f+','+g));}return this;},arc:function arc(a,b,c,d,e,x,y,f){f=isArray(a)?b:f;this._path+=f?'a':'A';if(isArray(a)){for(var i=0;i<a.length;i++){var g=a[i];this._path+=(i==0?'':' ')+g[0]+','+g[1]+' '+g[2]+' '+(g[3]?'1':'0')+','+(g[4]?'1':'0')+' '+g[5]+','+g[6];}}else{this._path+=a+','+b+' '+c+' '+(d?'1':'0')+','+(e?'1':'0')+' '+x+','+y;}return this;},close:function close(){this._path+='z';return this;},path:function path(){return this._path;}});SVGPath.prototype.moveTo=SVGPath.prototype.move;SVGPath.prototype.lineTo=SVGPath.prototype.line;SVGPath.prototype.horizTo=SVGPath.prototype.horiz;SVGPath.prototype.vertTo=SVGPath.prototype.vert;SVGPath.prototype.curveCTo=SVGPath.prototype.curveC;SVGPath.prototype.smoothCTo=SVGPath.prototype.smoothC;SVGPath.prototype.curveQTo=SVGPath.prototype.curveQ;SVGPath.prototype.smoothQTo=SVGPath.prototype.smoothQ;SVGPath.prototype.arcTo=SVGPath.prototype.arc;function SVGText(){this._parts=[];}$.extend(SVGText.prototype,{reset:function reset(){this._parts=[];return this;},string:function string(a){this._parts[this._parts.length]=['text',a];return this;},span:function span(a,b){this._parts[this._parts.length]=['tspan',a,b];return this;},ref:function ref(a,b){this._parts[this._parts.length]=['tref',a,b];return this;},path:function path(a,b,c){this._parts[this._parts.length]=['textpath',b,$.extend({href:a},c||{})];return this;}});$.fn.svg=function(a){var b=Array.prototype.slice.call(arguments,1);if(typeof a=='string'&&a=='get'){return $.svg['_'+a+'SVG'].apply($.svg,[this[0]].concat(b));}return this.each(function(){if(typeof a=='string'){$.svg['_'+a+'SVG'].apply($.svg,[this].concat(b));}else{$.svg._attachSVG(this,a||{});}});};function isArray(a){return a&&a.constructor==Array;}$.svg=new SVGManager();})(jQuery);},{}],6:[function(require,module,exports){/* http://keith-wood.name/svg.html
   SVG/jQuery DOM compatibility for jQuery v1.4.3.
   Written by Keith Wood (kbwood{at}iinet.com.au) April 2009.
   Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and 
   MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. 
   Please attribute the author if you use it. */(function($){$.fn.addClass=function(e){return function(d){d=d||'';return this.each(function(){if(isSVGElem(this)){var c=this;$.each(d.split(/\s+/),function(i,a){var b=c.className?c.className.baseVal:c.getAttribute('class');if($.inArray(a,b.split(/\s+/))==-1){b+=(b?' ':'')+a;c.className?c.className.baseVal=b:c.setAttribute('class',b);}});}else{e.apply($(this),[d]);}});};}($.fn.addClass);$.fn.removeClass=function(e){return function(d){d=d||'';return this.each(function(){if(isSVGElem(this)){var c=this;$.each(d.split(/\s+/),function(i,a){var b=c.className?c.className.baseVal:c.getAttribute('class');b=$.grep(b.split(/\s+/),function(n,i){return n!=a;}).join(' ');c.className?c.className.baseVal=b:c.setAttribute('class',b);});}else{e.apply($(this),[d]);}});};}($.fn.removeClass);$.fn.toggleClass=function(c){return function(a,b){return this.each(function(){if(isSVGElem(this)){if(typeof b!=='boolean'){b=!$(this).hasClass(a);}$(this)[(b?'add':'remove')+'Class'](a);}else{c.apply($(this),[a,b]);}});};}($.fn.toggleClass);$.fn.hasClass=function(d){return function(b){b=b||'';var c=false;this.each(function(){if(isSVGElem(this)){var a=(this.className?this.className.baseVal:this.getAttribute('class')).split(/\s+/);c=$.inArray(b,a)>-1;}else{c=d.apply($(this),[b]);}return!c;});return c;};}($.fn.hasClass);$.fn.attr=function(h){return function(b,c,d){if(typeof b==='string'&&c===undefined){var e=h.apply(this,[b,c,d]);if(e&&e.baseVal&&e.baseVal.numberOfItems!=null){c='';e=e.baseVal;for(var i=0;i<e.numberOfItems;i++){var f=e.getItem(i);switch(f.type){case 1:c+=' matrix('+f.matrix.a+','+f.matrix.b+','+f.matrix.c+','+f.matrix.d+','+f.matrix.e+','+f.matrix.f+')';break;case 2:c+=' translate('+f.matrix.e+','+f.matrix.f+')';break;case 3:c+=' scale('+f.matrix.a+','+f.matrix.d+')';break;case 4:c+=' rotate('+f.angle+')';break;case 5:c+=' skewX('+f.angle+')';break;case 6:c+=' skewY('+f.angle+')';break;}}e=c.substring(1);}return e&&e.baseVal?e.baseVal.valueAsString:e;}var g=b;if(typeof b==='string'){g={};g[b]=c;}return this.each(function(){if(isSVGElem(this)){for(var n in g){var a=$.isFunction(g[n])?g[n]():g[n];d?this.style[n]=a:this.setAttribute(n,a);}}else{h.apply($(this),[b,c,d]);}});};}($.fn.attr);$.fn.removeAttr=function(b){return function(a){return this.each(function(){if(isSVGElem(this)){this[a]&&this[a].baseVal?this[a].baseVal.value='':this.setAttribute(a,'');}else{b.apply($(this),[a]);}});};}($.fn.removeAttr);function anySVG(a){for(var i=0;i<a.length;i++){if(a[i].nodeType==1&&a[i].namespaceURI==$.svg.svgNS){return true;}}return false;}$.expr.relative['+']=function(d){return function(a,b,c){d(a,b,c||anySVG(a));};}($.expr.relative['+']);$.expr.relative['>']=function(d){return function(a,b,c){d(a,b,c||anySVG(a));};}($.expr.relative['>']);$.expr.relative['']=function(d){return function(a,b,c){d(a,b,c||anySVG(a));};}($.expr.relative['']);$.expr.relative['~']=function(d){return function(a,b,c){d(a,b,c||anySVG(a));};}($.expr.relative['~']);$.expr.find.ID=function(d){return function(a,b,c){return isSVGElem(b)?[b.ownerDocument.getElementById(a[1])]:d(a,b,c);};}($.expr.find.ID);var j=document.createElement('div');j.appendChild(document.createComment(''));if(j.getElementsByTagName('*').length>0){$.expr.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==='*'){var d=[];for(var i=0;c[i]||c.item(i);i++){if((c[i]||c.item(i)).nodeType===1){d.push(c[i]||c.item(i));}}c=d;}return c;};}$.expr.preFilter.CLASS=function(a,b,c,d,f,g){a=' '+a[1].replace(/\\/g,'')+' ';if(g){return a;}for(var i=0,elem={};elem!=null;i++){elem=b[i];if(!elem){try{elem=b.item(i);}catch(e){}}if(elem){var h=!isSVGElem(elem)?elem.className:(elem.className?elem.className.baseVal:'')||elem.getAttribute('class');if(f^(h&&(' '+h+' ').indexOf(a)>-1)){if(!c)d.push(elem);}else if(c){b[i]=false;}}}return false;};$.expr.filter.CLASS=function(a,b){var c=!isSVGElem(a)?a.className:a.className?a.className.baseVal:a.getAttribute('class');return(' '+c+' ').indexOf(b)>-1;};$.expr.filter.ATTR=function(g){return function(c,d){var e=null;if(isSVGElem(c)){e=d[1];$.expr.attrHandle[e]=function(a){var b=a.getAttribute(e);return b&&b.baseVal||b;};}var f=g(c,d);if(e){$.expr.attrHandle[e]=null;}return f;};}($.expr.filter.ATTR);function isSVGElem(a){return a.nodeType==1&&a.namespaceURI==$.svg.svgNS;}})(jQuery);},{}],7:[function(require,module,exports){(function(){function create(window){window=window||eval("require('js"+"dom')").jsdom().createWindow();// assume window is a jsdom instance...
// jsdom includes an incomplete version of XMLHttpRequest
try{window.XMLHttpRequest=eval("require('xml"+"httprequest')").XMLHttpRequest;// trick jQuery into thinking CORS is supported (should be in node-XMLHttpRequest)
window.XMLHttpRequest.prototype.withCredentials=false;}catch(e){}var location=window.location,navigator=window.navigator,XMLHttpRequest=window.XMLHttpRequest;/*!
 * jQuery JavaScript Library v1.7.1
 * http://jquery.com/
 *
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2011, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Mon Nov 21 21:11:03 2011 -0500
 */(function(window,undefined){// Use the correct document accordingly with window argument (sandbox)
var document=window.document,navigator=window.navigator,location=window.location;var jQuery=function(){// Define a local copy of jQuery
var jQuery=function jQuery(selector,context){// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector,context,rootjQuery);},// Map over jQuery in case of overwrite
_jQuery=window.jQuery,// Map over the $ in case of overwrite
_$=window.$,// A central reference to the root jQuery(document)
rootjQuery,// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,// Check if a string has a non-whitespace character in it
rnotwhite=/\S/,// Used for trimming whitespace
trimLeft=/^\s+/,trimRight=/\s+$/,// Match a standalone tag
rsingleTag=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,// JSON RegExp
rvalidchars=/^[\],:{}\s]*$/,rvalidescape=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,rvalidtokens=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,rvalidbraces=/(?:^|:|,)(?:\s*\[)+/g,// Useragent RegExp
rwebkit=/(webkit)[ \/]([\w.]+)/,ropera=/(opera)(?:.*version)?[ \/]([\w.]+)/,rmsie=/(msie) ([\w.]+)/,rmozilla=/(mozilla)(?:.*? rv:([\w.]+))?/,// Matches dashed string for camelizing
rdashAlpha=/-([a-z]|[0-9])/ig,rmsPrefix=/^-ms-/,// Used by jQuery.camelCase as callback to replace()
fcamelCase=function fcamelCase(all,letter){return(letter+"").toUpperCase();},// Keep a UserAgent string for use with jQuery.browser
userAgent=navigator.userAgent,// For matching the engine and version of the browser
browserMatch,// The deferred used on DOM ready
readyList,// The ready event handler
_DOMContentLoaded2,// Save a reference to some core methods
toString=Object.prototype.toString,hasOwn=Object.prototype.hasOwnProperty,push=Array.prototype.push,_slice=Array.prototype.slice,trim=String.prototype.trim,indexOf=Array.prototype.indexOf,// [[Class]] -> type pairs
class2type={};jQuery.fn=jQuery.prototype={constructor:jQuery,init:function init(selector,context,rootjQuery){var match,elem,ret,doc;// Handle $(""), $(null), or $(undefined)
if(!selector){return this;}// Handle $(DOMElement)
if(selector.nodeType){this.context=this[0]=selector;this.length=1;return this;}// The body element only exists once, optimize finding it
if(selector==="body"&&!context&&document.body){this.context=document;this[0]=document.body;this.selector=selector;this.length=1;return this;}// Handle HTML strings
if(typeof selector==="string"){// Are we dealing with HTML string or an ID?
if(selector.charAt(0)==="<"&&selector.charAt(selector.length-1)===">"&&selector.length>=3){// Assume that strings that start and end with <> are HTML and skip the regex check
match=[null,selector,null];}else{match=quickExpr.exec(selector);}// Verify a match, and that no context was specified for #id
if(match&&(match[1]||!context)){// HANDLE: $(html) -> $(array)
if(match[1]){context=context instanceof jQuery?context[0]:context;doc=context?context.ownerDocument||context:document;// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret=rsingleTag.exec(selector);if(ret){if(jQuery.isPlainObject(context)){selector=[document.createElement(ret[1])];jQuery.fn.attr.call(selector,context,true);}else{selector=[doc.createElement(ret[1])];}}else{ret=jQuery.buildFragment([match[1]],[doc]);selector=(ret.cacheable?jQuery.clone(ret.fragment):ret.fragment).childNodes;}return jQuery.merge(this,selector);// HANDLE: $("#id")
}else{elem=document.getElementById(match[2]);// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if(elem&&elem.parentNode){// Handle the case where IE and Opera return items
// by name instead of ID
if(elem.id!==match[2]){return rootjQuery.find(selector);}// Otherwise, we inject the element directly into the jQuery object
this.length=1;this[0]=elem;}this.context=document;this.selector=selector;return this;}// HANDLE: $(expr, $(...))
}else if(!context||context.jquery){return(context||rootjQuery).find(selector);// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
}else{return this.constructor(context).find(selector);}// HANDLE: $(function)
// Shortcut for document ready
}else if(jQuery.isFunction(selector)){return rootjQuery.ready(selector);}if(selector.selector!==undefined){this.selector=selector.selector;this.context=selector.context;}return jQuery.makeArray(selector,this);},// Start with an empty selector
selector:"",// The current version of jQuery being used
jquery:"1.7.1",// The default length of a jQuery object is 0
length:0,// The number of elements contained in the matched element set
size:function size(){return this.length;},toArray:function toArray(){return _slice.call(this,0);},// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get:function get(num){return num==null?// Return a 'clean' array
this.toArray():// Return just the object
num<0?this[this.length+num]:this[num];},// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack:function pushStack(elems,name,selector){// Build a new jQuery matched element set
var ret=this.constructor();if(jQuery.isArray(elems)){push.apply(ret,elems);}else{jQuery.merge(ret,elems);}// Add the old object onto the stack (as a reference)
ret.prevObject=this;ret.context=this.context;if(name==="find"){ret.selector=this.selector+(this.selector?" ":"")+selector;}else if(name){ret.selector=this.selector+"."+name+"("+selector+")";}// Return the newly-formed element set
return ret;},// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each:function each(callback,args){return jQuery.each(this,callback,args);},ready:function ready(fn){// Attach the listeners
jQuery.bindReady();// Add the callback
readyList.add(fn);return this;},eq:function eq(i){i=+i;return i===-1?this.slice(i):this.slice(i,i+1);},first:function first(){return this.eq(0);},last:function last(){return this.eq(-1);},slice:function slice(){return this.pushStack(_slice.apply(this,arguments),"slice",_slice.call(arguments).join(","));},map:function map(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},end:function end(){return this.prevObject||this.constructor(null);},// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push:push,sort:[].sort,splice:[].splice};// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype=jQuery.fn;jQuery.extend=jQuery.fn.extend=function(){var options,name,src,copy,copyIsArray,clone,target=arguments[0]||{},i=1,length=arguments.length,deep=false;// Handle a deep copy situation
if(typeof target==="boolean"){deep=target;target=arguments[1]||{};// skip the boolean and the target
i=2;}// Handle case when target is a string or something (possible in deep copy)
if((typeof target==="undefined"?"undefined":_typeof(target))!=="object"&&!jQuery.isFunction(target)){target={};}// extend jQuery itself if only one argument is passed
if(length===i){target=this;--i;}for(;i<length;i++){// Only deal with non-null/undefined values
if((options=arguments[i])!=null){// Extend the base object
for(name in options){src=target[name];copy=options[name];// Prevent never-ending loop
if(target===copy){continue;}// Recurse if we're merging plain objects or arrays
if(deep&&copy&&(jQuery.isPlainObject(copy)||(copyIsArray=jQuery.isArray(copy)))){if(copyIsArray){copyIsArray=false;clone=src&&jQuery.isArray(src)?src:[];}else{clone=src&&jQuery.isPlainObject(src)?src:{};}// Never move original objects, clone them
target[name]=jQuery.extend(deep,clone,copy);// Don't bring in undefined values
}else if(copy!==undefined){target[name]=copy;}}}}// Return the modified object
return target;};jQuery.extend({noConflict:function noConflict(deep){if(window.$===jQuery){window.$=_$;}if(deep&&window.jQuery===jQuery){window.jQuery=_jQuery;}return jQuery;},// Is the DOM ready to be used? Set to true once it occurs.
isReady:false,// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait:1,// Hold (or release) the ready event
holdReady:function holdReady(hold){if(hold){jQuery.readyWait++;}else{jQuery.ready(true);}},// Handle when the DOM is ready
ready:function ready(wait){// Either a released hold or an DOMready/load event and not yet ready
if(wait===true&&! --jQuery.readyWait||wait!==true&&!jQuery.isReady){// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if(!document.body){return setTimeout(jQuery.ready,1);}// Remember that the DOM is ready
jQuery.isReady=true;// If a normal DOM Ready event fired, decrement, and wait if need be
if(wait!==true&&--jQuery.readyWait>0){return;}// If there are functions bound, to execute
readyList.fireWith(document,[jQuery]);// Trigger any bound ready events
if(jQuery.fn.trigger){jQuery(document).trigger("ready").off("ready");}}},bindReady:function bindReady(){if(readyList){return;}readyList=jQuery.Callbacks("once memory");// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if(document.readyState==="complete"){// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout(jQuery.ready,1);}// Mozilla, Opera and webkit nightlies currently support this event
if(document.addEventListener){// Use the handy event callback
document.addEventListener("DOMContentLoaded",_DOMContentLoaded2,false);// A fallback to window.onload, that will always work
window.addEventListener("load",jQuery.ready,false);// If IE event model is used
}else if(document.attachEvent){// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange",_DOMContentLoaded2);// A fallback to window.onload, that will always work
window.attachEvent("onload",jQuery.ready);// If IE and not a frame
// continually check to see if the document is ready
var toplevel=false;try{toplevel=window.frameElement==null;}catch(e){}if(document.documentElement.doScroll&&toplevel){doScrollCheck();}}},// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction:function isFunction(obj){return jQuery.type(obj)==="function";},isArray:Array.isArray||function(obj){return jQuery.type(obj)==="array";},// A crude way of determining if an object is a window
isWindow:function isWindow(obj){return obj&&(typeof obj==="undefined"?"undefined":_typeof(obj))==="object"&&"setInterval"in obj;},isNumeric:function isNumeric(obj){return!isNaN(parseFloat(obj))&&isFinite(obj);},type:function type(obj){return obj==null?String(obj):class2type[toString.call(obj)]||"object";},isPlainObject:function isPlainObject(obj){// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if(!obj||jQuery.type(obj)!=="object"||obj.nodeType||jQuery.isWindow(obj)){return false;}try{// Not own constructor property must be Object
if(obj.constructor&&!hasOwn.call(obj,"constructor")&&!hasOwn.call(obj.constructor.prototype,"isPrototypeOf")){return false;}}catch(e){// IE8,9 Will throw exceptions on certain host objects #9897
return false;}// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;for(key in obj){}return key===undefined||hasOwn.call(obj,key);},isEmptyObject:function isEmptyObject(obj){for(var name in obj){return false;}return true;},error:function error(msg){throw new Error(msg);},parseJSON:function parseJSON(data){if(typeof data!=="string"||!data){return null;}// Make sure leading/trailing whitespace is removed (IE can't handle it)
data=jQuery.trim(data);// Attempt to parse using the native JSON parser first
if(window.JSON&&window.JSON.parse){return window.JSON.parse(data);}// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if(rvalidchars.test(data.replace(rvalidescape,"@").replace(rvalidtokens,"]").replace(rvalidbraces,""))){return new Function("return "+data)();}jQuery.error("Invalid JSON: "+data);},// Cross-browser xml parsing
parseXML:function parseXML(data){var xml,tmp;try{if(window.DOMParser){// Standard
tmp=new DOMParser();xml=tmp.parseFromString(data,"text/xml");}else{// IE
xml=new ActiveXObject("Microsoft.XMLDOM");xml.async="false";xml.loadXML(data);}}catch(e){xml=undefined;}if(!xml||!xml.documentElement||xml.getElementsByTagName("parsererror").length){jQuery.error("Invalid XML: "+data);}return xml;},noop:function noop(){},// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval:function globalEval(data){if(data&&rnotwhite.test(data)){// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
(window.execScript||function(data){window["eval"].call(window,data);})(data);}},// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase:function camelCase(string){return string.replace(rmsPrefix,"ms-").replace(rdashAlpha,fcamelCase);},nodeName:function nodeName(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()===name.toUpperCase();},// args is for internal usage only
each:function each(object,callback,args){var name,i=0,length=object.length,isObj=length===undefined||jQuery.isFunction(object);if(args){if(isObj){for(name in object){if(callback.apply(object[name],args)===false){break;}}}else{for(;i<length;){if(callback.apply(object[i++],args)===false){break;}}}// A special, fast, case for the most common use of each
}else{if(isObj){for(name in object){if(callback.call(object[name],name,object[name])===false){break;}}}else{for(;i<length;){if(callback.call(object[i],i,object[i++])===false){break;}}}}return object;},// Use native String.trim function wherever possible
trim:trim?function(text){return text==null?"":trim.call(text);}:// Otherwise use our own trimming functionality
function(text){return text==null?"":text.toString().replace(trimLeft,"").replace(trimRight,"");},// results is for internal usage only
makeArray:function makeArray(array,results){var ret=results||[];if(array!=null){// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type=jQuery.type(array);if(array.length==null||type==="string"||type==="function"||type==="regexp"||jQuery.isWindow(array)){push.call(ret,array);}else{jQuery.merge(ret,array);}}return ret;},inArray:function inArray(elem,array,i){var len;if(array){if(indexOf){return indexOf.call(array,elem,i);}len=array.length;i=i?i<0?Math.max(0,len+i):i:0;for(;i<len;i++){// Skip accessing in sparse arrays
if(i in array&&array[i]===elem){return i;}}}return-1;},merge:function merge(first,second){var i=first.length,j=0;if(typeof second.length==="number"){for(var l=second.length;j<l;j++){first[i++]=second[j];}}else{while(second[j]!==undefined){first[i++]=second[j++];}}first.length=i;return first;},grep:function grep(elems,callback,inv){var ret=[],retVal;inv=!!inv;// Go through the array, only saving the items
// that pass the validator function
for(var i=0,length=elems.length;i<length;i++){retVal=!!callback(elems[i],i);if(inv!==retVal){ret.push(elems[i]);}}return ret;},// arg is for internal usage only
map:function map(elems,callback,arg){var value,key,ret=[],i=0,length=elems.length,// jquery objects are treated as arrays
isArray=elems instanceof jQuery||length!==undefined&&typeof length==="number"&&(length>0&&elems[0]&&elems[length-1]||length===0||jQuery.isArray(elems));// Go through the array, translating each of the items to their
if(isArray){for(;i<length;i++){value=callback(elems[i],i,arg);if(value!=null){ret[ret.length]=value;}}// Go through every key on the object,
}else{for(key in elems){value=callback(elems[key],key,arg);if(value!=null){ret[ret.length]=value;}}}// Flatten any nested arrays
return ret.concat.apply([],ret);},// A global GUID counter for objects
guid:1,// Bind a function to a context, optionally partially applying any
// arguments.
proxy:function proxy(fn,context){if(typeof context==="string"){var tmp=fn[context];context=fn;fn=tmp;}// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if(!jQuery.isFunction(fn)){return undefined;}// Simulated bind
var args=_slice.call(arguments,2),proxy=function proxy(){return fn.apply(context,args.concat(_slice.call(arguments)));};// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid=fn.guid=fn.guid||proxy.guid||jQuery.guid++;return proxy;},// Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function
access:function access(elems,key,value,exec,fn,pass){var length=elems.length;// Setting many attributes
if((typeof key==="undefined"?"undefined":_typeof(key))==="object"){for(var k in key){jQuery.access(elems,k,key[k],exec,fn,value);}return elems;}// Setting one attribute
if(value!==undefined){// Optionally, function values get executed if exec is true
exec=!pass&&exec&&jQuery.isFunction(value);for(var i=0;i<length;i++){fn(elems[i],key,exec?value.call(elems[i],i,fn(elems[i],key)):value,pass);}return elems;}// Getting an attribute
return length?fn(elems[0],key):undefined;},now:function now(){return new Date().getTime();},// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch:function uaMatch(ua){ua=ua.toLowerCase();var match=rwebkit.exec(ua)||ropera.exec(ua)||rmsie.exec(ua)||ua.indexOf("compatible")<0&&rmozilla.exec(ua)||[];return{browser:match[1]||"",version:match[2]||"0"};},sub:function sub(){function jQuerySub(selector,context){return new jQuerySub.fn.init(selector,context);}jQuery.extend(true,jQuerySub,this);jQuerySub.superclass=this;jQuerySub.fn=jQuerySub.prototype=this();jQuerySub.fn.constructor=jQuerySub;jQuerySub.sub=this.sub;jQuerySub.fn.init=function init(selector,context){if(context&&context instanceof jQuery&&!(context instanceof jQuerySub)){context=jQuerySub(context);}return jQuery.fn.init.call(this,selector,context,rootjQuerySub);};jQuerySub.fn.init.prototype=jQuerySub.fn;var rootjQuerySub=jQuerySub(document);return jQuerySub;},browser:{}});// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(i,name){class2type["[object "+name+"]"]=name.toLowerCase();});browserMatch=jQuery.uaMatch(userAgent);if(browserMatch.browser){jQuery.browser[browserMatch.browser]=true;jQuery.browser.version=browserMatch.version;}// Deprecated, use jQuery.browser.webkit instead
if(jQuery.browser.webkit){jQuery.browser.safari=true;}// IE doesn't match non-breaking spaces with \s
if(rnotwhite.test("\xA0")){trimLeft=/^[\s\xA0]+/;trimRight=/[\s\xA0]+$/;}// All jQuery objects should point back to these
rootjQuery=jQuery(document);// Cleanup functions for the document ready method
if(document.addEventListener){_DOMContentLoaded2=function DOMContentLoaded(){document.removeEventListener("DOMContentLoaded",_DOMContentLoaded2,false);jQuery.ready();};}else if(document.attachEvent){_DOMContentLoaded2=function _DOMContentLoaded(){// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if(document.readyState==="complete"){document.detachEvent("onreadystatechange",_DOMContentLoaded2);jQuery.ready();}};}// The DOM ready check for Internet Explorer
function doScrollCheck(){if(jQuery.isReady){return;}try{// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");}catch(e){setTimeout(doScrollCheck,1);return;}// and execute any waiting functions
jQuery.ready();}return jQuery;}();// String to Object flags format cache
var flagsCache={};// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags(flags){var object=flagsCache[flags]={},i,length;flags=flags.split(/\s+/);for(i=0,length=flags.length;i<length;i++){object[flags[i]]=true;}return object;}/*
     * Create a callback list using the following parameters:
     *
     *	flags:	an optional list of space-separated flags that will change how
     *			the callback list behaves
     *
     * By default a callback list will act like an event callback list and can be
     * "fired" multiple times.
     *
     * Possible flags:
     *
     *	once:			will ensure the callback list can only be fired once (like a Deferred)
     *
     *	memory:			will keep track of previous values and will call any callback added
     *					after the list has been fired right away with the latest "memorized"
     *					values (like a Deferred)
     *
     *	unique:			will ensure a callback can only be added once (no duplicate in the list)
     *
     *	stopOnFalse:	interrupt callings when a callback returns false
     *
     */jQuery.Callbacks=function(flags){// Convert flags from String-formatted to Object-formatted
// (we check in cache first)
flags=flags?flagsCache[flags]||createFlags(flags):{};var// Actual callback list
list=[],// Stack of fire calls for repeatable lists
stack=[],// Last fire value (for non-forgettable lists)
memory,// Flag to know if list is currently firing
firing,// First callback to fire (used internally by add and fireWith)
firingStart,// End of the loop when firing
firingLength,// Index of currently firing callback (modified by remove if needed)
firingIndex,// Add one or several callbacks to the list
_add=function _add(args){var i,length,elem,type,actual;for(i=0,length=args.length;i<length;i++){elem=args[i];type=jQuery.type(elem);if(type==="array"){// Inspect recursively
_add(elem);}else if(type==="function"){// Add if not in unique mode and callback is not in
if(!flags.unique||!self.has(elem)){list.push(elem);}}}},// Fire callbacks
fire=function fire(context,args){args=args||[];memory=!flags.memory||[context,args];firing=true;firingIndex=firingStart||0;firingStart=0;firingLength=list.length;for(;list&&firingIndex<firingLength;firingIndex++){if(list[firingIndex].apply(context,args)===false&&flags.stopOnFalse){memory=true;// Mark as halted
break;}}firing=false;if(list){if(!flags.once){if(stack&&stack.length){memory=stack.shift();self.fireWith(memory[0],memory[1]);}}else if(memory===true){self.disable();}else{list=[];}}},// Actual Callbacks object
self={// Add a callback or a collection of callbacks to the list
add:function add(){if(list){var length=list.length;_add(arguments);// Do we need to add the callbacks to the
// current firing batch?
if(firing){firingLength=list.length;// With memory, if we're not firing then
// we should call right away, unless previous
// firing was halted (stopOnFalse)
}else if(memory&&memory!==true){firingStart=length;fire(memory[0],memory[1]);}}return this;},// Remove a callback from the list
remove:function remove(){if(list){var args=arguments,argIndex=0,argLength=args.length;for(;argIndex<argLength;argIndex++){for(var i=0;i<list.length;i++){if(args[argIndex]===list[i]){// Handle firingIndex and firingLength
if(firing){if(i<=firingLength){firingLength--;if(i<=firingIndex){firingIndex--;}}}// Remove the element
list.splice(i--,1);// If we have some unicity property then
// we only need to do this once
if(flags.unique){break;}}}}}return this;},// Control if a given callback is in the list
has:function has(fn){if(list){var i=0,length=list.length;for(;i<length;i++){if(fn===list[i]){return true;}}}return false;},// Remove all callbacks from the list
empty:function empty(){list=[];return this;},// Have the list do nothing anymore
disable:function disable(){list=stack=memory=undefined;return this;},// Is it disabled?
disabled:function disabled(){return!list;},// Lock the list in its current state
lock:function lock(){stack=undefined;if(!memory||memory===true){self.disable();}return this;},// Is it locked?
locked:function locked(){return!stack;},// Call all callbacks with the given context and arguments
fireWith:function fireWith(context,args){if(stack){if(firing){if(!flags.once){stack.push([context,args]);}}else if(!(flags.once&&memory)){fire(context,args);}}return this;},// Call all the callbacks with the given arguments
fire:function fire(){self.fireWith(this,arguments);return this;},// To know if the callbacks have already been called at least once
fired:function fired(){return!!memory;}};return self;};var// Static reference to slice
sliceDeferred=[].slice;jQuery.extend({Deferred:function Deferred(func){var doneList=jQuery.Callbacks("once memory"),failList=jQuery.Callbacks("once memory"),progressList=jQuery.Callbacks("memory"),_state="pending",lists={resolve:doneList,reject:failList,notify:progressList},_promise={done:doneList.add,fail:failList.add,progress:progressList.add,state:function state(){return _state;},// Deprecated
isResolved:doneList.fired,isRejected:failList.fired,then:function then(doneCallbacks,failCallbacks,progressCallbacks){deferred.done(doneCallbacks).fail(failCallbacks).progress(progressCallbacks);return this;},always:function always(){deferred.done.apply(deferred,arguments).fail.apply(deferred,arguments);return this;},pipe:function pipe(fnDone,fnFail,fnProgress){return jQuery.Deferred(function(newDefer){jQuery.each({done:[fnDone,"resolve"],fail:[fnFail,"reject"],progress:[fnProgress,"notify"]},function(handler,data){var fn=data[0],action=data[1],returned;if(jQuery.isFunction(fn)){deferred[handler](function(){returned=fn.apply(this,arguments);if(returned&&jQuery.isFunction(returned.promise)){returned.promise().then(newDefer.resolve,newDefer.reject,newDefer.notify);}else{newDefer[action+"With"](this===deferred?newDefer:this,[returned]);}});}else{deferred[handler](newDefer[action]);}});}).promise();},// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise:function promise(obj){if(obj==null){obj=_promise;}else{for(var key in _promise){obj[key]=_promise[key];}}return obj;}},deferred=_promise.promise({}),key;for(key in lists){deferred[key]=lists[key].fire;deferred[key+"With"]=lists[key].fireWith;}// Handle state
deferred.done(function(){_state="resolved";},failList.disable,progressList.lock).fail(function(){_state="rejected";},doneList.disable,progressList.lock);// Call given func if any
if(func){func.call(deferred,deferred);}// All done!
return deferred;},// Deferred helper
when:function when(firstParam){var args=sliceDeferred.call(arguments,0),i=0,length=args.length,pValues=new Array(length),count=length,pCount=length,deferred=length<=1&&firstParam&&jQuery.isFunction(firstParam.promise)?firstParam:jQuery.Deferred(),promise=deferred.promise();function resolveFunc(i){return function(value){args[i]=arguments.length>1?sliceDeferred.call(arguments,0):value;if(! --count){deferred.resolveWith(deferred,args);}};}function progressFunc(i){return function(value){pValues[i]=arguments.length>1?sliceDeferred.call(arguments,0):value;deferred.notifyWith(promise,pValues);};}if(length>1){for(;i<length;i++){if(args[i]&&args[i].promise&&jQuery.isFunction(args[i].promise)){args[i].promise().then(resolveFunc(i),deferred.reject,progressFunc(i));}else{--count;}}if(!count){deferred.resolveWith(deferred,args);}}else if(deferred!==firstParam){deferred.resolveWith(deferred,length?[firstParam]:[]);}return promise;}});jQuery.support=function(){var support,all,a,select,opt,input,marginDiv,fragment,tds,events,eventName,i,isSupported,div=document.createElement("div"),documentElement=document.documentElement;// Preliminary tests
div.setAttribute("className","t");div.innerHTML="   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";all=div.getElementsByTagName("*");a=div.getElementsByTagName("a")[0];// Can't get basic test support
if(!all||!all.length||!a){return{};}// First batch of supports tests
select=document.createElement("select");opt=select.appendChild(document.createElement("option"));input=div.getElementsByTagName("input")[0];support={// IE strips leading whitespace when .innerHTML is used
leadingWhitespace:div.firstChild.nodeType===3,// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody:!div.getElementsByTagName("tbody").length,// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize:!!div.getElementsByTagName("link").length,// Get the style information from getAttribute
// (IE uses .cssText instead)
style:/top/.test(a.getAttribute("style")),// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized:a.getAttribute("href")==="/a",// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity:/^0.55/.test(a.style.opacity),// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat:!!a.style.cssFloat,// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn:input.value==="on",// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected:opt.selected,// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute:div.className!=="t",// Tests for enctype support on a form(#6743)
enctype:!!document.createElement("form").enctype,// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone:document.createElement("nav").cloneNode(true).outerHTML!=="<:nav></:nav>",// Will be defined later
submitBubbles:true,changeBubbles:true,focusinBubbles:false,deleteExpando:true,noCloneEvent:true,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableMarginRight:true};// Make sure checked status is properly cloned
input.checked=true;support.noCloneChecked=input.cloneNode(true).checked;// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled=true;support.optDisabled=!opt.disabled;// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try{delete div.test;}catch(e){support.deleteExpando=false;}if(!div.addEventListener&&div.attachEvent&&div.fireEvent){div.attachEvent("onclick",function(){// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent=false;});div.cloneNode(true).fireEvent("onclick");}// Check if a radio maintains its value
// after being appended to the DOM
input=document.createElement("input");input.value="t";input.setAttribute("type","radio");support.radioValue=input.value==="t";input.setAttribute("checked","checked");div.appendChild(input);fragment=document.createDocumentFragment();fragment.appendChild(div.lastChild);// WebKit doesn't clone checked state correctly in fragments
support.checkClone=fragment.cloneNode(true).cloneNode(true).lastChild.checked;// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked=input.checked;fragment.removeChild(input);fragment.appendChild(div);div.innerHTML="";// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if(window.getComputedStyle){marginDiv=document.createElement("div");marginDiv.style.width="0";marginDiv.style.marginRight="0";div.style.width="2px";div.appendChild(marginDiv);support.reliableMarginRight=(parseInt((window.getComputedStyle(marginDiv,null)||{marginRight:0}).marginRight,10)||0)===0;}// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if(div.attachEvent){for(i in{submit:1,change:1,focusin:1}){eventName="on"+i;isSupported=eventName in div;if(!isSupported){div.setAttribute(eventName,"return;");isSupported=typeof div[eventName]==="function";}support[i+"Bubbles"]=isSupported;}}fragment.removeChild(div);// Null elements to avoid leaks in IE
fragment=select=opt=marginDiv=div=input=null;// Run tests that need a body at doc ready
jQuery(function(){var container,outer,inner,table,td,offsetSupport,conMarginTop,ptlm,vb,style,html,body=document.getElementsByTagName("body")[0];if(!body){// Return for frameset docs that don't have a body
return;}conMarginTop=1;ptlm="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;";vb="visibility:hidden;border:0;";style="style='"+ptlm+"border:5px solid #000;padding:0;'";html="<div "+style+"><div></div></div>"+"<table "+style+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>";container=document.createElement("div");container.style.cssText=vb+"width:0;height:0;position:static;top:0;margin-top:"+conMarginTop+"px";body.insertBefore(container,body.firstChild);// Construct the test element
div=document.createElement("div");container.appendChild(div);// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";tds=div.getElementsByTagName("td");isSupported=tds[0].offsetHeight===0;tds[0].style.display="";tds[1].style.display="none";// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets=isSupported&&tds[0].offsetHeight===0;// Figure out if the W3C box model works as expected
div.innerHTML="";div.style.width=div.style.paddingLeft="1px";jQuery.boxModel=support.boxModel=div.offsetWidth===2;if(typeof div.style.zoom!=="undefined"){// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.style.display="inline";div.style.zoom=1;support.inlineBlockNeedsLayout=div.offsetWidth===2;// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display="";div.innerHTML="<div style='width:4px;'></div>";support.shrinkWrapBlocks=div.offsetWidth!==2;}div.style.cssText=ptlm+vb;div.innerHTML=html;outer=div.firstChild;inner=outer.firstChild;td=outer.nextSibling.firstChild.firstChild;offsetSupport={doesNotAddBorder:inner.offsetTop!==5,doesAddBorderForTableAndCells:td.offsetTop===5};inner.style.position="fixed";inner.style.top="20px";// safari subtracts parent border width here which is 5px
offsetSupport.fixedPosition=inner.offsetTop===20||inner.offsetTop===15;inner.style.position=inner.style.top="";outer.style.overflow="hidden";outer.style.position="relative";offsetSupport.subtractsBorderForOverflowNotVisible=inner.offsetTop===-5;offsetSupport.doesNotIncludeMarginInBodyOffset=body.offsetTop!==conMarginTop;body.removeChild(container);div=container=null;jQuery.extend(support,offsetSupport);});return support;}();var rbrace=/^(?:\{.*\}|\[.*\])$/,rmultiDash=/([A-Z])/g;jQuery.extend({cache:{},// Please use with caution
uuid:0,// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando:"jQuery"+(jQuery.fn.jquery+Math.random()).replace(/\D/g,""),// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData:{"embed":true,// Ban all objects except for Flash (which handle expandos)
"object":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000","applet":true},hasData:function hasData(elem){elem=elem.nodeType?jQuery.cache[elem[jQuery.expando]]:elem[jQuery.expando];return!!elem&&!isEmptyDataObject(elem);},data:function data(elem,name,_data2,pvt/* Internal Use Only */){if(!jQuery.acceptData(elem)){return;}var privateCache,thisCache,ret,internalKey=jQuery.expando,getByName=typeof name==="string",// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode=elem.nodeType,// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache=isNode?jQuery.cache:elem,// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id=isNode?elem[internalKey]:elem[internalKey]&&internalKey,isEvents=name==="events";// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if((!id||!cache[id]||!isEvents&&!pvt&&!cache[id].data)&&getByName&&_data2===undefined){return;}if(!id){// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if(isNode){elem[internalKey]=id=++jQuery.uuid;}else{id=internalKey;}}if(!cache[id]){cache[id]={};// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if(!isNode){cache[id].toJSON=jQuery.noop;}}// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if((typeof name==="undefined"?"undefined":_typeof(name))==="object"||typeof name==="function"){if(pvt){cache[id]=jQuery.extend(cache[id],name);}else{cache[id].data=jQuery.extend(cache[id].data,name);}}privateCache=thisCache=cache[id];// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if(!pvt){if(!thisCache.data){thisCache.data={};}thisCache=thisCache.data;}if(_data2!==undefined){thisCache[jQuery.camelCase(name)]=_data2;}// Users should not attempt to inspect the internal events object using jQuery.data,
// it is undocumented and subject to change. But does anyone listen? No.
if(isEvents&&!thisCache[name]){return privateCache.events;}// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if(getByName){// First Try to find as-is property data
ret=thisCache[name];// Test for null|undefined property data
if(ret==null){// Try to find the camelCased property
ret=thisCache[jQuery.camelCase(name)];}}else{ret=thisCache;}return ret;},removeData:function removeData(elem,name,pvt/* Internal Use Only */){if(!jQuery.acceptData(elem)){return;}var thisCache,i,l,// Reference to internal data cache key
internalKey=jQuery.expando,isNode=elem.nodeType,// See jQuery.data for more information
cache=isNode?jQuery.cache:elem,// See jQuery.data for more information
id=isNode?elem[internalKey]:internalKey;// If there is already no cache entry for this object, there is no
// purpose in continuing
if(!cache[id]){return;}if(name){thisCache=pvt?cache[id]:cache[id].data;if(thisCache){// Support array or space separated string names for data keys
if(!jQuery.isArray(name)){// try the string as a key before any manipulation
if(name in thisCache){name=[name];}else{// split the camel cased version by spaces unless a key with the spaces exists
name=jQuery.camelCase(name);if(name in thisCache){name=[name];}else{name=name.split(" ");}}}for(i=0,l=name.length;i<l;i++){delete thisCache[name[i]];}// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if(!(pvt?isEmptyDataObject:jQuery.isEmptyObject)(thisCache)){return;}}}// See jQuery.data for more information
if(!pvt){delete cache[id].data;// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if(!isEmptyDataObject(cache[id])){return;}}// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
// Ensure that `cache` is not a window object #10080
if(jQuery.support.deleteExpando||!cache.setInterval){delete cache[id];}else{cache[id]=null;}// We destroyed the cache and need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
if(isNode){// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if(jQuery.support.deleteExpando){delete elem[internalKey];}else if(elem.removeAttribute){elem.removeAttribute(internalKey);}else{elem[internalKey]=null;}}},// For internal use only.
_data:function _data(elem,name,data){return jQuery.data(elem,name,data,true);},// A method for determining if a DOM node can handle the data expando
acceptData:function acceptData(elem){if(elem.nodeName){var match=jQuery.noData[elem.nodeName.toLowerCase()];if(match){return!(match===true||elem.getAttribute("classid")!==match);}}return true;}});jQuery.fn.extend({data:function data(key,value){var parts,attr,name,data=null;if(typeof key==="undefined"){if(this.length){data=jQuery.data(this[0]);if(this[0].nodeType===1&&!jQuery._data(this[0],"parsedAttrs")){attr=this[0].attributes;for(var i=0,l=attr.length;i<l;i++){name=attr[i].name;if(name.indexOf("data-")===0){name=jQuery.camelCase(name.substring(5));dataAttr(this[0],name,data[name]);}}jQuery._data(this[0],"parsedAttrs",true);}}return data;}else if((typeof key==="undefined"?"undefined":_typeof(key))==="object"){return this.each(function(){jQuery.data(this,key);});}parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);// Try to fetch any internally stored data first
if(data===undefined&&this.length){data=jQuery.data(this[0],key);data=dataAttr(this[0],key,data);}return data===undefined&&parts[1]?this.data(parts[0]):data;}else{return this.each(function(){var self=jQuery(this),args=[parts[0],value];self.triggerHandler("setData"+parts[1]+"!",args);jQuery.data(this,key,value);self.triggerHandler("changeData"+parts[1]+"!",args);});}},removeData:function removeData(key){return this.each(function(){jQuery.removeData(this,key);});}});function dataAttr(elem,key,data){// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if(data===undefined&&elem.nodeType===1){var name="data-"+key.replace(rmultiDash,"-$1").toLowerCase();data=elem.getAttribute(name);if(typeof data==="string"){try{data=data==="true"?true:data==="false"?false:data==="null"?null:jQuery.isNumeric(data)?parseFloat(data):rbrace.test(data)?jQuery.parseJSON(data):data;}catch(e){}// Make sure we set the data so it isn't changed later
jQuery.data(elem,key,data);}else{data=undefined;}}return data;}// checks a cache object for emptiness
function isEmptyDataObject(obj){for(var name in obj){// if the public data object is empty, the private is still empty
if(name==="data"&&jQuery.isEmptyObject(obj[name])){continue;}if(name!=="toJSON"){return false;}}return true;}function handleQueueMarkDefer(elem,type,src){var deferDataKey=type+"defer",queueDataKey=type+"queue",markDataKey=type+"mark",defer=jQuery._data(elem,deferDataKey);if(defer&&(src==="queue"||!jQuery._data(elem,queueDataKey))&&(src==="mark"||!jQuery._data(elem,markDataKey))){// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout(function(){if(!jQuery._data(elem,queueDataKey)&&!jQuery._data(elem,markDataKey)){jQuery.removeData(elem,deferDataKey,true);defer.fire();}},0);}}jQuery.extend({_mark:function _mark(elem,type){if(elem){type=(type||"fx")+"mark";jQuery._data(elem,type,(jQuery._data(elem,type)||0)+1);}},_unmark:function _unmark(force,elem,type){if(force!==true){type=elem;elem=force;force=false;}if(elem){type=type||"fx";var key=type+"mark",count=force?0:(jQuery._data(elem,key)||1)-1;if(count){jQuery._data(elem,key,count);}else{jQuery.removeData(elem,key,true);handleQueueMarkDefer(elem,type,"mark");}}},queue:function queue(elem,type,data){var q;if(elem){type=(type||"fx")+"queue";q=jQuery._data(elem,type);// Speed up dequeue by getting out quickly if this is just a lookup
if(data){if(!q||jQuery.isArray(data)){q=jQuery._data(elem,type,jQuery.makeArray(data));}else{q.push(data);}}return q||[];}},dequeue:function dequeue(elem,type){type=type||"fx";var queue=jQuery.queue(elem,type),fn=queue.shift(),hooks={};// If the fx queue is dequeued, always remove the progress sentinel
if(fn==="inprogress"){fn=queue.shift();}if(fn){// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if(type==="fx"){queue.unshift("inprogress");}jQuery._data(elem,type+".run",hooks);fn.call(elem,function(){jQuery.dequeue(elem,type);},hooks);}if(!queue.length){jQuery.removeData(elem,type+"queue "+type+".run",true);handleQueueMarkDefer(elem,type,"queue");}}});jQuery.fn.extend({queue:function queue(type,data){if(typeof type!=="string"){data=type;type="fx";}if(data===undefined){return jQuery.queue(this[0],type);}return this.each(function(){var queue=jQuery.queue(this,type,data);if(type==="fx"&&queue[0]!=="inprogress"){jQuery.dequeue(this,type);}});},dequeue:function dequeue(type){return this.each(function(){jQuery.dequeue(this,type);});},// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay:function delay(time,type){time=jQuery.fx?jQuery.fx.speeds[time]||time:time;type=type||"fx";return this.queue(type,function(next,hooks){var timeout=setTimeout(next,time);hooks.stop=function(){clearTimeout(timeout);};});},clearQueue:function clearQueue(type){return this.queue(type||"fx",[]);},// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise:function promise(type,object){if(typeof type!=="string"){object=type;type=undefined;}type=type||"fx";var defer=jQuery.Deferred(),elements=this,i=elements.length,count=1,deferDataKey=type+"defer",queueDataKey=type+"queue",markDataKey=type+"mark",tmp;function resolve(){if(! --count){defer.resolveWith(elements,[elements]);}}while(i--){if(tmp=jQuery.data(elements[i],deferDataKey,undefined,true)||(jQuery.data(elements[i],queueDataKey,undefined,true)||jQuery.data(elements[i],markDataKey,undefined,true))&&jQuery.data(elements[i],deferDataKey,jQuery.Callbacks("once memory"),true)){count++;tmp.add(resolve);}}resolve();return defer.promise();}});var rclass=/[\n\t\r]/g,rspace=/\s+/,rreturn=/\r/g,rtype=/^(?:button|input)$/i,rfocusable=/^(?:button|input|object|select|textarea)$/i,rclickable=/^a(?:rea)?$/i,rboolean=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,getSetAttribute=jQuery.support.getSetAttribute,nodeHook,boolHook,fixSpecified;jQuery.fn.extend({attr:function attr(name,value){return jQuery.access(this,name,value,true,jQuery.attr);},removeAttr:function removeAttr(name){return this.each(function(){jQuery.removeAttr(this,name);});},prop:function prop(name,value){return jQuery.access(this,name,value,true,jQuery.prop);},removeProp:function removeProp(name){name=jQuery.propFix[name]||name;return this.each(function(){// try/catch handles cases where IE balks (such as removing a property on window)
try{this[name]=undefined;delete this[name];}catch(e){}});},addClass:function addClass(value){var classNames,i,l,elem,setClass,c,cl;if(jQuery.isFunction(value)){return this.each(function(j){jQuery(this).addClass(value.call(this,j,this.className));});}if(value&&typeof value==="string"){classNames=value.split(rspace);for(i=0,l=this.length;i<l;i++){elem=this[i];if(elem.nodeType===1){if(!elem.className&&classNames.length===1){elem.className=value;}else{setClass=" "+elem.className+" ";for(c=0,cl=classNames.length;c<cl;c++){if(!~setClass.indexOf(" "+classNames[c]+" ")){setClass+=classNames[c]+" ";}}elem.className=jQuery.trim(setClass);}}}}return this;},removeClass:function removeClass(value){var classNames,i,l,elem,className,c,cl;if(jQuery.isFunction(value)){return this.each(function(j){jQuery(this).removeClass(value.call(this,j,this.className));});}if(value&&typeof value==="string"||value===undefined){classNames=(value||"").split(rspace);for(i=0,l=this.length;i<l;i++){elem=this[i];if(elem.nodeType===1&&elem.className){if(value){className=(" "+elem.className+" ").replace(rclass," ");for(c=0,cl=classNames.length;c<cl;c++){className=className.replace(" "+classNames[c]+" "," ");}elem.className=jQuery.trim(className);}else{elem.className="";}}}}return this;},toggleClass:function toggleClass(value,stateVal){var type=typeof value==="undefined"?"undefined":_typeof(value),isBool=typeof stateVal==="boolean";if(jQuery.isFunction(value)){return this.each(function(i){jQuery(this).toggleClass(value.call(this,i,this.className,stateVal),stateVal);});}return this.each(function(){if(type==="string"){// toggle individual class names
var className,i=0,self=jQuery(this),state=stateVal,classNames=value.split(rspace);while(className=classNames[i++]){// check each className given, space seperated list
state=isBool?state:!self.hasClass(className);self[state?"addClass":"removeClass"](className);}}else if(type==="undefined"||type==="boolean"){if(this.className){// store className if set
jQuery._data(this,"__className__",this.className);}// toggle whole className
this.className=this.className||value===false?"":jQuery._data(this,"__className__")||"";}});},hasClass:function hasClass(selector){var className=" "+selector+" ",i=0,l=this.length;for(;i<l;i++){if(this[i].nodeType===1&&(" "+this[i].className+" ").replace(rclass," ").indexOf(className)>-1){return true;}}return false;},val:function val(value){var hooks,ret,isFunction,elem=this[0];if(!arguments.length){if(elem){hooks=jQuery.valHooks[elem.nodeName.toLowerCase()]||jQuery.valHooks[elem.type];if(hooks&&"get"in hooks&&(ret=hooks.get(elem,"value"))!==undefined){return ret;}ret=elem.value;return typeof ret==="string"?// handle most common string cases
ret.replace(rreturn,""):// handle cases where value is null/undef or number
ret==null?"":ret;}return;}isFunction=jQuery.isFunction(value);return this.each(function(i){var self=jQuery(this),val;if(this.nodeType!==1){return;}if(isFunction){val=value.call(this,i,self.val());}else{val=value;}// Treat null/undefined as ""; convert numbers to string
if(val==null){val="";}else if(typeof val==="number"){val+="";}else if(jQuery.isArray(val)){val=jQuery.map(val,function(value){return value==null?"":value+"";});}hooks=jQuery.valHooks[this.nodeName.toLowerCase()]||jQuery.valHooks[this.type];// If set returns undefined, fall back to normal setting
if(!hooks||!("set"in hooks)||hooks.set(this,val,"value")===undefined){this.value=val;}});}});jQuery.extend({valHooks:{option:{get:function get(elem){// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val=elem.attributes.value;return!val||val.specified?elem.value:elem.text;}},select:{get:function get(elem){var value,i,max,option,index=elem.selectedIndex,values=[],options=elem.options,one=elem.type==="select-one";// Nothing was selected
if(index<0){return null;}// Loop through all the selected options
i=one?index:0;max=one?index+1:options.length;for(;i<max;i++){option=options[i];// Don't return options that are disabled or in a disabled optgroup
if(option.selected&&(jQuery.support.optDisabled?!option.disabled:option.getAttribute("disabled")===null)&&(!option.parentNode.disabled||!jQuery.nodeName(option.parentNode,"optgroup"))){// Get the specific value for the option
value=jQuery(option).val();// We don't need an array for one selects
if(one){return value;}// Multi-Selects return an array
values.push(value);}}// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if(one&&!values.length&&options.length){return jQuery(options[index]).val();}return values;},set:function set(elem,value){var values=jQuery.makeArray(value);jQuery(elem).find("option").each(function(){this.selected=jQuery.inArray(jQuery(this).val(),values)>=0;});if(!values.length){elem.selectedIndex=-1;}return values;}}},attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function attr(elem,name,value,pass){var ret,hooks,notxml,nType=elem.nodeType;// don't get/set attributes on text, comment and attribute nodes
if(!elem||nType===3||nType===8||nType===2){return;}if(pass&&name in jQuery.attrFn){return jQuery(elem)[name](value);}// Fallback to prop when attributes are not supported
if(typeof elem.getAttribute==="undefined"){return jQuery.prop(elem,name,value);}notxml=nType!==1||!jQuery.isXMLDoc(elem);// All attributes are lowercase
// Grab necessary hook if one is defined
if(notxml){name=name.toLowerCase();hooks=jQuery.attrHooks[name]||(rboolean.test(name)?boolHook:nodeHook);}if(value!==undefined){if(value===null){jQuery.removeAttr(elem,name);return;}else if(hooks&&"set"in hooks&&notxml&&(ret=hooks.set(elem,value,name))!==undefined){return ret;}else{elem.setAttribute(name,""+value);return value;}}else if(hooks&&"get"in hooks&&notxml&&(ret=hooks.get(elem,name))!==null){return ret;}else{ret=elem.getAttribute(name);// Non-existent attributes return null, we normalize to undefined
return ret===null?undefined:ret;}},removeAttr:function removeAttr(elem,value){var propName,attrNames,name,l,i=0;if(value&&elem.nodeType===1){attrNames=value.toLowerCase().split(rspace);l=attrNames.length;for(;i<l;i++){name=attrNames[i];if(name){propName=jQuery.propFix[name]||name;// See #9699 for explanation of this approach (setting first, then removal)
jQuery.attr(elem,name,"");elem.removeAttribute(getSetAttribute?name:propName);// Set corresponding property to false for boolean attributes
if(rboolean.test(name)&&propName in elem){elem[propName]=false;}}}}},attrHooks:{type:{set:function set(elem,value){// We can't allow the type property to be changed (since it causes problems in IE)
if(rtype.test(elem.nodeName)&&elem.parentNode){jQuery.error("type property can't be changed");}else if(!jQuery.support.radioValue&&value==="radio"&&jQuery.nodeName(elem,"input")){// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val=elem.value;elem.setAttribute("type",value);if(val){elem.value=val;}return value;}}},// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value:{get:function get(elem,name){if(nodeHook&&jQuery.nodeName(elem,"button")){return nodeHook.get(elem,name);}return name in elem?elem.value:null;},set:function set(elem,value,name){if(nodeHook&&jQuery.nodeName(elem,"button")){return nodeHook.set(elem,value,name);}// Does not return so that setAttribute is also used
elem.value=value;}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function prop(elem,name,value){var ret,hooks,notxml,nType=elem.nodeType;// don't get/set properties on text, comment and attribute nodes
if(!elem||nType===3||nType===8||nType===2){return;}notxml=nType!==1||!jQuery.isXMLDoc(elem);if(notxml){// Fix name and attach hooks
name=jQuery.propFix[name]||name;hooks=jQuery.propHooks[name];}if(value!==undefined){if(hooks&&"set"in hooks&&(ret=hooks.set(elem,value,name))!==undefined){return ret;}else{return elem[name]=value;}}else{if(hooks&&"get"in hooks&&(ret=hooks.get(elem,name))!==null){return ret;}else{return elem[name];}}},propHooks:{tabIndex:{get:function get(elem){// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode=elem.getAttributeNode("tabindex");return attributeNode&&attributeNode.specified?parseInt(attributeNode.value,10):rfocusable.test(elem.nodeName)||rclickable.test(elem.nodeName)&&elem.href?0:undefined;}}}});// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
jQuery.attrHooks.tabindex=jQuery.propHooks.tabIndex;// Hook for boolean attributes
boolHook={get:function get(elem,name){// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,property=jQuery.prop(elem,name);return property===true||typeof property!=="boolean"&&(attrNode=elem.getAttributeNode(name))&&attrNode.nodeValue!==false?name.toLowerCase():undefined;},set:function set(elem,value,name){var propName;if(value===false){// Remove boolean attributes when set to false
jQuery.removeAttr(elem,name);}else{// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName=jQuery.propFix[name]||name;if(propName in elem){// Only set the IDL specifically if it already exists on the element
elem[propName]=true;}elem.setAttribute(name,name.toLowerCase());}return name;}};// IE6/7 do not support getting/setting some attributes with get/setAttribute
if(!getSetAttribute){fixSpecified={name:true,id:true};// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook=jQuery.valHooks.button={get:function get(elem,name){var ret;ret=elem.getAttributeNode(name);return ret&&(fixSpecified[name]?ret.nodeValue!=="":ret.specified)?ret.nodeValue:undefined;},set:function set(elem,value,name){// Set the existing or create a new attribute node
var ret=elem.getAttributeNode(name);if(!ret){ret=document.createAttribute(name);elem.setAttributeNode(ret);}return ret.nodeValue=value+"";}};// Apply the nodeHook to tabindex
jQuery.attrHooks.tabindex.set=nodeHook.set;// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each(["width","height"],function(i,name){jQuery.attrHooks[name]=jQuery.extend(jQuery.attrHooks[name],{set:function set(elem,value){if(value===""){elem.setAttribute(name,"auto");return value;}}});});// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable={get:nodeHook.get,set:function set(elem,value,name){if(value===""){value="false";}nodeHook.set(elem,value,name);}};}// Some attributes require a special call on IE
if(!jQuery.support.hrefNormalized){jQuery.each(["href","src","width","height"],function(i,name){jQuery.attrHooks[name]=jQuery.extend(jQuery.attrHooks[name],{get:function get(elem){var ret=elem.getAttribute(name,2);return ret===null?undefined:ret;}});});}if(!jQuery.support.style){jQuery.attrHooks.style={get:function get(elem){// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase()||undefined;},set:function set(elem,value){return elem.style.cssText=""+value;}};}// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if(!jQuery.support.optSelected){jQuery.propHooks.selected=jQuery.extend(jQuery.propHooks.selected,{get:function get(elem){var parent=elem.parentNode;if(parent){parent.selectedIndex;// Make sure that it also works with optgroups, see #5701
if(parent.parentNode){parent.parentNode.selectedIndex;}}return null;}});}// IE6/7 call enctype encoding
if(!jQuery.support.enctype){jQuery.propFix.enctype="encoding";}// Radios and checkboxes getter/setter
if(!jQuery.support.checkOn){jQuery.each(["radio","checkbox"],function(){jQuery.valHooks[this]={get:function get(elem){// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value")===null?"on":elem.value;}};});}jQuery.each(["radio","checkbox"],function(){jQuery.valHooks[this]=jQuery.extend(jQuery.valHooks[this],{set:function set(elem,value){if(jQuery.isArray(value)){return elem.checked=jQuery.inArray(jQuery(elem).val(),value)>=0;}}});});var rformElems=/^(?:textarea|input|select)$/i,rtypenamespace=/^([^\.]*)?(?:\.(.+))?$/,rhoverHack=/\bhover(\.\S+)?\b/,rkeyEvent=/^key/,rmouseEvent=/^(?:mouse|contextmenu)|click/,rfocusMorph=/^(?:focusinfocus|focusoutblur)$/,rquickIs=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,quickParse=function quickParse(selector){var quick=rquickIs.exec(selector);if(quick){//   0  1    2   3
// [ _, tag, id, class ]
quick[1]=(quick[1]||"").toLowerCase();quick[3]=quick[3]&&new RegExp("(?:^|\\s)"+quick[3]+"(?:\\s|$)");}return quick;},quickIs=function quickIs(elem,m){var attrs=elem.attributes||{};return(!m[1]||elem.nodeName.toLowerCase()===m[1])&&(!m[2]||(attrs.id||{}).value===m[2])&&(!m[3]||m[3].test((attrs["class"]||{}).value));},hoverHack=function hoverHack(events){return jQuery.event.special.hover?events:events.replace(rhoverHack,"mouseenter$1 mouseleave$1");};/*
     * Helper functions for managing events -- not part of the public interface.
     * Props to Dean Edwards' addEvent library for many of the ideas.
     */jQuery.event={add:function add(elem,types,handler,data,selector){var elemData,_eventHandle,events,t,tns,type,namespaces,handleObj,handleObjIn,quick,handlers,special;// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if(elem.nodeType===3||elem.nodeType===8||!types||!handler||!(elemData=jQuery._data(elem))){return;}// Caller can pass in an object of custom data in lieu of the handler
if(handler.handler){handleObjIn=handler;handler=handleObjIn.handler;}// Make sure that the handler has a unique ID, used to find/remove it later
if(!handler.guid){handler.guid=jQuery.guid++;}// Init the element's event structure and main handler, if this is the first
events=elemData.events;if(!events){elemData.events=events={};}_eventHandle=elemData.handle;if(!_eventHandle){elemData.handle=_eventHandle=function eventHandle(e){// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery!=="undefined"&&(!e||jQuery.event.triggered!==e.type)?jQuery.event.dispatch.apply(_eventHandle.elem,arguments):undefined;};// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
_eventHandle.elem=elem;}// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types=jQuery.trim(hoverHack(types)).split(" ");for(t=0;t<types.length;t++){tns=rtypenamespace.exec(types[t])||[];type=tns[1];namespaces=(tns[2]||"").split(".").sort();// If event changes its type, use the special event handlers for the changed type
special=jQuery.event.special[type]||{};// If selector defined, determine special event api type, otherwise given type
type=(selector?special.delegateType:special.bindType)||type;// Update special based on newly reset type
special=jQuery.event.special[type]||{};// handleObj is passed to all event handlers
handleObj=jQuery.extend({type:type,origType:tns[1],data:data,handler:handler,guid:handler.guid,selector:selector,quick:quickParse(selector),namespace:namespaces.join(".")},handleObjIn);// Init the event handler queue if we're the first
handlers=events[type];if(!handlers){handlers=events[type]=[];handlers.delegateCount=0;// Only use addEventListener/attachEvent if the special events handler returns false
if(!special.setup||special.setup.call(elem,data,namespaces,_eventHandle)===false){// Bind the global event handler to the element
if(elem.addEventListener){elem.addEventListener(type,_eventHandle,false);}else if(elem.attachEvent){elem.attachEvent("on"+type,_eventHandle);}}}if(special.add){special.add.call(elem,handleObj);if(!handleObj.handler.guid){handleObj.handler.guid=handler.guid;}}// Add to the element's handler list, delegates in front
if(selector){handlers.splice(handlers.delegateCount++,0,handleObj);}else{handlers.push(handleObj);}// Keep track of which events have ever been used, for event optimization
jQuery.event.global[type]=true;}// Nullify elem to prevent memory leaks in IE
elem=null;},global:{},// Detach an event or set of events from an element
remove:function remove(elem,types,handler,selector,mappedTypes){var elemData=jQuery.hasData(elem)&&jQuery._data(elem),t,tns,type,origType,namespaces,origCount,j,events,special,handle,eventType,handleObj;if(!elemData||!(events=elemData.events)){return;}// Once for each type.namespace in types; type may be omitted
types=jQuery.trim(hoverHack(types||"")).split(" ");for(t=0;t<types.length;t++){tns=rtypenamespace.exec(types[t])||[];type=origType=tns[1];namespaces=tns[2];// Unbind all events (on this namespace, if provided) for the element
if(!type){for(type in events){jQuery.event.remove(elem,type+types[t],handler,selector,true);}continue;}special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;eventType=events[type]||[];origCount=eventType.length;namespaces=namespaces?new RegExp("(^|\\.)"+namespaces.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;// Remove matching events
for(j=0;j<eventType.length;j++){handleObj=eventType[j];if((mappedTypes||origType===handleObj.origType)&&(!handler||handler.guid===handleObj.guid)&&(!namespaces||namespaces.test(handleObj.namespace))&&(!selector||selector===handleObj.selector||selector==="**"&&handleObj.selector)){eventType.splice(j--,1);if(handleObj.selector){eventType.delegateCount--;}if(special.remove){special.remove.call(elem,handleObj);}}}// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if(eventType.length===0&&origCount!==eventType.length){if(!special.teardown||special.teardown.call(elem,namespaces)===false){jQuery.removeEvent(elem,type,elemData.handle);}delete events[type];}}// Remove the expando if it's no longer used
if(jQuery.isEmptyObject(events)){handle=elemData.handle;if(handle){handle.elem=null;}// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData(elem,["events","handle"],true);}},// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent:{"getData":true,"setData":true,"changeData":true},trigger:function trigger(event,data,elem,onlyHandlers){// Don't do events on text and comment nodes
if(elem&&(elem.nodeType===3||elem.nodeType===8)){return;}// Event object or event type
var type=event.type||event,namespaces=[],cache,exclusive,i,cur,old,ontype,special,handle,eventPath,bubbleType;// focus/blur morphs to focusin/out; ensure we're not firing them right now
if(rfocusMorph.test(type+jQuery.event.triggered)){return;}if(type.indexOf("!")>=0){// Exclusive events trigger only for the exact event (no namespaces)
type=type.slice(0,-1);exclusive=true;}if(type.indexOf(".")>=0){// Namespaced trigger; create a regexp to match event type in handle()
namespaces=type.split(".");type=namespaces.shift();namespaces.sort();}if((!elem||jQuery.event.customEvent[type])&&!jQuery.event.global[type]){// No jQuery handlers for this event type, and it can't have inline handlers
return;}// Caller can pass in an Event, Object, or just an event type string
event=(typeof event==="undefined"?"undefined":_typeof(event))==="object"?// jQuery.Event object
event[jQuery.expando]?event:// Object literal
new jQuery.Event(type,event):// Just the event type (string)
new jQuery.Event(type);event.type=type;event.isTrigger=true;event.exclusive=exclusive;event.namespace=namespaces.join(".");event.namespace_re=event.namespace?new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.)?")+"(\\.|$)"):null;ontype=type.indexOf(":")<0?"on"+type:"";// Handle a global trigger
if(!elem){// TODO: Stop taunting the data cache; remove global events and always attach to document
cache=jQuery.cache;for(i in cache){if(cache[i].events&&cache[i].events[type]){jQuery.event.trigger(event,data,cache[i].handle.elem,true);}}return;}// Clean up the event in case it is being reused
event.result=undefined;if(!event.target){event.target=elem;}// Clone any incoming data and prepend the event, creating the handler arg list
data=data!=null?jQuery.makeArray(data):[];data.unshift(event);// Allow special events to draw outside the lines
special=jQuery.event.special[type]||{};if(special.trigger&&special.trigger.apply(elem,data)===false){return;}// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath=[[elem,special.bindType||type]];if(!onlyHandlers&&!special.noBubble&&!jQuery.isWindow(elem)){bubbleType=special.delegateType||type;cur=rfocusMorph.test(bubbleType+type)?elem:elem.parentNode;old=null;for(;cur;cur=cur.parentNode){eventPath.push([cur,bubbleType]);old=cur;}// Only add window if we got to document (e.g., not plain obj or detached DOM)
if(old&&old===elem.ownerDocument){eventPath.push([old.defaultView||old.parentWindow||window,bubbleType]);}}// Fire handlers on the event path
for(i=0;i<eventPath.length&&!event.isPropagationStopped();i++){cur=eventPath[i][0];event.type=eventPath[i][1];handle=(jQuery._data(cur,"events")||{})[event.type]&&jQuery._data(cur,"handle");if(handle){handle.apply(cur,data);}// Note that this is a bare JS function and not a jQuery handler
handle=ontype&&cur[ontype];if(handle&&jQuery.acceptData(cur)&&handle.apply(cur,data)===false){event.preventDefault();}}event.type=type;// If nobody prevented the default action, do it now
if(!onlyHandlers&&!event.isDefaultPrevented()){if((!special._default||special._default.apply(elem.ownerDocument,data)===false)&&!(type==="click"&&jQuery.nodeName(elem,"a"))&&jQuery.acceptData(elem)){// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if(ontype&&elem[type]&&(type!=="focus"&&type!=="blur"||event.target.offsetWidth!==0)&&!jQuery.isWindow(elem)){// Don't re-trigger an onFOO event when we call its FOO() method
old=elem[ontype];if(old){elem[ontype]=null;}// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered=type;elem[type]();jQuery.event.triggered=undefined;if(old){elem[ontype]=old;}}}}return event.result;},dispatch:function dispatch(event){// Make a writable jQuery.Event from the native event object
event=jQuery.event.fix(event||window.event);var handlers=(jQuery._data(this,"events")||{})[event.type]||[],delegateCount=handlers.delegateCount,args=[].slice.call(arguments,0),run_all=!event.exclusive&&!event.namespace,handlerQueue=[],i,j,cur,jqcur,ret,selMatch,matched,matches,handleObj,sel,related;// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0]=event;event.delegateTarget=this;// Determine handlers that should run if there are delegated events
// Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861)
if(delegateCount&&!event.target.disabled&&!(event.button&&event.type==="click")){// Pregenerate a single jQuery object for reuse with .is()
jqcur=jQuery(this);jqcur.context=this.ownerDocument||this;for(cur=event.target;cur!=this;cur=cur.parentNode||this){selMatch={};matches=[];jqcur[0]=cur;for(i=0;i<delegateCount;i++){handleObj=handlers[i];sel=handleObj.selector;if(selMatch[sel]===undefined){selMatch[sel]=handleObj.quick?quickIs(cur,handleObj.quick):jqcur.is(sel);}if(selMatch[sel]){matches.push(handleObj);}}if(matches.length){handlerQueue.push({elem:cur,matches:matches});}}}// Add the remaining (directly-bound) handlers
if(handlers.length>delegateCount){handlerQueue.push({elem:this,matches:handlers.slice(delegateCount)});}// Run delegates first; they may want to stop propagation beneath us
for(i=0;i<handlerQueue.length&&!event.isPropagationStopped();i++){matched=handlerQueue[i];event.currentTarget=matched.elem;for(j=0;j<matched.matches.length&&!event.isImmediatePropagationStopped();j++){handleObj=matched.matches[j];// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if(run_all||!event.namespace&&!handleObj.namespace||event.namespace_re&&event.namespace_re.test(handleObj.namespace)){event.data=handleObj.data;event.handleObj=handleObj;ret=((jQuery.event.special[handleObj.origType]||{}).handle||handleObj.handler).apply(matched.elem,args);if(ret!==undefined){event.result=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}}}return event.result;},// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement  are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function filter(event,original){// Add which for key events
if(event.which==null){event.which=original.charCode!=null?original.charCode:original.keyCode;}return event;}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function filter(event,original){var eventDoc,doc,body,button=original.button,fromElement=original.fromElement;// Calculate pageX/Y if missing and clientX/Y available
if(event.pageX==null&&original.clientX!=null){eventDoc=event.target.ownerDocument||document;doc=eventDoc.documentElement;body=eventDoc.body;event.pageX=original.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc&&doc.clientLeft||body&&body.clientLeft||0);event.pageY=original.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc&&doc.clientTop||body&&body.clientTop||0);}// Add relatedTarget, if necessary
if(!event.relatedTarget&&fromElement){event.relatedTarget=fromElement===event.target?original.toElement:fromElement;}// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if(!event.which&&button!==undefined){event.which=button&1?1:button&2?3:button&4?2:0;}return event;}},fix:function fix(event){if(event[jQuery.expando]){return event;}// Create a writable copy of the event object and normalize some properties
var i,prop,originalEvent=event,fixHook=jQuery.event.fixHooks[event.type]||{},copy=fixHook.props?this.props.concat(fixHook.props):this.props;event=jQuery.Event(originalEvent);for(i=copy.length;i;){prop=copy[--i];event[prop]=originalEvent[prop];}// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if(!event.target){event.target=originalEvent.srcElement||document;}// Target should not be a text node (#504, Safari)
if(event.target.nodeType===3){event.target=event.target.parentNode;}// For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8)
if(event.metaKey===undefined){event.metaKey=event.ctrlKey;}return fixHook.filter?fixHook.filter(event,originalEvent):event;},special:{ready:{// Make sure the ready event is setup
setup:jQuery.bindReady},load:{// Prevent triggered image.load events from bubbling to window.load
noBubble:true},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function setup(data,namespaces,eventHandle){// We only want to do this special case on windows
if(jQuery.isWindow(this)){this.onbeforeunload=eventHandle;}},teardown:function teardown(namespaces,eventHandle){if(this.onbeforeunload===eventHandle){this.onbeforeunload=null;}}}},simulate:function simulate(type,elem,event,bubble){// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e=jQuery.extend(new jQuery.Event(),event,{type:type,isSimulated:true,originalEvent:{}});if(bubble){jQuery.event.trigger(e,null,elem);}else{jQuery.event.dispatch.call(elem,e);}if(e.isDefaultPrevented()){event.preventDefault();}}};// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle=jQuery.event.dispatch;jQuery.removeEvent=document.removeEventListener?function(elem,type,handle){if(elem.removeEventListener){elem.removeEventListener(type,handle,false);}}:function(elem,type,handle){if(elem.detachEvent){elem.detachEvent("on"+type,handle);}};jQuery.Event=function(src,props){// Allow instantiation without the 'new' keyword
if(!(this instanceof jQuery.Event)){return new jQuery.Event(src,props);}// Event object
if(src&&src.type){this.originalEvent=src;this.type=src.type;// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented=src.defaultPrevented||src.returnValue===false||src.getPreventDefault&&src.getPreventDefault()?returnTrue:returnFalse;// Event type
}else{this.type=src;}// Put explicitly provided properties onto the event object
if(props){jQuery.extend(this,props);}// Create a timestamp if incoming event doesn't have one
this.timeStamp=src&&src.timeStamp||jQuery.now();// Mark it as fixed
this[jQuery.expando]=true;};function returnFalse(){return false;}function returnTrue(){return true;}// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype={preventDefault:function preventDefault(){this.isDefaultPrevented=returnTrue;var e=this.originalEvent;if(!e){return;}// if preventDefault exists run it on the original event
if(e.preventDefault){e.preventDefault();// otherwise set the returnValue property of the original event to false (IE)
}else{e.returnValue=false;}},stopPropagation:function stopPropagation(){this.isPropagationStopped=returnTrue;var e=this.originalEvent;if(!e){return;}// if stopPropagation exists run it on the original event
if(e.stopPropagation){e.stopPropagation();}// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble=true;},stopImmediatePropagation:function stopImmediatePropagation(){this.isImmediatePropagationStopped=returnTrue;this.stopPropagation();},isDefaultPrevented:returnFalse,isPropagationStopped:returnFalse,isImmediatePropagationStopped:returnFalse};// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(orig,fix){jQuery.event.special[orig]={delegateType:fix,bindType:fix,handle:function handle(event){var target=this,related=event.relatedTarget,handleObj=event.handleObj,selector=handleObj.selector,ret;// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if(!related||related!==target&&!jQuery.contains(target,related)){event.type=handleObj.origType;ret=handleObj.handler.apply(this,arguments);event.type=fix;}return ret;}};});// IE submit delegation
if(!jQuery.support.submitBubbles){jQuery.event.special.submit={setup:function setup(){// Only need this for delegated form submit events
if(jQuery.nodeName(this,"form")){return false;}// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add(this,"click._submit keypress._submit",function(e){// Node name check avoids a VML-related crash in IE (#9807)
var elem=e.target,form=jQuery.nodeName(elem,"input")||jQuery.nodeName(elem,"button")?elem.form:undefined;if(form&&!form._submit_attached){jQuery.event.add(form,"submit._submit",function(event){// If form was submitted by the user, bubble the event up the tree
if(this.parentNode&&!event.isTrigger){jQuery.event.simulate("submit",this.parentNode,event,true);}});form._submit_attached=true;}});// return undefined since we don't need an event listener
},teardown:function teardown(){// Only need this for delegated form submit events
if(jQuery.nodeName(this,"form")){return false;}// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove(this,"._submit");}};}// IE change delegation and checkbox/radio fix
if(!jQuery.support.changeBubbles){jQuery.event.special.change={setup:function setup(){if(rformElems.test(this.nodeName)){// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if(this.type==="checkbox"||this.type==="radio"){jQuery.event.add(this,"propertychange._change",function(event){if(event.originalEvent.propertyName==="checked"){this._just_changed=true;}});jQuery.event.add(this,"click._change",function(event){if(this._just_changed&&!event.isTrigger){this._just_changed=false;jQuery.event.simulate("change",this,event,true);}});}return false;}// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add(this,"beforeactivate._change",function(e){var elem=e.target;if(rformElems.test(elem.nodeName)&&!elem._change_attached){jQuery.event.add(elem,"change._change",function(event){if(this.parentNode&&!event.isSimulated&&!event.isTrigger){jQuery.event.simulate("change",this.parentNode,event,true);}});elem._change_attached=true;}});},handle:function handle(event){var elem=event.target;// Swallow native change events from checkbox/radio, we already triggered them above
if(this!==elem||event.isSimulated||event.isTrigger||elem.type!=="radio"&&elem.type!=="checkbox"){return event.handleObj.handler.apply(this,arguments);}},teardown:function teardown(){jQuery.event.remove(this,"._change");return rformElems.test(this.nodeName);}};}// Create "bubbling" focus and blur events
if(!jQuery.support.focusinBubbles){jQuery.each({focus:"focusin",blur:"focusout"},function(orig,fix){// Attach a single capturing handler while someone wants focusin/focusout
var attaches=0,handler=function handler(event){jQuery.event.simulate(fix,event.target,jQuery.event.fix(event),true);};jQuery.event.special[fix]={setup:function setup(){if(attaches++===0){document.addEventListener(orig,handler,true);}},teardown:function teardown(){if(--attaches===0){document.removeEventListener(orig,handler,true);}}};});}jQuery.fn.extend({on:function on(types,selector,data,fn,/*INTERNAL*/one){var origFn,type;// Types can be a map of types/handlers
if((typeof types==="undefined"?"undefined":_typeof(types))==="object"){// ( types-Object, selector, data )
if(typeof selector!=="string"){// ( types-Object, data )
data=selector;selector=undefined;}for(type in types){this.on(type,selector,data,types[type],one);}return this;}if(data==null&&fn==null){// ( types, fn )
fn=selector;data=selector=undefined;}else if(fn==null){if(typeof selector==="string"){// ( types, selector, fn )
fn=data;data=undefined;}else{// ( types, data, fn )
fn=data;data=selector;selector=undefined;}}if(fn===false){fn=returnFalse;}else if(!fn){return this;}if(one===1){origFn=fn;fn=function fn(event){// Can use an empty set, since event contains the info
jQuery().off(event);return origFn.apply(this,arguments);};// Use same guid so caller can remove using origFn
fn.guid=origFn.guid||(origFn.guid=jQuery.guid++);}return this.each(function(){jQuery.event.add(this,types,fn,data,selector);});},one:function one(types,selector,data,fn){return this.on.call(this,types,selector,data,fn,1);},off:function off(types,selector,fn){if(types&&types.preventDefault&&types.handleObj){// ( event )  dispatched jQuery.Event
var handleObj=types.handleObj;jQuery(types.delegateTarget).off(handleObj.namespace?handleObj.type+"."+handleObj.namespace:handleObj.type,handleObj.selector,handleObj.handler);return this;}if((typeof types==="undefined"?"undefined":_typeof(types))==="object"){// ( types-object [, selector] )
for(var type in types){this.off(type,selector,types[type]);}return this;}if(selector===false||typeof selector==="function"){// ( types [, fn] )
fn=selector;selector=undefined;}if(fn===false){fn=returnFalse;}return this.each(function(){jQuery.event.remove(this,types,fn,selector);});},bind:function bind(types,data,fn){return this.on(types,null,data,fn);},unbind:function unbind(types,fn){return this.off(types,null,fn);},live:function live(types,data,fn){jQuery(this.context).on(types,this.selector,data,fn);return this;},die:function die(types,fn){jQuery(this.context).off(types,this.selector||"**",fn);return this;},delegate:function delegate(selector,types,data,fn){return this.on(types,selector,data,fn);},undelegate:function undelegate(selector,types,fn){// ( namespace ) or ( selector, types [, fn] )
return arguments.length==1?this.off(selector,"**"):this.off(types,selector,fn);},trigger:function trigger(type,data){return this.each(function(){jQuery.event.trigger(type,data,this);});},triggerHandler:function triggerHandler(type,data){if(this[0]){return jQuery.event.trigger(type,data,this[0],true);}},toggle:function toggle(fn){// Save reference to arguments for access in closure
var args=arguments,guid=fn.guid||jQuery.guid++,i=0,toggler=function toggler(event){// Figure out which function to execute
var lastToggle=(jQuery._data(this,"lastToggle"+fn.guid)||0)%i;jQuery._data(this,"lastToggle"+fn.guid,lastToggle+1);// Make sure that clicks stop
event.preventDefault();// and execute the function
return args[lastToggle].apply(this,arguments)||false;};// link all the functions, so any of them can unbind this click handler
toggler.guid=guid;while(i<args.length){args[i++].guid=guid;}return this.click(toggler);},hover:function hover(fnOver,fnOut){return this.mouseenter(fnOver).mouseleave(fnOut||fnOver);}});jQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick "+"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave "+"change select submit keydown keypress keyup error contextmenu").split(" "),function(i,name){// Handle event binding
jQuery.fn[name]=function(data,fn){if(fn==null){fn=data;data=null;}return arguments.length>0?this.on(name,null,data,fn):this.trigger(name);};if(jQuery.attrFn){jQuery.attrFn[name]=true;}if(rkeyEvent.test(name)){jQuery.event.fixHooks[name]=jQuery.event.keyHooks;}if(rmouseEvent.test(name)){jQuery.event.fixHooks[name]=jQuery.event.mouseHooks;}});/*!
     * Sizzle CSS Selector Engine
     *  Copyright 2011, The Dojo Foundation
     *  Released under the MIT, BSD, and GPL Licenses.
     *  More information: http://sizzlejs.com/
     */(function(){var chunker=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,expando="sizcache"+(Math.random()+'').replace('.',''),done=0,toString=Object.prototype.toString,hasDuplicate=false,baseHasDuplicate=true,rBackslash=/\\/g,rReturn=/\r\n/g,rNonWord=/\W/;// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
//   Thus far that includes Google Chrome.
[0,0].sort(function(){baseHasDuplicate=false;return 0;});var _Sizzle2=function Sizzle(selector,context,results,seed){results=results||[];context=context||document;var origContext=context;if(context.nodeType!==1&&context.nodeType!==9){return[];}if(!selector||typeof selector!=="string"){return results;}var m,set,checkSet,extra,ret,cur,pop,i,prune=true,contextXML=_Sizzle2.isXML(context),parts=[],soFar=selector;// Reset the position of the chunker regexp (start from head)
do{chunker.exec("");m=chunker.exec(soFar);if(m){soFar=m[3];parts.push(m[1]);if(m[2]){extra=m[3];break;}}}while(m);if(parts.length>1&&origPOS.exec(selector)){if(parts.length===2&&Expr.relative[parts[0]]){set=posProcess(parts[0]+parts[1],context,seed);}else{set=Expr.relative[parts[0]]?[context]:_Sizzle2(parts.shift(),context);while(parts.length){selector=parts.shift();if(Expr.relative[selector]){selector+=parts.shift();}set=posProcess(selector,set,seed);}}}else{// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if(!seed&&parts.length>1&&context.nodeType===9&&!contextXML&&Expr.match.ID.test(parts[0])&&!Expr.match.ID.test(parts[parts.length-1])){ret=_Sizzle2.find(parts.shift(),context,contextXML);context=ret.expr?_Sizzle2.filter(ret.expr,ret.set)[0]:ret.set[0];}if(context){ret=seed?{expr:parts.pop(),set:makeArray(seed)}:_Sizzle2.find(parts.pop(),parts.length===1&&(parts[0]==="~"||parts[0]==="+")&&context.parentNode?context.parentNode:context,contextXML);set=ret.expr?_Sizzle2.filter(ret.expr,ret.set):ret.set;if(parts.length>0){checkSet=makeArray(set);}else{prune=false;}while(parts.length){cur=parts.pop();pop=cur;if(!Expr.relative[cur]){cur="";}else{pop=parts.pop();}if(pop==null){pop=context;}Expr.relative[cur](checkSet,pop,contextXML);}}else{checkSet=parts=[];}}if(!checkSet){checkSet=set;}if(!checkSet){_Sizzle2.error(cur||selector);}if(toString.call(checkSet)==="[object Array]"){if(!prune){results.push.apply(results,checkSet);}else if(context&&context.nodeType===1){for(i=0;checkSet[i]!=null;i++){if(checkSet[i]&&(checkSet[i]===true||checkSet[i].nodeType===1&&_Sizzle2.contains(context,checkSet[i]))){results.push(set[i]);}}}else{for(i=0;checkSet[i]!=null;i++){if(checkSet[i]&&checkSet[i].nodeType===1){results.push(set[i]);}}}}else{makeArray(checkSet,results);}if(extra){_Sizzle2(extra,origContext,results,seed);_Sizzle2.uniqueSort(results);}return results;};_Sizzle2.uniqueSort=function(results){if(sortOrder){hasDuplicate=baseHasDuplicate;results.sort(sortOrder);if(hasDuplicate){for(var i=1;i<results.length;i++){if(results[i]===results[i-1]){results.splice(i--,1);}}}}return results;};_Sizzle2.matches=function(expr,set){return _Sizzle2(expr,null,null,set);};_Sizzle2.matchesSelector=function(node,expr){return _Sizzle2(expr,null,null,[node]).length>0;};_Sizzle2.find=function(expr,context,isXML){var set,i,len,match,type,left;if(!expr){return[];}for(i=0,len=Expr.order.length;i<len;i++){type=Expr.order[i];if(match=Expr.leftMatch[type].exec(expr)){left=match[1];match.splice(1,1);if(left.substr(left.length-1)!=="\\"){match[1]=(match[1]||"").replace(rBackslash,"");set=Expr.find[type](match,context,isXML);if(set!=null){expr=expr.replace(Expr.match[type],"");break;}}}}if(!set){set=typeof context.getElementsByTagName!=="undefined"?context.getElementsByTagName("*"):[];}return{set:set,expr:expr};};_Sizzle2.filter=function(expr,set,inplace,not){var match,anyFound,type,found,item,filter,left,i,pass,old=expr,result=[],curLoop=set,isXMLFilter=set&&set[0]&&_Sizzle2.isXML(set[0]);while(expr&&set.length){for(type in Expr.filter){if((match=Expr.leftMatch[type].exec(expr))!=null&&match[2]){filter=Expr.filter[type];left=match[1];anyFound=false;match.splice(1,1);if(left.substr(left.length-1)==="\\"){continue;}if(curLoop===result){result=[];}if(Expr.preFilter[type]){match=Expr.preFilter[type](match,curLoop,inplace,result,not,isXMLFilter);if(!match){anyFound=found=true;}else if(match===true){continue;}}if(match){for(i=0;(item=curLoop[i])!=null;i++){if(item){found=filter(item,match,i,curLoop);pass=not^found;if(inplace&&found!=null){if(pass){anyFound=true;}else{curLoop[i]=false;}}else if(pass){result.push(item);anyFound=true;}}}}if(found!==undefined){if(!inplace){curLoop=result;}expr=expr.replace(Expr.match[type],"");if(!anyFound){return[];}break;}}}// Improper expression
if(expr===old){if(anyFound==null){_Sizzle2.error(expr);}else{break;}}old=expr;}return curLoop;};_Sizzle2.error=function(msg){throw new Error("Syntax error, unrecognized expression: "+msg);};/**
         * Utility function for retreiving the text value of an array of DOM nodes
         * @param {Array|Element} elem
         */var getText=_Sizzle2.getText=function(elem){var i,node,nodeType=elem.nodeType,ret="";if(nodeType){if(nodeType===1||nodeType===9){// Use textContent || innerText for elements
if(typeof elem.textContent==='string'){return elem.textContent;}else if(typeof elem.innerText==='string'){// Replace IE's carriage returns
return elem.innerText.replace(rReturn,'');}else{// Traverse it's children
for(elem=elem.firstChild;elem;elem=elem.nextSibling){ret+=getText(elem);}}}else if(nodeType===3||nodeType===4){return elem.nodeValue;}}else{// If no nodeType, this is expected to be an array
for(i=0;node=elem[i];i++){// Do not traverse comment nodes
if(node.nodeType!==8){ret+=getText(node);}}}return ret;};var Expr=_Sizzle2.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function href(elem){return elem.getAttribute("href");},type:function type(elem){return elem.getAttribute("type");}},relative:{"+":function _(checkSet,part){var isPartStr=typeof part==="string",isTag=isPartStr&&!rNonWord.test(part),isPartStrNotTag=isPartStr&&!isTag;if(isTag){part=part.toLowerCase();}for(var i=0,l=checkSet.length,elem;i<l;i++){if(elem=checkSet[i]){while((elem=elem.previousSibling)&&elem.nodeType!==1){}checkSet[i]=isPartStrNotTag||elem&&elem.nodeName.toLowerCase()===part?elem||false:elem===part;}}if(isPartStrNotTag){_Sizzle2.filter(part,checkSet,true);}},">":function _(checkSet,part){var elem,isPartStr=typeof part==="string",i=0,l=checkSet.length;if(isPartStr&&!rNonWord.test(part)){part=part.toLowerCase();for(;i<l;i++){elem=checkSet[i];if(elem){var parent=elem.parentNode;checkSet[i]=parent.nodeName.toLowerCase()===part?parent:false;}}}else{for(;i<l;i++){elem=checkSet[i];if(elem){checkSet[i]=isPartStr?elem.parentNode:elem.parentNode===part;}}if(isPartStr){_Sizzle2.filter(part,checkSet,true);}}},"":function _(checkSet,part,isXML){var nodeCheck,doneName=done++,checkFn=dirCheck;if(typeof part==="string"&&!rNonWord.test(part)){part=part.toLowerCase();nodeCheck=part;checkFn=dirNodeCheck;}checkFn("parentNode",part,doneName,checkSet,nodeCheck,isXML);},"~":function _(checkSet,part,isXML){var nodeCheck,doneName=done++,checkFn=dirCheck;if(typeof part==="string"&&!rNonWord.test(part)){part=part.toLowerCase();nodeCheck=part;checkFn=dirNodeCheck;}checkFn("previousSibling",part,doneName,checkSet,nodeCheck,isXML);}},find:{ID:function ID(match,context,isXML){if(typeof context.getElementById!=="undefined"&&!isXML){var m=context.getElementById(match[1]);// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m&&m.parentNode?[m]:[];}},NAME:function NAME(match,context){if(typeof context.getElementsByName!=="undefined"){var ret=[],results=context.getElementsByName(match[1]);for(var i=0,l=results.length;i<l;i++){if(results[i].getAttribute("name")===match[1]){ret.push(results[i]);}}return ret.length===0?null:ret;}},TAG:function TAG(match,context){if(typeof context.getElementsByTagName!=="undefined"){return context.getElementsByTagName(match[1]);}}},preFilter:{CLASS:function CLASS(match,curLoop,inplace,result,not,isXML){match=" "+match[1].replace(rBackslash,"")+" ";if(isXML){return match;}for(var i=0,elem;(elem=curLoop[i])!=null;i++){if(elem){if(not^(elem.className&&(" "+elem.className+" ").replace(/[\t\n\r]/g," ").indexOf(match)>=0)){if(!inplace){result.push(elem);}}else if(inplace){curLoop[i]=false;}}}return false;},ID:function ID(match){return match[1].replace(rBackslash,"");},TAG:function TAG(match,curLoop){return match[1].replace(rBackslash,"").toLowerCase();},CHILD:function CHILD(match){if(match[1]==="nth"){if(!match[2]){_Sizzle2.error(match[0]);}match[2]=match[2].replace(/^\+|\s*/g,'');// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(match[2]==="even"&&"2n"||match[2]==="odd"&&"2n+1"||!/\D/.test(match[2])&&"0n+"+match[2]||match[2]);// calculate the numbers (first)n+(last) including if they are negative
match[2]=test[1]+(test[2]||1)-0;match[3]=test[3]-0;}else if(match[2]){_Sizzle2.error(match[0]);}// TODO: Move to normal caching system
match[0]=done++;return match;},ATTR:function ATTR(match,curLoop,inplace,result,not,isXML){var name=match[1]=match[1].replace(rBackslash,"");if(!isXML&&Expr.attrMap[name]){match[1]=Expr.attrMap[name];}// Handle if an un-quoted value was used
match[4]=(match[4]||match[5]||"").replace(rBackslash,"");if(match[2]==="~="){match[4]=" "+match[4]+" ";}return match;},PSEUDO:function PSEUDO(match,curLoop,inplace,result,not){if(match[1]==="not"){// If we're dealing with a complex expression, or a simple one
if((chunker.exec(match[3])||"").length>1||/^\w/.test(match[3])){match[3]=_Sizzle2(match[3],null,null,curLoop);}else{var ret=_Sizzle2.filter(match[3],curLoop,inplace,true^not);if(!inplace){result.push.apply(result,ret);}return false;}}else if(Expr.match.POS.test(match[0])||Expr.match.CHILD.test(match[0])){return true;}return match;},POS:function POS(match){match.unshift(true);return match;}},filters:{enabled:function enabled(elem){return elem.disabled===false&&elem.type!=="hidden";},disabled:function disabled(elem){return elem.disabled===true;},checked:function checked(elem){return elem.checked===true;},selected:function selected(elem){// Accessing this property makes selected-by-default
// options in Safari work properly
if(elem.parentNode){elem.parentNode.selectedIndex;}return elem.selected===true;},parent:function parent(elem){return!!elem.firstChild;},empty:function empty(elem){return!elem.firstChild;},has:function has(elem,i,match){return!!_Sizzle2(match[3],elem).length;},header:function header(elem){return /h\d/i.test(elem.nodeName);},text:function text(elem){var attr=elem.getAttribute("type"),type=elem.type;// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase()==="input"&&"text"===type&&(attr===type||attr===null);},radio:function radio(elem){return elem.nodeName.toLowerCase()==="input"&&"radio"===elem.type;},checkbox:function checkbox(elem){return elem.nodeName.toLowerCase()==="input"&&"checkbox"===elem.type;},file:function file(elem){return elem.nodeName.toLowerCase()==="input"&&"file"===elem.type;},password:function password(elem){return elem.nodeName.toLowerCase()==="input"&&"password"===elem.type;},submit:function submit(elem){var name=elem.nodeName.toLowerCase();return(name==="input"||name==="button")&&"submit"===elem.type;},image:function image(elem){return elem.nodeName.toLowerCase()==="input"&&"image"===elem.type;},reset:function reset(elem){var name=elem.nodeName.toLowerCase();return(name==="input"||name==="button")&&"reset"===elem.type;},button:function button(elem){var name=elem.nodeName.toLowerCase();return name==="input"&&"button"===elem.type||name==="button";},input:function input(elem){return /input|select|textarea|button/i.test(elem.nodeName);},focus:function focus(elem){return elem===elem.ownerDocument.activeElement;}},setFilters:{first:function first(elem,i){return i===0;},last:function last(elem,i,match,array){return i===array.length-1;},even:function even(elem,i){return i%2===0;},odd:function odd(elem,i){return i%2===1;},lt:function lt(elem,i,match){return i<match[3]-0;},gt:function gt(elem,i,match){return i>match[3]-0;},nth:function nth(elem,i,match){return match[3]-0===i;},eq:function eq(elem,i,match){return match[3]-0===i;}},filter:{PSEUDO:function PSEUDO(elem,match,i,array){var name=match[1],filter=Expr.filters[name];if(filter){return filter(elem,i,match,array);}else if(name==="contains"){return(elem.textContent||elem.innerText||getText([elem])||"").indexOf(match[3])>=0;}else if(name==="not"){var not=match[3];for(var j=0,l=not.length;j<l;j++){if(not[j]===elem){return false;}}return true;}else{_Sizzle2.error(name);}},CHILD:function CHILD(elem,match){var first,last,doneName,parent,cache,count,diff,type=match[1],node=elem;switch(type){case"only":case"first":while(node=node.previousSibling){if(node.nodeType===1){return false;}}if(type==="first"){return true;}node=elem;case"last":while(node=node.nextSibling){if(node.nodeType===1){return false;}}return true;case"nth":first=match[2];last=match[3];if(first===1&&last===0){return true;}doneName=match[0];parent=elem.parentNode;if(parent&&(parent[expando]!==doneName||!elem.nodeIndex)){count=0;for(node=parent.firstChild;node;node=node.nextSibling){if(node.nodeType===1){node.nodeIndex=++count;}}parent[expando]=doneName;}diff=elem.nodeIndex-last;if(first===0){return diff===0;}else{return diff%first===0&&diff/first>=0;}}},ID:function ID(elem,match){return elem.nodeType===1&&elem.getAttribute("id")===match;},TAG:function TAG(elem,match){return match==="*"&&elem.nodeType===1||!!elem.nodeName&&elem.nodeName.toLowerCase()===match;},CLASS:function CLASS(elem,match){return(" "+(elem.className||elem.getAttribute("class"))+" ").indexOf(match)>-1;},ATTR:function ATTR(elem,match){var name=match[1],result=_Sizzle2.attr?_Sizzle2.attr(elem,name):Expr.attrHandle[name]?Expr.attrHandle[name](elem):elem[name]!=null?elem[name]:elem.getAttribute(name),value=result+"",type=match[2],check=match[4];return result==null?type==="!=":!type&&_Sizzle2.attr?result!=null:type==="="?value===check:type==="*="?value.indexOf(check)>=0:type==="~="?(" "+value+" ").indexOf(check)>=0:!check?value&&result!==false:type==="!="?value!==check:type==="^="?value.indexOf(check)===0:type==="$="?value.substr(value.length-check.length)===check:type==="|="?value===check||value.substr(0,check.length+1)===check+"-":false;},POS:function POS(elem,match,i,array){var name=match[2],filter=Expr.setFilters[name];if(filter){return filter(elem,i,match,array);}}}};var origPOS=Expr.match.POS,fescape=function fescape(all,num){return"\\"+(num-0+1);};for(var type in Expr.match){Expr.match[type]=new RegExp(Expr.match[type].source+/(?![^\[]*\])(?![^\(]*\))/.source);Expr.leftMatch[type]=new RegExp(/(^(?:.|\r|\n)*?)/.source+Expr.match[type].source.replace(/\\(\d+)/g,fescape));}var makeArray=function makeArray(array,results){array=Array.prototype.slice.call(array,0);if(results){results.push.apply(results,array);return results;}return array;};// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try{Array.prototype.slice.call(document.documentElement.childNodes,0)[0].nodeType;// Provide a fallback method if it does not work
}catch(e){makeArray=function makeArray(array,results){var i=0,ret=results||[];if(toString.call(array)==="[object Array]"){Array.prototype.push.apply(ret,array);}else{if(typeof array.length==="number"){for(var l=array.length;i<l;i++){ret.push(array[i]);}}else{for(;array[i];i++){ret.push(array[i]);}}}return ret;};}var sortOrder,siblingCheck;if(document.documentElement.compareDocumentPosition){sortOrder=function sortOrder(a,b){if(a===b){hasDuplicate=true;return 0;}if(!a.compareDocumentPosition||!b.compareDocumentPosition){return a.compareDocumentPosition?-1:1;}return a.compareDocumentPosition(b)&4?-1:1;};}else{sortOrder=function sortOrder(a,b){// The nodes are identical, we can exit early
if(a===b){hasDuplicate=true;return 0;// Fallback to using sourceIndex (in IE) if it's available on both nodes
}else if(a.sourceIndex&&b.sourceIndex){return a.sourceIndex-b.sourceIndex;}var al,bl,ap=[],bp=[],aup=a.parentNode,bup=b.parentNode,cur=aup;// If the nodes are siblings (or identical) we can do a quick check
if(aup===bup){return siblingCheck(a,b);// If no parents were found then the nodes are disconnected
}else if(!aup){return-1;}else if(!bup){return 1;}// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while(cur){ap.unshift(cur);cur=cur.parentNode;}cur=bup;while(cur){bp.unshift(cur);cur=cur.parentNode;}al=ap.length;bl=bp.length;// Start walking down the tree looking for a discrepancy
for(var i=0;i<al&&i<bl;i++){if(ap[i]!==bp[i]){return siblingCheck(ap[i],bp[i]);}}// We ended someplace up the tree so do a sibling check
return i===al?siblingCheck(a,bp[i],-1):siblingCheck(ap[i],b,1);};siblingCheck=function siblingCheck(a,b,ret){if(a===b){return ret;}var cur=a.nextSibling;while(cur){if(cur===b){return-1;}cur=cur.nextSibling;}return 1;};}// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){// We're going to inject a fake input element with a specified name
var form=document.createElement("div"),id="script"+new Date().getTime(),root=document.documentElement;form.innerHTML="<a name='"+id+"'/>";// Inject it into the root element, check its status, and remove it quickly
root.insertBefore(form,root.firstChild);// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if(document.getElementById(id)){Expr.find.ID=function(match,context,isXML){if(typeof context.getElementById!=="undefined"&&!isXML){var m=context.getElementById(match[1]);return m?m.id===match[1]||typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id").nodeValue===match[1]?[m]:undefined:[];}};Expr.filter.ID=function(elem,match){var node=typeof elem.getAttributeNode!=="undefined"&&elem.getAttributeNode("id");return elem.nodeType===1&&node&&node.nodeValue===match;};}root.removeChild(form);// release memory in IE
root=form=null;})();(function(){// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div=document.createElement("div");div.appendChild(document.createComment(""));// Make sure no comments are found
if(div.getElementsByTagName("*").length>0){Expr.find.TAG=function(match,context){var results=context.getElementsByTagName(match[1]);// Filter out possible comments
if(match[1]==="*"){var tmp=[];for(var i=0;results[i];i++){if(results[i].nodeType===1){tmp.push(results[i]);}}results=tmp;}return results;};}// Check to see if an attribute returns normalized href attributes
div.innerHTML="<a href='#'></a>";if(div.firstChild&&typeof div.firstChild.getAttribute!=="undefined"&&div.firstChild.getAttribute("href")!=="#"){Expr.attrHandle.href=function(elem){return elem.getAttribute("href",2);};}// release memory in IE
div=null;})();if(document.querySelectorAll){(function(){var oldSizzle=_Sizzle2,div=document.createElement("div"),id="__sizzle__";div.innerHTML="<p class='TEST'></p>";// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if(div.querySelectorAll&&div.querySelectorAll(".TEST").length===0){return;}_Sizzle2=function _Sizzle(query,context,extra,seed){context=context||document;// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if(!seed&&!_Sizzle2.isXML(context)){// See if we find a selector to speed up
var match=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(query);if(match&&(context.nodeType===1||context.nodeType===9)){// Speed-up: Sizzle("TAG")
if(match[1]){return makeArray(context.getElementsByTagName(query),extra);// Speed-up: Sizzle(".CLASS")
}else if(match[2]&&Expr.find.CLASS&&context.getElementsByClassName){return makeArray(context.getElementsByClassName(match[2]),extra);}}if(context.nodeType===9){// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if(query==="body"&&context.body){return makeArray([context.body],extra);// Speed-up: Sizzle("#ID")
}else if(match&&match[3]){var elem=context.getElementById(match[3]);// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if(elem&&elem.parentNode){// Handle the case where IE and Opera return items
// by name instead of ID
if(elem.id===match[3]){return makeArray([elem],extra);}}else{return makeArray([],extra);}}try{return makeArray(context.querySelectorAll(query),extra);}catch(qsaError){}// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
}else if(context.nodeType===1&&context.nodeName.toLowerCase()!=="object"){var oldContext=context,old=context.getAttribute("id"),nid=old||id,hasParent=context.parentNode,relativeHierarchySelector=/^\s*[+~]/.test(query);if(!old){context.setAttribute("id",nid);}else{nid=nid.replace(/'/g,"\\$&");}if(relativeHierarchySelector&&hasParent){context=context.parentNode;}try{if(!relativeHierarchySelector||hasParent){return makeArray(context.querySelectorAll("[id='"+nid+"'] "+query),extra);}}catch(pseudoError){}finally{if(!old){oldContext.removeAttribute("id");}}}}return oldSizzle(query,context,extra,seed);};for(var prop in oldSizzle){_Sizzle2[prop]=oldSizzle[prop];}// release memory in IE
div=null;})();}(function(){var html=document.documentElement,matches=html.matchesSelector||html.mozMatchesSelector||html.webkitMatchesSelector||html.msMatchesSelector;if(matches){// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch=!matches.call(document.createElement("div"),"div"),pseudoWorks=false;try{// This should fail with an exception
// Gecko does not error, returns false instead
matches.call(document.documentElement,"[test!='']:sizzle");}catch(pseudoError){pseudoWorks=true;}_Sizzle2.matchesSelector=function(node,expr){// Make sure that attribute selectors are quoted
expr=expr.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!_Sizzle2.isXML(node)){try{if(pseudoWorks||!Expr.match.PSEUDO.test(expr)&&!/!=/.test(expr)){var ret=matches.call(node,expr);// IE 9's matchesSelector returns false on disconnected nodes
if(ret||!disconnectedMatch||// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document&&node.document.nodeType!==11){return ret;}}}catch(e){}}return _Sizzle2(expr,null,null,[node]).length>0;};}})();(function(){var div=document.createElement("div");div.innerHTML="<div class='test e'></div><div class='test'></div>";// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if(!div.getElementsByClassName||div.getElementsByClassName("e").length===0){return;}// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className="e";if(div.getElementsByClassName("e").length===1){return;}Expr.order.splice(1,0,"CLASS");Expr.find.CLASS=function(match,context,isXML){if(typeof context.getElementsByClassName!=="undefined"&&!isXML){return context.getElementsByClassName(match[1]);}};// release memory in IE
div=null;})();function dirNodeCheck(dir,cur,doneName,checkSet,nodeCheck,isXML){for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem){var match=false;elem=elem[dir];while(elem){if(elem[expando]===doneName){match=checkSet[elem.sizset];break;}if(elem.nodeType===1&&!isXML){elem[expando]=doneName;elem.sizset=i;}if(elem.nodeName.toLowerCase()===cur){match=elem;break;}elem=elem[dir];}checkSet[i]=match;}}}function dirCheck(dir,cur,doneName,checkSet,nodeCheck,isXML){for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem){var match=false;elem=elem[dir];while(elem){if(elem[expando]===doneName){match=checkSet[elem.sizset];break;}if(elem.nodeType===1){if(!isXML){elem[expando]=doneName;elem.sizset=i;}if(typeof cur!=="string"){if(elem===cur){match=true;break;}}else if(_Sizzle2.filter(cur,[elem]).length>0){match=elem;break;}}elem=elem[dir];}checkSet[i]=match;}}}if(document.documentElement.contains){_Sizzle2.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):true);};}else if(document.documentElement.compareDocumentPosition){_Sizzle2.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16);};}else{_Sizzle2.contains=function(){return false;};}_Sizzle2.isXML=function(elem){// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement=(elem?elem.ownerDocument||elem:0).documentElement;return documentElement?documentElement.nodeName!=="HTML":false;};var posProcess=function posProcess(selector,context,seed){var match,tmpSet=[],later="",root=context.nodeType?[context]:context;// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while(match=Expr.match.PSEUDO.exec(selector)){later+=match[0];selector=selector.replace(Expr.match.PSEUDO,"");}selector=Expr.relative[selector]?selector+"*":selector;for(var i=0,l=root.length;i<l;i++){_Sizzle2(selector,root[i],tmpSet,seed);}return _Sizzle2.filter(later,tmpSet);};// EXPOSE
// Override sizzle attribute retrieval
_Sizzle2.attr=jQuery.attr;_Sizzle2.selectors.attrMap={};jQuery.find=_Sizzle2;jQuery.expr=_Sizzle2.selectors;jQuery.expr[":"]=jQuery.expr.filters;jQuery.unique=_Sizzle2.uniqueSort;jQuery.text=_Sizzle2.getText;jQuery.isXMLDoc=_Sizzle2.isXML;jQuery.contains=_Sizzle2.contains;})();var runtil=/Until$/,rparentsprev=/^(?:parents|prevUntil|prevAll)/,// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector=/,/,isSimple=/^.[^:#\[\.,]*$/,slice=Array.prototype.slice,POS=jQuery.expr.match.POS,// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique={children:true,contents:true,next:true,prev:true};jQuery.fn.extend({find:function find(selector){var self=this,i,l;if(typeof selector!=="string"){return jQuery(selector).filter(function(){for(i=0,l=self.length;i<l;i++){if(jQuery.contains(self[i],this)){return true;}}});}var ret=this.pushStack("","find",selector),length,n,r;for(i=0,l=this.length;i<l;i++){length=ret.length;jQuery.find(selector,this[i],ret);if(i>0){// Make sure that the results are unique
for(n=length;n<ret.length;n++){for(r=0;r<length;r++){if(ret[r]===ret[n]){ret.splice(n--,1);break;}}}}}return ret;},has:function has(target){var targets=jQuery(target);return this.filter(function(){for(var i=0,l=targets.length;i<l;i++){if(jQuery.contains(this,targets[i])){return true;}}});},not:function not(selector){return this.pushStack(winnow(this,selector,false),"not",selector);},filter:function filter(selector){return this.pushStack(winnow(this,selector,true),"filter",selector);},is:function is(selector){return!!selector&&(typeof selector==="string"?// If this is a positional selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
POS.test(selector)?jQuery(selector,this.context).index(this[0])>=0:jQuery.filter(selector,this).length>0:this.filter(selector).length>0);},closest:function closest(selectors,context){var ret=[],i,l,cur=this[0];// Array (deprecated as of jQuery 1.7)
if(jQuery.isArray(selectors)){var level=1;while(cur&&cur.ownerDocument&&cur!==context){for(i=0;i<selectors.length;i++){if(jQuery(cur).is(selectors[i])){ret.push({selector:selectors[i],elem:cur,level:level});}}cur=cur.parentNode;level++;}return ret;}// String
var pos=POS.test(selectors)||typeof selectors!=="string"?jQuery(selectors,context||this.context):0;for(i=0,l=this.length;i<l;i++){cur=this[i];while(cur){if(pos?pos.index(cur)>-1:jQuery.find.matchesSelector(cur,selectors)){ret.push(cur);break;}else{cur=cur.parentNode;if(!cur||!cur.ownerDocument||cur===context||cur.nodeType===11){break;}}}}ret=ret.length>1?jQuery.unique(ret):ret;return this.pushStack(ret,"closest",selectors);},// Determine the position of an element within
// the matched set of elements
index:function index(elem){// No argument, return index in parent
if(!elem){return this[0]&&this[0].parentNode?this.prevAll().length:-1;}// index in selector
if(typeof elem==="string"){return jQuery.inArray(this[0],jQuery(elem));}// Locate the position of the desired element
return jQuery.inArray(// If it receives a jQuery object, the first element is used
elem.jquery?elem[0]:elem,this);},add:function add(selector,context){var set=typeof selector==="string"?jQuery(selector,context):jQuery.makeArray(selector&&selector.nodeType?[selector]:selector),all=jQuery.merge(this.get(),set);return this.pushStack(isDisconnected(set[0])||isDisconnected(all[0])?all:jQuery.unique(all));},andSelf:function andSelf(){return this.add(this.prevObject);}});// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected(node){return!node||!node.parentNode||node.parentNode.nodeType===11;}jQuery.each({parent:function parent(elem){var parent=elem.parentNode;return parent&&parent.nodeType!==11?parent:null;},parents:function parents(elem){return jQuery.dir(elem,"parentNode");},parentsUntil:function parentsUntil(elem,i,until){return jQuery.dir(elem,"parentNode",until);},next:function next(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function prev(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function nextAll(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function prevAll(elem){return jQuery.dir(elem,"previousSibling");},nextUntil:function nextUntil(elem,i,until){return jQuery.dir(elem,"nextSibling",until);},prevUntil:function prevUntil(elem,i,until){return jQuery.dir(elem,"previousSibling",until);},siblings:function siblings(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function children(elem){return jQuery.sibling(elem.firstChild);},contents:function contents(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(until,selector){var ret=jQuery.map(this,fn,until);if(!runtil.test(name)){selector=until;}if(selector&&typeof selector==="string"){ret=jQuery.filter(selector,ret);}ret=this.length>1&&!guaranteedUnique[name]?jQuery.unique(ret):ret;if((this.length>1||rmultiselector.test(selector))&&rparentsprev.test(name)){ret=ret.reverse();}return this.pushStack(ret,name,slice.call(arguments).join(","));};});jQuery.extend({filter:function filter(expr,elems,not){if(not){expr=":not("+expr+")";}return elems.length===1?jQuery.find.matchesSelector(elems[0],expr)?[elems[0]]:[]:jQuery.find.matches(expr,elems);},dir:function dir(elem,_dir,until){var matched=[],cur=elem[_dir];while(cur&&cur.nodeType!==9&&(until===undefined||cur.nodeType!==1||!jQuery(cur).is(until))){if(cur.nodeType===1){matched.push(cur);}cur=cur[_dir];}return matched;},nth:function nth(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir]){if(cur.nodeType===1&&++num===result){break;}}return cur;},sibling:function sibling(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType===1&&n!==elem){r.push(n);}}return r;}});// Implement the identical functionality for filter and not
function winnow(elements,qualifier,keep){// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier=qualifier||0;if(jQuery.isFunction(qualifier)){return jQuery.grep(elements,function(elem,i){var retVal=!!qualifier.call(elem,i,elem);return retVal===keep;});}else if(qualifier.nodeType){return jQuery.grep(elements,function(elem,i){return elem===qualifier===keep;});}else if(typeof qualifier==="string"){var filtered=jQuery.grep(elements,function(elem){return elem.nodeType===1;});if(isSimple.test(qualifier)){return jQuery.filter(qualifier,filtered,!keep);}else{qualifier=jQuery.filter(qualifier,filtered);}}return jQuery.grep(elements,function(elem,i){return jQuery.inArray(elem,qualifier)>=0===keep;});}function createSafeFragment(document){var list=nodeNames.split("|"),safeFrag=document.createDocumentFragment();if(safeFrag.createElement){while(list.length){safeFrag.createElement(list.pop());}}return safeFrag;}var nodeNames="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|"+"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",rinlinejQuery=/ jQuery\d+="(?:\d+|null)"/g,rleadingWhitespace=/^\s+/,rxhtmlTag=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,rtagName=/<([\w:]+)/,rtbody=/<tbody/i,rhtml=/<|&#?\w+;/,rnoInnerhtml=/<(?:script|style)/i,rnocache=/<(?:script|object|embed|option|style)/i,rnoshimcache=new RegExp("<(?:"+nodeNames+")","i"),// checked="checked" or checked
rchecked=/checked\s*(?:[^=]|=\s*.checked.)/i,rscriptType=/\/(java|ecma)script/i,rcleanScript=/^\s*<!(?:\[CDATA\[|\-\-)/,wrapMap={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},safeFragment=createSafeFragment(document);wrapMap.optgroup=wrapMap.option;wrapMap.tbody=wrapMap.tfoot=wrapMap.colgroup=wrapMap.caption=wrapMap.thead;wrapMap.th=wrapMap.td;// IE can't serialize <link> and <script> tags normally
if(!jQuery.support.htmlSerialize){wrapMap._default=[1,"div<div>","</div>"];}jQuery.fn.extend({text:function text(_text2){if(jQuery.isFunction(_text2)){return this.each(function(i){var self=jQuery(this);self.text(_text2.call(this,i,self.text()));});}if((typeof _text2==="undefined"?"undefined":_typeof(_text2))!=="object"&&_text2!==undefined){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(_text2));}return jQuery.text(this);},wrapAll:function wrapAll(html){if(jQuery.isFunction(html)){return this.each(function(i){jQuery(this).wrapAll(html.call(this,i));});}if(this[0]){// The elements to wrap the target around
var wrap=jQuery(html,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){wrap.insertBefore(this[0]);}wrap.map(function(){var elem=this;while(elem.firstChild&&elem.firstChild.nodeType===1){elem=elem.firstChild;}return elem;}).append(this);}return this;},wrapInner:function wrapInner(html){if(jQuery.isFunction(html)){return this.each(function(i){jQuery(this).wrapInner(html.call(this,i));});}return this.each(function(){var self=jQuery(this),contents=self.contents();if(contents.length){contents.wrapAll(html);}else{self.append(html);}});},wrap:function wrap(html){var isFunction=jQuery.isFunction(html);return this.each(function(i){jQuery(this).wrapAll(isFunction?html.call(this,i):html);});},unwrap:function unwrap(){return this.parent().each(function(){if(!jQuery.nodeName(this,"body")){jQuery(this).replaceWith(this.childNodes);}}).end();},append:function append(){return this.domManip(arguments,true,function(elem){if(this.nodeType===1){this.appendChild(elem);}});},prepend:function prepend(){return this.domManip(arguments,true,function(elem){if(this.nodeType===1){this.insertBefore(elem,this.firstChild);}});},before:function before(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(elem){this.parentNode.insertBefore(elem,this);});}else if(arguments.length){var set=jQuery.clean(arguments);set.push.apply(set,this.toArray());return this.pushStack(set,"before",arguments);}},after:function after(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});}else if(arguments.length){var set=this.pushStack(this,"after",arguments);set.push.apply(set,jQuery.clean(arguments));return set;}},// keepData is for internal use only--do not document
remove:function remove(selector,keepData){for(var i=0,elem;(elem=this[i])!=null;i++){if(!selector||jQuery.filter(selector,[elem]).length){if(!keepData&&elem.nodeType===1){jQuery.cleanData(elem.getElementsByTagName("*"));jQuery.cleanData([elem]);}if(elem.parentNode){elem.parentNode.removeChild(elem);}}}return this;},empty:function empty(){for(var i=0,elem;(elem=this[i])!=null;i++){// Remove element nodes and prevent memory leaks
if(elem.nodeType===1){jQuery.cleanData(elem.getElementsByTagName("*"));}// Remove any remaining nodes
while(elem.firstChild){elem.removeChild(elem.firstChild);}}return this;},clone:function clone(dataAndEvents,deepDataAndEvents){dataAndEvents=dataAndEvents==null?false:dataAndEvents;deepDataAndEvents=deepDataAndEvents==null?dataAndEvents:deepDataAndEvents;return this.map(function(){return jQuery.clone(this,dataAndEvents,deepDataAndEvents);});},html:function html(value){if(value===undefined){return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(rinlinejQuery,""):null;// See if we can take a shortcut and just use innerHTML
}else if(typeof value==="string"&&!rnoInnerhtml.test(value)&&(jQuery.support.leadingWhitespace||!rleadingWhitespace.test(value))&&!wrapMap[(rtagName.exec(value)||["",""])[1].toLowerCase()]){value=value.replace(rxhtmlTag,"<$1></$2>");try{for(var i=0,l=this.length;i<l;i++){// Remove element nodes and prevent memory leaks
if(this[i].nodeType===1){jQuery.cleanData(this[i].getElementsByTagName("*"));this[i].innerHTML=value;}}// If using innerHTML throws an exception, use the fallback method
}catch(e){this.empty().append(value);}}else if(jQuery.isFunction(value)){this.each(function(i){var self=jQuery(this);self.html(value.call(this,i,self.html()));});}else{this.empty().append(value);}return this;},replaceWith:function replaceWith(value){if(this[0]&&this[0].parentNode){// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if(jQuery.isFunction(value)){return this.each(function(i){var self=jQuery(this),old=self.html();self.replaceWith(value.call(this,i,old));});}if(typeof value!=="string"){value=jQuery(value).detach();}return this.each(function(){var next=this.nextSibling,parent=this.parentNode;jQuery(this).remove();if(next){jQuery(next).before(value);}else{jQuery(parent).append(value);}});}else{return this.length?this.pushStack(jQuery(jQuery.isFunction(value)?value():value),"replaceWith",value):this;}},detach:function detach(selector){return this.remove(selector,true);},domManip:function domManip(args,table,callback){var results,first,fragment,parent,value=args[0],scripts=[];// We can't cloneNode fragments that contain checked, in WebKit
if(!jQuery.support.checkClone&&arguments.length===3&&typeof value==="string"&&rchecked.test(value)){return this.each(function(){jQuery(this).domManip(args,table,callback,true);});}if(jQuery.isFunction(value)){return this.each(function(i){var self=jQuery(this);args[0]=value.call(this,i,table?self.html():undefined);self.domManip(args,table,callback);});}if(this[0]){parent=value&&value.parentNode;// If we're in a fragment, just use that instead of building a new one
if(jQuery.support.parentNode&&parent&&parent.nodeType===11&&parent.childNodes.length===this.length){results={fragment:parent};}else{results=jQuery.buildFragment(args,this,scripts);}fragment=results.fragment;if(fragment.childNodes.length===1){first=fragment=fragment.firstChild;}else{first=fragment.firstChild;}if(first){table=table&&jQuery.nodeName(first,"tr");for(var i=0,l=this.length,lastIndex=l-1;i<l;i++){callback.call(table?root(this[i],first):this[i],// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable||l>1&&i<lastIndex?jQuery.clone(fragment,true,true):fragment);}}if(scripts.length){jQuery.each(scripts,evalScript);}}return this;}});function root(elem,cur){return jQuery.nodeName(elem,"table")?elem.getElementsByTagName("tbody")[0]||elem.appendChild(elem.ownerDocument.createElement("tbody")):elem;}function cloneCopyEvent(src,dest){if(dest.nodeType!==1||!jQuery.hasData(src)){return;}var type,i,l,oldData=jQuery._data(src),curData=jQuery._data(dest,oldData),events=oldData.events;if(events){delete curData.handle;curData.events={};for(type in events){for(i=0,l=events[type].length;i<l;i++){jQuery.event.add(dest,type+(events[type][i].namespace?".":"")+events[type][i].namespace,events[type][i],events[type][i].data);}}}// make the cloned public data object a copy from the original
if(curData.data){curData.data=jQuery.extend({},curData.data);}}function cloneFixAttributes(src,dest){var nodeName;// We do not need to do anything for non-Elements
if(dest.nodeType!==1){return;}// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if(dest.clearAttributes){dest.clearAttributes();}// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if(dest.mergeAttributes){dest.mergeAttributes(src);}nodeName=dest.nodeName.toLowerCase();// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if(nodeName==="object"){dest.outerHTML=src.outerHTML;}else if(nodeName==="input"&&(src.type==="checkbox"||src.type==="radio")){// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if(src.checked){dest.defaultChecked=dest.checked=src.checked;}// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if(dest.value!==src.value){dest.value=src.value;}// IE6-8 fails to return the selected option to the default selected
// state when cloning options
}else if(nodeName==="option"){dest.selected=src.defaultSelected;// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
}else if(nodeName==="input"||nodeName==="textarea"){dest.defaultValue=src.defaultValue;}// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute(jQuery.expando);}jQuery.buildFragment=function(args,nodes,scripts){var fragment,cacheable,cacheresults,doc,first=args[0];// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if(nodes&&nodes[0]){doc=nodes[0].ownerDocument||nodes[0];}// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if(!doc.createDocumentFragment){doc=document;}// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if(args.length===1&&typeof first==="string"&&first.length<512&&doc===document&&first.charAt(0)==="<"&&!rnocache.test(first)&&(jQuery.support.checkClone||!rchecked.test(first))&&(jQuery.support.html5Clone||!rnoshimcache.test(first))){cacheable=true;cacheresults=jQuery.fragments[first];if(cacheresults&&cacheresults!==1){fragment=cacheresults;}}if(!fragment){fragment=doc.createDocumentFragment();jQuery.clean(args,doc,fragment,scripts);}if(cacheable){jQuery.fragments[first]=cacheresults?fragment:1;}return{fragment:fragment,cacheable:cacheable};};jQuery.fragments={};jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(selector){var ret=[],insert=jQuery(selector),parent=this.length===1&&this[0].parentNode;if(parent&&parent.nodeType===11&&parent.childNodes.length===1&&insert.length===1){insert[original](this[0]);return this;}else{for(var i=0,l=insert.length;i<l;i++){var elems=(i>0?this.clone(true):this).get();jQuery(insert[i])[original](elems);ret=ret.concat(elems);}return this.pushStack(ret,name,insert.selector);}};});function getAll(elem){if(typeof elem.getElementsByTagName!=="undefined"){return elem.getElementsByTagName("*");}else if(typeof elem.querySelectorAll!=="undefined"){return elem.querySelectorAll("*");}else{return[];}}// Used in clean, fixes the defaultChecked property
function fixDefaultChecked(elem){if(elem.type==="checkbox"||elem.type==="radio"){elem.defaultChecked=elem.checked;}}// Finds all inputs and passes them to fixDefaultChecked
function findInputs(elem){var nodeName=(elem.nodeName||"").toLowerCase();if(nodeName==="input"){fixDefaultChecked(elem);// Skip scripts, get other children
}else if(nodeName!=="script"&&typeof elem.getElementsByTagName!=="undefined"){jQuery.grep(elem.getElementsByTagName("input"),fixDefaultChecked);}}// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
function shimCloneNode(elem){var div=document.createElement("div");safeFragment.appendChild(div);div.innerHTML=elem.outerHTML;return div.firstChild;}jQuery.extend({clone:function clone(elem,dataAndEvents,deepDataAndEvents){var srcElements,destElements,i,// IE<=8 does not properly clone detached, unknown element nodes
clone=jQuery.support.html5Clone||!rnoshimcache.test("<"+elem.nodeName)?elem.cloneNode(true):shimCloneNode(elem);if((!jQuery.support.noCloneEvent||!jQuery.support.noCloneChecked)&&(elem.nodeType===1||elem.nodeType===11)&&!jQuery.isXMLDoc(elem)){// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes(elem,clone);// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements=getAll(elem);destElements=getAll(clone);// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for(i=0;srcElements[i];++i){// Ensure that the destination node is not null; Fixes #9587
if(destElements[i]){cloneFixAttributes(srcElements[i],destElements[i]);}}}// Copy the events from the original to the clone
if(dataAndEvents){cloneCopyEvent(elem,clone);if(deepDataAndEvents){srcElements=getAll(elem);destElements=getAll(clone);for(i=0;srcElements[i];++i){cloneCopyEvent(srcElements[i],destElements[i]);}}}srcElements=destElements=null;// Return the cloned set
return clone;},clean:function clean(elems,context,fragment,scripts){var checkScriptType;context=context||document;// !context.createElement fails in IE with an error but returns typeof 'object'
if(typeof context.createElement==="undefined"){context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;}var ret=[],j;for(var i=0,elem;(elem=elems[i])!=null;i++){if(typeof elem==="number"){elem+="";}if(!elem){continue;}// Convert html string into DOM nodes
if(typeof elem==="string"){if(!rhtml.test(elem)){elem=context.createTextNode(elem);}else{// Fix "XHTML"-style tags in all browsers
elem=elem.replace(rxhtmlTag,"<$1></$2>");// Trim whitespace, otherwise indexOf won't work as expected
var tag=(rtagName.exec(elem)||["",""])[1].toLowerCase(),wrap=wrapMap[tag]||wrapMap._default,depth=wrap[0],div=context.createElement("div");// Append wrapper element to unknown element safe doc fragment
if(context===document){// Use the fragment we've already created for this document
safeFragment.appendChild(div);}else{// Use a fragment created with the owner document
createSafeFragment(context).appendChild(div);}// Go to html and back, then peel off extra wrappers
div.innerHTML=wrap[1]+elem+wrap[2];// Move to the right depth
while(depth--){div=div.lastChild;}// Remove IE's autoinserted <tbody> from table fragments
if(!jQuery.support.tbody){// String was a <table>, *may* have spurious <tbody>
var hasBody=rtbody.test(elem),tbody=tag==="table"&&!hasBody?div.firstChild&&div.firstChild.childNodes:// String was a bare <thead> or <tfoot>
wrap[1]==="<table>"&&!hasBody?div.childNodes:[];for(j=tbody.length-1;j>=0;--j){if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length){tbody[j].parentNode.removeChild(tbody[j]);}}}// IE completely kills leading whitespace when innerHTML is used
if(!jQuery.support.leadingWhitespace&&rleadingWhitespace.test(elem)){div.insertBefore(context.createTextNode(rleadingWhitespace.exec(elem)[0]),div.firstChild);}elem=div.childNodes;}}// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;if(!jQuery.support.appendChecked){if(elem[0]&&typeof(len=elem.length)==="number"){for(j=0;j<len;j++){findInputs(elem[j]);}}else{findInputs(elem);}}if(elem.nodeType){ret.push(elem);}else{ret=jQuery.merge(ret,elem);}}if(fragment){checkScriptType=function checkScriptType(elem){return!elem.type||rscriptType.test(elem.type);};for(i=0;ret[i];i++){if(scripts&&jQuery.nodeName(ret[i],"script")&&(!ret[i].type||ret[i].type.toLowerCase()==="text/javascript")){scripts.push(ret[i].parentNode?ret[i].parentNode.removeChild(ret[i]):ret[i]);}else{if(ret[i].nodeType===1){var jsTags=jQuery.grep(ret[i].getElementsByTagName("script"),checkScriptType);ret.splice.apply(ret,[i+1,0].concat(jsTags));}fragment.appendChild(ret[i]);}}}return ret;},cleanData:function cleanData(elems){var data,id,cache=jQuery.cache,special=jQuery.event.special,deleteExpando=jQuery.support.deleteExpando;for(var i=0,elem;(elem=elems[i])!=null;i++){if(elem.nodeName&&jQuery.noData[elem.nodeName.toLowerCase()]){continue;}id=elem[jQuery.expando];if(id){data=cache[id];if(data&&data.events){for(var type in data.events){if(special[type]){jQuery.event.remove(elem,type);// This is a shortcut to avoid jQuery.event.remove's overhead
}else{jQuery.removeEvent(elem,type,data.handle);}}// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if(data.handle){data.handle.elem=null;}}if(deleteExpando){delete elem[jQuery.expando];}else if(elem.removeAttribute){elem.removeAttribute(jQuery.expando);}delete cache[id];}}}});function evalScript(i,elem){if(elem.src){jQuery.ajax({url:elem.src,async:false,dataType:"script"});}else{jQuery.globalEval((elem.text||elem.textContent||elem.innerHTML||"").replace(rcleanScript,"/*$0*/"));}if(elem.parentNode){elem.parentNode.removeChild(elem);}}var ralpha=/alpha\([^)]*\)/i,ropacity=/opacity=([^)]*)/,// fixed for IE9, see #8346
rupper=/([A-Z]|^ms)/g,rnumpx=/^-?\d+(?:px)?$/i,rnum=/^-?\d/,rrelNum=/^([\-+])=([\-+.\de]+)/,cssShow={position:"absolute",visibility:"hidden",display:"block"},cssWidth=["Left","Right"],cssHeight=["Top","Bottom"],curCSS,getComputedStyle,currentStyle;jQuery.fn.css=function(name,value){// Setting 'undefined' is a no-op
if(arguments.length===2&&value===undefined){return this;}return jQuery.access(this,name,value,true,function(elem,name,value){return value!==undefined?jQuery.style(elem,name,value):jQuery.css(elem,name);});};jQuery.extend({// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks:{opacity:{get:function get(elem,computed){if(computed){// We should always get a number back from opacity
var ret=curCSS(elem,"opacity","opacity");return ret===""?"1":ret;}else{return elem.style.opacity;}}}},// Exclude the following css properties to add px
cssNumber:{"fillOpacity":true,"fontWeight":true,"lineHeight":true,"opacity":true,"orphans":true,"widows":true,"zIndex":true,"zoom":true},// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps:{// normalize float css property
"float":jQuery.support.cssFloat?"cssFloat":"styleFloat"},// Get and set the style property on a DOM Node
style:function style(elem,name,value,extra){// Don't set styles on text and comment nodes
if(!elem||elem.nodeType===3||elem.nodeType===8||!elem.style){return;}// Make sure that we're working with the right name
var ret,type,origName=jQuery.camelCase(name),style=elem.style,hooks=jQuery.cssHooks[origName];name=jQuery.cssProps[origName]||origName;// Check if we're setting a value
if(value!==undefined){type=typeof value==="undefined"?"undefined":_typeof(value);// convert relative number strings (+= or -=) to relative numbers. #7345
if(type==="string"&&(ret=rrelNum.exec(value))){value=+(ret[1]+1)*+ret[2]+parseFloat(jQuery.css(elem,name));// Fixes bug #9237
type="number";}// Make sure that NaN and null values aren't set. See: #7116
if(value==null||type==="number"&&isNaN(value)){return;}// If a number was passed in, add 'px' to the (except for certain CSS properties)
if(type==="number"&&!jQuery.cssNumber[origName]){value+="px";}// If a hook was provided, use that value, otherwise just set the specified value
if(!hooks||!("set"in hooks)||(value=hooks.set(elem,value))!==undefined){// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try{style[name]=value;}catch(e){}}}else{// If a hook was provided get the non-computed value from there
if(hooks&&"get"in hooks&&(ret=hooks.get(elem,false,extra))!==undefined){return ret;}// Otherwise just get the value from the style object
return style[name];}},css:function css(elem,name,extra){var ret,hooks;// Make sure that we're working with the right name
name=jQuery.camelCase(name);hooks=jQuery.cssHooks[name];name=jQuery.cssProps[name]||name;// cssFloat needs a special treatment
if(name==="cssFloat"){name="float";}// If a hook was provided get the computed value from there
if(hooks&&"get"in hooks&&(ret=hooks.get(elem,true,extra))!==undefined){return ret;// Otherwise, if a way to get the computed value exists, use that
}else if(curCSS){return curCSS(elem,name);}},// A method for quickly swapping in/out CSS properties to get correct calculations
swap:function swap(elem,options,callback){var old={};// Remember the old values, and insert the new ones
for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);// Revert the old values
for(name in options){elem.style[name]=old[name];}}});// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS=jQuery.css;jQuery.each(["height","width"],function(i,name){jQuery.cssHooks[name]={get:function get(elem,computed,extra){var val;if(computed){if(elem.offsetWidth!==0){return getWH(elem,name,extra);}else{jQuery.swap(elem,cssShow,function(){val=getWH(elem,name,extra);});}return val;}},set:function set(elem,value){if(rnumpx.test(value)){// ignore negative width and height values #1599
value=parseFloat(value);if(value>=0){return value+"px";}}else{return value;}}};});if(!jQuery.support.opacity){jQuery.cssHooks.opacity={get:function get(elem,computed){// IE uses filters for opacity
return ropacity.test((computed&&elem.currentStyle?elem.currentStyle.filter:elem.style.filter)||"")?parseFloat(RegExp.$1)/100+"":computed?"1":"";},set:function set(elem,value){var style=elem.style,currentStyle=elem.currentStyle,opacity=jQuery.isNumeric(value)?"alpha(opacity="+value*100+")":"",filter=currentStyle&&currentStyle.filter||style.filter||"";// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom=1;// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if(value>=1&&jQuery.trim(filter.replace(ralpha,""))===""){// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute("filter");// if there there is no filter style applied in a css rule, we are done
if(currentStyle&&!currentStyle.filter){return;}}// otherwise, set new filter values
style.filter=ralpha.test(filter)?filter.replace(ralpha,opacity):filter+" "+opacity;}};}jQuery(function(){// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if(!jQuery.support.reliableMarginRight){jQuery.cssHooks.marginRight={get:function get(elem,computed){// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
var ret;jQuery.swap(elem,{"display":"inline-block"},function(){if(computed){ret=curCSS(elem,"margin-right","marginRight");}else{ret=elem.style.marginRight;}});return ret;}};}});if(document.defaultView&&document.defaultView.getComputedStyle){getComputedStyle=function getComputedStyle(elem,name){var ret,defaultView,computedStyle;name=name.replace(rupper,"-$1").toLowerCase();if((defaultView=elem.ownerDocument.defaultView)&&(computedStyle=defaultView.getComputedStyle(elem,null))){ret=computedStyle.getPropertyValue(name);if(ret===""&&!jQuery.contains(elem.ownerDocument.documentElement,elem)){ret=jQuery.style(elem,name);}}return ret;};}if(document.documentElement.currentStyle){currentStyle=function currentStyle(elem,name){var left,rsLeft,uncomputed,ret=elem.currentStyle&&elem.currentStyle[name],style=elem.style;// Avoid setting ret to empty string here
// so we don't default to auto
if(ret===null&&style&&(uncomputed=style[name])){ret=uncomputed;}// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if(!rnumpx.test(ret)&&rnum.test(ret)){// Remember the original values
left=style.left;rsLeft=elem.runtimeStyle&&elem.runtimeStyle.left;// Put in the new values to get a computed value out
if(rsLeft){elem.runtimeStyle.left=elem.currentStyle.left;}style.left=name==="fontSize"?"1em":ret||0;ret=style.pixelLeft+"px";// Revert the changed values
style.left=left;if(rsLeft){elem.runtimeStyle.left=rsLeft;}}return ret===""?"auto":ret;};}curCSS=getComputedStyle||currentStyle;function getWH(elem,name,extra){// Start with offset property
var val=name==="width"?elem.offsetWidth:elem.offsetHeight,which=name==="width"?cssWidth:cssHeight,i=0,len=which.length;if(val>0){if(extra!=="border"){for(;i<len;i++){if(!extra){val-=parseFloat(jQuery.css(elem,"padding"+which[i]))||0;}if(extra==="margin"){val+=parseFloat(jQuery.css(elem,extra+which[i]))||0;}else{val-=parseFloat(jQuery.css(elem,"border"+which[i]+"Width"))||0;}}}return val+"px";}// Fall back to computed then uncomputed css if necessary
val=curCSS(elem,name,name);if(val<0||val==null){val=elem.style[name]||0;}// Normalize "", auto, and prepare for extra
val=parseFloat(val)||0;// Add padding, border, margin
if(extra){for(;i<len;i++){val+=parseFloat(jQuery.css(elem,"padding"+which[i]))||0;if(extra!=="padding"){val+=parseFloat(jQuery.css(elem,"border"+which[i]+"Width"))||0;}if(extra==="margin"){val+=parseFloat(jQuery.css(elem,extra+which[i]))||0;}}}return val+"px";}if(jQuery.expr&&jQuery.expr.filters){jQuery.expr.filters.hidden=function(elem){var width=elem.offsetWidth,height=elem.offsetHeight;return width===0&&height===0||!jQuery.support.reliableHiddenOffsets&&(elem.style&&elem.style.display||jQuery.css(elem,"display"))==="none";};jQuery.expr.filters.visible=function(elem){return!jQuery.expr.filters.hidden(elem);};}var r20=/%20/g,rbracket=/\[\]$/,rCRLF=/\r?\n/g,rhash=/#.*$/,rheaders=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,// IE leaves an \r character at EOL
rinput=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,// #7653, #8125, #8152: local protocol detection
rlocalProtocol=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,rnoContent=/^(?:GET|HEAD)$/,rprotocol=/^\/\//,rquery=/\?/,rscript=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,rselectTextarea=/^(?:select|textarea)/i,rspacesAjax=/\s+/,rts=/([?&])_=[^&]*/,rurl=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,// Keep a copy of the old load method
_load=jQuery.fn.load,/* Prefilters
     * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
     * 2) These are called:
     *    - BEFORE asking for a transport
     *    - AFTER param serialization (s.data is a string if s.processData is true)
     * 3) key is the dataType
     * 4) the catchall symbol "*" can be used
     * 5) execution will start with transport dataType and THEN continue down to "*" if needed
     */prefilters={},/* Transports bindings
     * 1) key is the dataType
     * 2) the catchall symbol "*" can be used
     * 3) selection will start with transport dataType and THEN go to "*" if needed
     */transports={},// Document location
ajaxLocation,// Document location segments
ajaxLocParts,// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes=["*/"]+["*"];// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try{ajaxLocation=location.href;}catch(e){// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation=document.createElement("a");ajaxLocation.href="";ajaxLocation=ajaxLocation.href;}// Segment location into parts
ajaxLocParts=rurl.exec(ajaxLocation.toLowerCase())||[];// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports(structure){// dataTypeExpression is optional and defaults to "*"
return function(dataTypeExpression,func){if(typeof dataTypeExpression!=="string"){func=dataTypeExpression;dataTypeExpression="*";}if(jQuery.isFunction(func)){var dataTypes=dataTypeExpression.toLowerCase().split(rspacesAjax),i=0,length=dataTypes.length,dataType,list,placeBefore;// For each dataType in the dataTypeExpression
for(;i<length;i++){dataType=dataTypes[i];// We control if we're asked to add before
// any existing element
placeBefore=/^\+/.test(dataType);if(placeBefore){dataType=dataType.substr(1)||"*";}list=structure[dataType]=structure[dataType]||[];// then we add to the structure accordingly
list[placeBefore?"unshift":"push"](func);}}};}// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR,dataType/* internal */,inspected/* internal */){dataType=dataType||options.dataTypes[0];inspected=inspected||{};inspected[dataType]=true;var list=structure[dataType],i=0,length=list?list.length:0,executeOnly=structure===prefilters,selection;for(;i<length&&(executeOnly||!selection);i++){selection=list[i](options,originalOptions,jqXHR);// If we got redirected to another dataType
// we try there if executing only and not done already
if(typeof selection==="string"){if(!executeOnly||inspected[selection]){selection=undefined;}else{options.dataTypes.unshift(selection);selection=inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR,selection,inspected);}}}// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if((executeOnly||!selection)&&!inspected["*"]){selection=inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR,"*",inspected);}// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;}// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key];}}if(deep){jQuery.extend(true,target,deep);}}jQuery.fn.extend({load:function load(url,params,callback){if(typeof url!=="string"&&_load){return _load.apply(this,arguments);// Don't do a request if no elements are being requested
}else if(!this.length){return this;}var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}// Default to a GET request
var type="GET";// If the second parameter was provided
if(params){// If it's a function
if(jQuery.isFunction(params)){// We assume that it's the callback
callback=params;params=undefined;// Otherwise, build a param string
}else if((typeof params==="undefined"?"undefined":_typeof(params))==="object"){params=jQuery.param(params,jQuery.ajaxSettings.traditional);type="POST";}}var self=this;// Request the remote document
jQuery.ajax({url:url,type:type,dataType:"html",data:params,// Complete callback (responseText is used internally)
complete:function complete(jqXHR,status,responseText){// Store the response as specified by the jqXHR object
responseText=jqXHR.responseText;// If successful, inject the HTML into all the matched elements
if(jqXHR.isResolved()){// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function(r){responseText=r;});// See if a selector was specified
self.html(selector?// Create a dummy div to hold the results
jQuery("<div>")// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript,""))// Locate the specified elements
.find(selector):// If not, just inject the full result
responseText);}if(callback){self.each(callback,[responseText,status,jqXHR]);}}});return this;},serialize:function serialize(){return jQuery.param(this.serializeArray());},serializeArray:function serializeArray(){return this.map(function(){return this.elements?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||rselectTextarea.test(this.nodeName)||rinput.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:jQuery.isArray(val)?jQuery.map(val,function(val,i){return{name:elem.name,value:val.replace(rCRLF,"\r\n")};}):{name:elem.name,value:val.replace(rCRLF,"\r\n")};}).get();}});// Attach a bunch of functions for handling common AJAX events
jQuery.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(i,o){jQuery.fn[o]=function(f){return this.on(o,f);};});jQuery.each(["get","post"],function(i,method){jQuery[method]=function(url,data,callback,type){// shift arguments if data argument was omitted
if(jQuery.isFunction(data)){type=type||callback;callback=data;data=undefined;}return jQuery.ajax({type:method,url:url,data:data,success:callback,dataType:type});};});jQuery.extend({getScript:function getScript(url,callback){return jQuery.get(url,undefined,callback,"script");},getJSON:function getJSON(url,data,callback){return jQuery.get(url,data,callback,"json");},// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup:function ajaxSetup(target,settings){if(settings){// Building a settings object
ajaxExtend(target,jQuery.ajaxSettings);}else{// Extending ajaxSettings
settings=target;target=jQuery.ajaxSettings;}ajaxExtend(target,settings);return target;},ajaxSettings:{url:ajaxLocation,isLocal:rlocalProtocol.test(ajaxLocParts[1]),global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,/*
             timeout: 0,
             data: null,
             dataType: null,
             username: null,
             password: null,
             cache: null,
             traditional: false,
             headers: {},
             */accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":allTypes},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters:{// Convert anything to text
"* text":window.String,// Text to html (true = no transformation)
"text html":true,// Evaluate text as a json expression
"text json":jQuery.parseJSON,// Parse text as xml
"text xml":jQuery.parseXML},// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions:{context:true,url:true}},ajaxPrefilter:addToPrefiltersOrTransports(prefilters),ajaxTransport:addToPrefiltersOrTransports(transports),// Main method
ajax:function ajax(url,options){// If url is an object, simulate pre-1.5 signature
if((typeof url==="undefined"?"undefined":_typeof(url))==="object"){options=url;url=undefined;}// Force options to be an object
options=options||{};var// Create the final options object
s=jQuery.ajaxSetup({},options),// Callbacks context
callbackContext=s.context||s,// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext=callbackContext!==s&&(callbackContext.nodeType||callbackContext instanceof jQuery)?jQuery(callbackContext):jQuery.event,// Deferreds
deferred=jQuery.Deferred(),completeDeferred=jQuery.Callbacks("once memory"),// Status-dependent callbacks
statusCode=s.statusCode||{},// ifModified key
ifModifiedKey,// Headers (they are sent all at once)
requestHeaders={},requestHeadersNames={},// Response headers
responseHeadersString,responseHeaders,// transport
transport,// timeout handle
timeoutTimer,// Cross-domain detection vars
parts,// The jqXHR state
state=0,// To know if global events are to be dispatched
fireGlobals,// Loop variable
i,// Fake xhr
jqXHR={readyState:0,// Caches the header
setRequestHeader:function setRequestHeader(name,value){if(!state){var lname=name.toLowerCase();name=requestHeadersNames[lname]=requestHeadersNames[lname]||name;requestHeaders[name]=value;}return this;},// Raw string
getAllResponseHeaders:function getAllResponseHeaders(){return state===2?responseHeadersString:null;},// Builds headers hashtable if needed
getResponseHeader:function getResponseHeader(key){var match;if(state===2){if(!responseHeaders){responseHeaders={};while(match=rheaders.exec(responseHeadersString)){responseHeaders[match[1].toLowerCase()]=match[2];}}match=responseHeaders[key.toLowerCase()];}return match===undefined?null:match;},// Overrides response content-type header
overrideMimeType:function overrideMimeType(type){if(!state){s.mimeType=type;}return this;},// Cancel the request
abort:function abort(statusText){statusText=statusText||"abort";if(transport){transport.abort(statusText);}done(0,statusText);return this;}};// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done(status,nativeStatusText,responses,headers){// Called once
if(state===2){return;}// State is "done" now
state=2;// Clear timeout if it exists
if(timeoutTimer){clearTimeout(timeoutTimer);}// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport=undefined;// Cache response headers
responseHeadersString=headers||"";// Set readyState
jqXHR.readyState=status>0?4:0;var isSuccess,success,error,statusText=nativeStatusText,response=responses?ajaxHandleResponses(s,jqXHR,responses):undefined,lastModified,etag;// If successful, handle type chaining
if(status>=200&&status<300||status===304){// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if(s.ifModified){if(lastModified=jqXHR.getResponseHeader("Last-Modified")){jQuery.lastModified[ifModifiedKey]=lastModified;}if(etag=jqXHR.getResponseHeader("Etag")){jQuery.etag[ifModifiedKey]=etag;}}// If not modified
if(status===304){statusText="notmodified";isSuccess=true;// If we have data
}else{try{success=ajaxConvert(s,response);statusText="success";isSuccess=true;}catch(e){// We have a parsererror
statusText="parsererror";error=e;}}}else{// We extract error from statusText
// then normalize statusText and status for non-aborts
error=statusText;if(!statusText||status){statusText="error";if(status<0){status=0;}}}// Set data for the fake xhr object
jqXHR.status=status;jqXHR.statusText=""+(nativeStatusText||statusText);// Success/Error
if(isSuccess){deferred.resolveWith(callbackContext,[success,statusText,jqXHR]);}else{deferred.rejectWith(callbackContext,[jqXHR,statusText,error]);}// Status-dependent callbacks
jqXHR.statusCode(statusCode);statusCode=undefined;if(fireGlobals){globalEventContext.trigger("ajax"+(isSuccess?"Success":"Error"),[jqXHR,s,isSuccess?success:error]);}// Complete
completeDeferred.fireWith(callbackContext,[jqXHR,statusText]);if(fireGlobals){globalEventContext.trigger("ajaxComplete",[jqXHR,s]);// Handle the global AJAX counter
if(! --jQuery.active){jQuery.event.trigger("ajaxStop");}}}// Attach deferreds
deferred.promise(jqXHR);jqXHR.success=jqXHR.done;jqXHR.error=jqXHR.fail;jqXHR.complete=completeDeferred.add;// Status-dependent callbacks
jqXHR.statusCode=function(map){if(map){var tmp;if(state<2){for(tmp in map){statusCode[tmp]=[statusCode[tmp],map[tmp]];}}else{tmp=map[jqXHR.status];jqXHR.then(tmp,tmp);}}return this;};// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url=((url||s.url)+"").replace(rhash,"").replace(rprotocol,ajaxLocParts[1]+"//");// Extract dataTypes list
s.dataTypes=jQuery.trim(s.dataType||"*").toLowerCase().split(rspacesAjax);// Determine if a cross-domain request is in order
if(s.crossDomain==null){parts=rurl.exec(s.url.toLowerCase());s.crossDomain=!!(parts&&(parts[1]!=ajaxLocParts[1]||parts[2]!=ajaxLocParts[2]||(parts[3]||(parts[1]==="http:"?80:443))!=(ajaxLocParts[3]||(ajaxLocParts[1]==="http:"?80:443))));}// Convert data if not already a string
if(s.data&&s.processData&&typeof s.data!=="string"){s.data=jQuery.param(s.data,s.traditional);}// Apply prefilters
inspectPrefiltersOrTransports(prefilters,s,options,jqXHR);// If request was aborted inside a prefiler, stop there
if(state===2){return false;}// We can fire global events as of now if asked to
fireGlobals=s.global;// Uppercase the type
s.type=s.type.toUpperCase();// Determine if request has content
s.hasContent=!rnoContent.test(s.type);// Watch for a new set of requests
if(fireGlobals&&jQuery.active++===0){jQuery.event.trigger("ajaxStart");}// More options handling for requests with no content
if(!s.hasContent){// If data is available, append data to url
if(s.data){s.url+=(rquery.test(s.url)?"&":"?")+s.data;// #9682: remove data so that it's not used in an eventual retry
delete s.data;}// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey=s.url;// Add anti-cache in url if needed
if(s.cache===false){var ts=jQuery.now(),// try replacing _= if it is there
ret=s.url.replace(rts,"$1_="+ts);// if nothing was replaced, add timestamp to the end
s.url=ret+(ret===s.url?(rquery.test(s.url)?"&":"?")+"_="+ts:"");}}// Set the correct header, if data is being sent
if(s.data&&s.hasContent&&s.contentType!==false||options.contentType){jqXHR.setRequestHeader("Content-Type",s.contentType);}// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if(s.ifModified){ifModifiedKey=ifModifiedKey||s.url;if(jQuery.lastModified[ifModifiedKey]){jqXHR.setRequestHeader("If-Modified-Since",jQuery.lastModified[ifModifiedKey]);}if(jQuery.etag[ifModifiedKey]){jqXHR.setRequestHeader("If-None-Match",jQuery.etag[ifModifiedKey]);}}// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader("Accept",s.dataTypes[0]&&s.accepts[s.dataTypes[0]]?s.accepts[s.dataTypes[0]]+(s.dataTypes[0]!=="*"?", "+allTypes+"; q=0.01":""):s.accepts["*"]);// Check for headers option
for(i in s.headers){jqXHR.setRequestHeader(i,s.headers[i]);}// Allow custom headers/mimetypes and early abort
if(s.beforeSend&&(s.beforeSend.call(callbackContext,jqXHR,s)===false||state===2)){// Abort if not done already
jqXHR.abort();return false;}// Install callbacks on deferreds
for(i in{success:1,error:1,complete:1}){jqXHR[i](s[i]);}// Get transport
transport=inspectPrefiltersOrTransports(transports,s,options,jqXHR);// If no transport, we auto-abort
if(!transport){done(-1,"No Transport");}else{jqXHR.readyState=1;// Send global event
if(fireGlobals){globalEventContext.trigger("ajaxSend",[jqXHR,s]);}// Timeout
if(s.async&&s.timeout>0){timeoutTimer=setTimeout(function(){jqXHR.abort("timeout");},s.timeout);}try{state=1;transport.send(requestHeaders,done);}catch(e){// Propagate exception as error if not done
if(state<2){done(-1,e);// Simply rethrow otherwise
}else{throw e;}}}return jqXHR;},// Serialize an array of form elements or a set of
// key/values into a query string
param:function param(a,traditional){var s=[],add=function add(key,value){// If value is a function, invoke it and return its value
value=jQuery.isFunction(value)?value():value;s[s.length]=encodeURIComponent(key)+"="+encodeURIComponent(value);};// Set traditional to true for jQuery <= 1.3.2 behavior.
if(traditional===undefined){traditional=jQuery.ajaxSettings.traditional;}// If an array was passed in, assume that it is an array of form elements.
if(jQuery.isArray(a)||a.jquery&&!jQuery.isPlainObject(a)){// Serialize the form elements
jQuery.each(a,function(){add(this.name,this.value);});}else{// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for(var prefix in a){buildParams(prefix,a[prefix],traditional,add);}}// Return the resulting serialization
return s.join("&").replace(r20,"+");}});function buildParams(prefix,obj,traditional,add){if(jQuery.isArray(obj)){// Serialize array item.
jQuery.each(obj,function(i,v){if(traditional||rbracket.test(prefix)){// Treat each array item as a scalar.
add(prefix,v);}else{// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams(prefix+"["+((typeof v==="undefined"?"undefined":_typeof(v))==="object"||jQuery.isArray(v)?i:"")+"]",v,traditional,add);}});}else if(!traditional&&obj!=null&&(typeof obj==="undefined"?"undefined":_typeof(obj))==="object"){// Serialize object item.
for(var name in obj){buildParams(prefix+"["+name+"]",obj[name],traditional,add);}}else{// Serialize scalar item.
add(prefix,obj);}}// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({// Counter for holding the number of active queries
active:0,// Last-Modified header cache for next request
lastModified:{},etag:{}});/* Handles responses to an ajax request:
     * - sets all responseXXX fields accordingly
     * - finds the right dataType (mediates between content-type and expected dataType)
     * - returns the corresponding response
     */function ajaxHandleResponses(s,jqXHR,responses){var contents=s.contents,dataTypes=s.dataTypes,responseFields=s.responseFields,ct,type,finalDataType,firstDataType;// Fill responseXXX fields
for(type in responseFields){if(type in responses){jqXHR[responseFields[type]]=responses[type];}}// Remove auto dataType and get content-type in the process
while(dataTypes[0]==="*"){dataTypes.shift();if(ct===undefined){ct=s.mimeType||jqXHR.getResponseHeader("content-type");}}// Check if we're dealing with a known content-type
if(ct){for(type in contents){if(contents[type]&&contents[type].test(ct)){dataTypes.unshift(type);break;}}}// Check to see if we have a response for the expected dataType
if(dataTypes[0]in responses){finalDataType=dataTypes[0];}else{// Try convertible dataTypes
for(type in responses){if(!dataTypes[0]||s.converters[type+" "+dataTypes[0]]){finalDataType=type;break;}if(!firstDataType){firstDataType=type;}}// Or just use first one
finalDataType=finalDataType||firstDataType;}// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if(finalDataType){if(finalDataType!==dataTypes[0]){dataTypes.unshift(finalDataType);}return responses[finalDataType];}}// Chain conversions given the request and the original response
function ajaxConvert(s,response){// Apply the dataFilter if provided
if(s.dataFilter){response=s.dataFilter(response,s.dataType);}var dataTypes=s.dataTypes,converters={},i,key,length=dataTypes.length,tmp,// Current and previous dataTypes
current=dataTypes[0],prev,// Conversion expression
conversion,// Conversion function
conv,// Conversion functions (transitive conversion)
conv1,conv2;// For each dataType in the chain
for(i=1;i<length;i++){// Create converters map
// with lowercased keys
if(i===1){for(key in s.converters){if(typeof key==="string"){converters[key.toLowerCase()]=s.converters[key];}}}// Get the dataTypes
prev=current;current=dataTypes[i];// If current is auto dataType, update it to prev
if(current==="*"){current=prev;// If no auto and dataTypes are actually different
}else if(prev!=="*"&&prev!==current){// Get the converter
conversion=prev+" "+current;conv=converters[conversion]||converters["* "+current];// If there is no direct converter, search transitively
if(!conv){conv2=undefined;for(conv1 in converters){tmp=conv1.split(" ");if(tmp[0]===prev||tmp[0]==="*"){conv2=converters[tmp[1]+" "+current];if(conv2){conv1=converters[conv1];if(conv1===true){conv=conv2;}else if(conv2===true){conv=conv1;}break;}}}}// If we found no converter, dispatch an error
if(!(conv||conv2)){jQuery.error("No conversion from "+conversion.replace(" "," to "));}// If found converter is not an equivalence
if(conv!==true){// Convert with 1 or 2 converters accordingly
response=conv?conv(response):conv2(conv1(response));}}}return response;}var jsc=jQuery.now(),jsre=/(\=)\?(&|$)|\?\?/i;// Default jsonp settings
jQuery.ajaxSetup({jsonp:"callback",jsonpCallback:function jsonpCallback(){return jQuery.expando+"_"+jsc++;}});// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter("json jsonp",function(s,originalSettings,jqXHR){var inspectData=s.contentType==="application/x-www-form-urlencoded"&&typeof s.data==="string";if(s.dataTypes[0]==="jsonp"||s.jsonp!==false&&(jsre.test(s.url)||inspectData&&jsre.test(s.data))){var responseContainer,jsonpCallback=s.jsonpCallback=jQuery.isFunction(s.jsonpCallback)?s.jsonpCallback():s.jsonpCallback,previous=window[jsonpCallback],url=s.url,data=s.data,replace="$1"+jsonpCallback+"$2";if(s.jsonp!==false){url=url.replace(jsre,replace);if(s.url===url){if(inspectData){data=data.replace(jsre,replace);}if(s.data===data){// Add callback manually
url+=(/\?/.test(url)?"&":"?")+s.jsonp+"="+jsonpCallback;}}}s.url=url;s.data=data;// Install callback
window[jsonpCallback]=function(response){responseContainer=[response];};// Clean-up function
jqXHR.always(function(){// Set callback back to previous value
window[jsonpCallback]=previous;// Call if it was a function and we have a response
if(responseContainer&&jQuery.isFunction(previous)){window[jsonpCallback](responseContainer[0]);}});// Use data converter to retrieve json after script execution
s.converters["script json"]=function(){if(!responseContainer){jQuery.error(jsonpCallback+" was not called");}return responseContainer[0];};// force json dataType
s.dataTypes[0]="json";// Delegate to script
return"script";}});// Install script dataType
jQuery.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function textScript(text){jQuery.globalEval(text);return text;}}});// Handle cache's special case and global
jQuery.ajaxPrefilter("script",function(s){if(s.cache===undefined){s.cache=false;}if(s.crossDomain){s.type="GET";s.global=false;}});// Bind script tag hack transport
jQuery.ajaxTransport("script",function(s){// This transport only deals with cross domain requests
if(s.crossDomain){var script,head=document.head||document.getElementsByTagName("head")[0]||document.documentElement;return{send:function send(_,callback){script=document.createElement("script");script.async="async";if(s.scriptCharset){script.charset=s.scriptCharset;}script.src=s.url;// Attach handlers for all browsers
script.onload=script.onreadystatechange=function(_,isAbort){if(isAbort||!script.readyState||/loaded|complete/.test(script.readyState)){// Handle memory leak in IE
script.onload=script.onreadystatechange=null;// Remove the script
if(head&&script.parentNode){head.removeChild(script);}// Dereference the script
script=undefined;// Callback if not abort
if(!isAbort){callback(200,"success");}}};// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore(script,head.firstChild);},abort:function abort(){if(script){script.onload(0,1);}}};}});var// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort=window.ActiveXObject?function(){// Abort all pending requests
for(var key in xhrCallbacks){xhrCallbacks[key](0,1);}}:false,xhrId=0,xhrCallbacks;// Functions to create xhrs
function createStandardXHR(){try{return new window.XMLHttpRequest();}catch(e){}}function createActiveXHR(){try{return new window.ActiveXObject("Microsoft.XMLHTTP");}catch(e){}}// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr=window.ActiveXObject?/* Microsoft failed to properly
         * implement the XMLHttpRequest in IE7 (can't request local files),
         * so we use the ActiveXObject when it is available
         * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
         * we need a fallback.
         */function(){return!this.isLocal&&createStandardXHR()||createActiveXHR();}:// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;// Determine support properties
(function(xhr){jQuery.extend(jQuery.support,{ajax:!!xhr,cors:!!xhr&&"withCredentials"in xhr});})(jQuery.ajaxSettings.xhr());// Create transport if the browser can provide an xhr
if(jQuery.support.ajax){jQuery.ajaxTransport(function(s){// Cross domain only allowed if supported through XMLHttpRequest
if(!s.crossDomain||jQuery.support.cors){var _callback;return{send:function send(headers,complete){// Get a new xhr
var xhr=s.xhr(),handle,i;// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if(s.username){xhr.open(s.type,s.url,s.async,s.username,s.password);}else{xhr.open(s.type,s.url,s.async);}// Apply custom fields if provided
if(s.xhrFields){for(i in s.xhrFields){xhr[i]=s.xhrFields[i];}}// Override mime type if needed
if(s.mimeType&&xhr.overrideMimeType){xhr.overrideMimeType(s.mimeType);}// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if(!s.crossDomain&&!headers["X-Requested-With"]){headers["X-Requested-With"]="XMLHttpRequest";}// Need an extra try/catch for cross domain requests in Firefox 3
try{for(i in headers){xhr.setRequestHeader(i,headers[i]);}}catch(_){}// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send(s.hasContent&&s.data||null);// Listener
_callback=function callback(_,isAbort){var status,statusText,responseHeaders,responses,xml;// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try{// Was never called and is aborted or complete
if(_callback&&(isAbort||xhr.readyState===4)){// Only called once
_callback=undefined;// Do not keep as active anymore
if(handle){xhr.onreadystatechange=jQuery.noop;if(xhrOnUnloadAbort){delete xhrCallbacks[handle];}}// If it's an abort
if(isAbort){// Abort it manually if needed
if(xhr.readyState!==4){xhr.abort();}}else{status=xhr.status;responseHeaders=xhr.getAllResponseHeaders();responses={};xml=xhr.responseXML;// Construct response list
if(xml&&xml.documentElement/* #4958 */){responses.xml=xml;}responses.text=xhr.responseText;// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try{statusText=xhr.statusText;}catch(e){// We normalize with Webkit giving an empty statusText
statusText="";}// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if(!status&&s.isLocal&&!s.crossDomain){status=responses.text?200:404;// IE - #1450: sometimes returns 1223 when it should be 204
}else if(status===1223){status=204;}}}}catch(firefoxAccessException){if(!isAbort){complete(-1,firefoxAccessException);}}// Call complete if needed
if(responses){complete(status,statusText,responses,responseHeaders);}};// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if(!s.async||xhr.readyState===4){_callback();}else{handle=++xhrId;if(xhrOnUnloadAbort){// Create the active xhrs callbacks list if needed
// and attach the unload handler
if(!xhrCallbacks){xhrCallbacks={};jQuery(window).unload(xhrOnUnloadAbort);}// Add to list of active xhrs callbacks
xhrCallbacks[handle]=_callback;}xhr.onreadystatechange=_callback;}},abort:function abort(){if(_callback){_callback(0,1);}}};}});}var elemdisplay={},iframe,iframeDoc,rfxtypes=/^(?:toggle|show|hide)$/,rfxnum=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,timerId,fxAttrs=[// height animations
["height","marginTop","marginBottom","paddingTop","paddingBottom"],// width animations
["width","marginLeft","marginRight","paddingLeft","paddingRight"],// opacity animations
["opacity"]],fxNow;jQuery.fn.extend({show:function show(speed,easing,callback){var elem,display;if(speed||speed===0){return this.animate(genFx("show",3),speed,easing,callback);}else{for(var i=0,j=this.length;i<j;i++){elem=this[i];if(elem.style){display=elem.style.display;// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if(!jQuery._data(elem,"olddisplay")&&display==="none"){display=elem.style.display="";}// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if(display===""&&jQuery.css(elem,"display")==="none"){jQuery._data(elem,"olddisplay",defaultDisplay(elem.nodeName));}}}// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for(i=0;i<j;i++){elem=this[i];if(elem.style){display=elem.style.display;if(display===""||display==="none"){elem.style.display=jQuery._data(elem,"olddisplay")||"";}}}return this;}},hide:function hide(speed,easing,callback){if(speed||speed===0){return this.animate(genFx("hide",3),speed,easing,callback);}else{var elem,display,i=0,j=this.length;for(;i<j;i++){elem=this[i];if(elem.style){display=jQuery.css(elem,"display");if(display!=="none"&&!jQuery._data(elem,"olddisplay")){jQuery._data(elem,"olddisplay",display);}}}// Set the display of the elements in a second loop
// to avoid the constant reflow
for(i=0;i<j;i++){if(this[i].style){this[i].style.display="none";}}return this;}},// Save the old toggle function
_toggle:jQuery.fn.toggle,toggle:function toggle(fn,fn2,callback){var bool=typeof fn==="boolean";if(jQuery.isFunction(fn)&&jQuery.isFunction(fn2)){this._toggle.apply(this,arguments);}else if(fn==null||bool){this.each(function(){var state=bool?fn:jQuery(this).is(":hidden");jQuery(this)[state?"show":"hide"]();});}else{this.animate(genFx("toggle",3),fn,fn2,callback);}return this;},fadeTo:function fadeTo(speed,to,easing,callback){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:to},speed,easing,callback);},animate:function animate(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);if(jQuery.isEmptyObject(prop)){return this.each(optall.complete,[false]);}// Do not change referenced properties as per-property easing will be lost
prop=jQuery.extend({},prop);function doAnimation(){// XXX 'this' does not always have a nodeName when running the
// test suite
if(optall.queue===false){jQuery._mark(this);}var opt=jQuery.extend({},optall),isElement=this.nodeType===1,hidden=isElement&&jQuery(this).is(":hidden"),name,val,p,e,parts,start,end,unit,method;// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties={};for(p in prop){// property name normalization
name=jQuery.camelCase(p);if(p!==name){prop[name]=prop[p];delete prop[p];}val=prop[name];// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if(jQuery.isArray(val)){opt.animatedProperties[name]=val[1];val=prop[name]=val[0];}else{opt.animatedProperties[name]=opt.specialEasing&&opt.specialEasing[name]||opt.easing||'swing';}if(val==="hide"&&hidden||val==="show"&&!hidden){return opt.complete.call(this);}if(isElement&&(name==="height"||name==="width")){// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if(jQuery.css(this,"display")==="inline"&&jQuery.css(this,"float")==="none"){// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if(!jQuery.support.inlineBlockNeedsLayout||defaultDisplay(this.nodeName)==="inline"){this.style.display="inline-block";}else{this.style.zoom=1;}}}}if(opt.overflow!=null){this.style.overflow="hidden";}for(p in prop){e=new jQuery.fx(this,opt,p);val=prop[p];if(rfxtypes.test(val)){// Tracks whether to show or hide based on private
// data attached to the element
method=jQuery._data(this,"toggle"+p)||(val==="toggle"?hidden?"show":"hide":0);if(method){jQuery._data(this,"toggle"+p,method==="show"?"hide":"show");e[method]();}else{e[val]();}}else{parts=rfxnum.exec(val);start=e.cur();if(parts){end=parseFloat(parts[2]);unit=parts[3]||(jQuery.cssNumber[p]?"":"px");// We need to compute starting value
if(unit!=="px"){jQuery.style(this,p,(end||1)+unit);start=(end||1)/e.cur()*start;jQuery.style(this,p,start+unit);}// If a +=/-= token was provided, we're doing a relative animation
if(parts[1]){end=(parts[1]==="-="?-1:1)*end+start;}e.custom(start,end,unit);}else{e.custom(start,val,"");}}}// For JS strict compliance
return true;}return optall.queue===false?this.each(doAnimation):this.queue(optall.queue,doAnimation);},stop:function stop(type,clearQueue,gotoEnd){if(typeof type!=="string"){gotoEnd=clearQueue;clearQueue=type;type=undefined;}if(clearQueue&&type!==false){this.queue(type||"fx",[]);}return this.each(function(){var index,hadTimers=false,timers=jQuery.timers,data=jQuery._data(this);// clear marker counters if we know they won't be
if(!gotoEnd){jQuery._unmark(true,this);}function stopQueue(elem,data,index){var hooks=data[index];jQuery.removeData(elem,index,true);hooks.stop(gotoEnd);}if(type==null){for(index in data){if(data[index]&&data[index].stop&&index.indexOf(".run")===index.length-4){stopQueue(this,data,index);}}}else if(data[index=type+".run"]&&data[index].stop){stopQueue(this,data,index);}for(index=timers.length;index--;){if(timers[index].elem===this&&(type==null||timers[index].queue===type)){if(gotoEnd){// force the next step to be the last
timers[index](true);}else{timers[index].saveState();}hadTimers=true;timers.splice(index,1);}}// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if(!(gotoEnd&&hadTimers)){jQuery.dequeue(this,type);}});}});// Animations created synchronously will run synchronously
function createFxNow(){setTimeout(clearFxNow,0);return fxNow=jQuery.now();}function clearFxNow(){fxNow=undefined;}// Generate parameters to create a standard animation
function genFx(type,num){var obj={};jQuery.each(fxAttrs.concat.apply([],fxAttrs.slice(0,num)),function(){obj[this]=type;});return obj;}// Generate shortcuts for custom animations
jQuery.each({slideDown:genFx("show",1),slideUp:genFx("hide",1),slideToggle:genFx("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(name,props){jQuery.fn[name]=function(speed,easing,callback){return this.animate(props,speed,easing,callback);};});jQuery.extend({speed:function speed(_speed,easing,fn){var opt=_speed&&(typeof _speed==="undefined"?"undefined":_typeof(_speed))==="object"?jQuery.extend({},_speed):{complete:fn||!fn&&easing||jQuery.isFunction(_speed)&&_speed,duration:_speed,easing:fn&&easing||easing&&!jQuery.isFunction(easing)&&easing};opt.duration=jQuery.fx.off?0:typeof opt.duration==="number"?opt.duration:opt.duration in jQuery.fx.speeds?jQuery.fx.speeds[opt.duration]:jQuery.fx.speeds._default;// normalize opt.queue - true/undefined/null -> "fx"
if(opt.queue==null||opt.queue===true){opt.queue="fx";}// Queueing
opt.old=opt.complete;opt.complete=function(noUnmark){if(jQuery.isFunction(opt.old)){opt.old.call(this);}if(opt.queue){jQuery.dequeue(this,opt.queue);}else if(noUnmark!==false){jQuery._unmark(this);}};return opt;},easing:{linear:function linear(p,n,firstNum,diff){return firstNum+diff*p;},swing:function swing(p,n,firstNum,diff){return(-Math.cos(p*Math.PI)/2+0.5)*diff+firstNum;}},timers:[],fx:function fx(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;options.orig=options.orig||{};}});jQuery.fx.prototype={// Simple function for setting a style value
update:function update(){if(this.options.step){this.options.step.call(this.elem,this.now,this);}(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);},// Get the current size
cur:function cur(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop];}var parsed,r=jQuery.css(this.elem,this.prop);// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN(parsed=parseFloat(r))?!r||r==="auto"?0:r:parsed;},// Start an animation from one number to another
custom:function custom(from,to,unit){var self=this,fx=jQuery.fx;this.startTime=fxNow||createFxNow();this.end=to;this.now=this.start=from;this.pos=this.state=0;this.unit=unit||this.unit||(jQuery.cssNumber[this.prop]?"":"px");function t(gotoEnd){return self.step(gotoEnd);}t.queue=this.options.queue;t.elem=this.elem;t.saveState=function(){if(self.options.hide&&jQuery._data(self.elem,"fxshow"+self.prop)===undefined){jQuery._data(self.elem,"fxshow"+self.prop,self.start);}};if(t()&&jQuery.timers.push(t)&&!timerId){timerId=setInterval(fx.tick,fx.interval);}},// Simple 'show' function
show:function show(){var dataShow=jQuery._data(this.elem,"fxshow"+this.prop);// Remember where we started, so that we can go back to it later
this.options.orig[this.prop]=dataShow||jQuery.style(this.elem,this.prop);this.options.show=true;// Begin the animation
// Make sure that we start at a small width/height to avoid any flash of content
if(dataShow!==undefined){// This show is picking up where a previous hide or show left off
this.custom(this.cur(),dataShow);}else{this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());}// Start by showing the element
jQuery(this.elem).show();},// Simple 'hide' function
hide:function hide(){// Remember where we started, so that we can go back to it later
this.options.orig[this.prop]=jQuery._data(this.elem,"fxshow"+this.prop)||jQuery.style(this.elem,this.prop);this.options.hide=true;// Begin the animation
this.custom(this.cur(),0);},// Each step of an animation
step:function step(gotoEnd){var p,n,complete,t=fxNow||createFxNow(),done=true,elem=this.elem,options=this.options;if(gotoEnd||t>=options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();options.animatedProperties[this.prop]=true;for(p in options.animatedProperties){if(options.animatedProperties[p]!==true){done=false;}}if(done){// Reset the overflow
if(options.overflow!=null&&!jQuery.support.shrinkWrapBlocks){jQuery.each(["","X","Y"],function(index,value){elem.style["overflow"+value]=options.overflow[index];});}// Hide the element if the "hide" operation was done
if(options.hide){jQuery(elem).hide();}// Reset the properties, if the item has been hidden or shown
if(options.hide||options.show){for(p in options.animatedProperties){jQuery.style(elem,p,options.orig[p]);jQuery.removeData(elem,"fxshow"+p,true);// Toggle data is no longer needed
jQuery.removeData(elem,"toggle"+p,true);}}// Execute the complete function
// in the event that the complete function throws an exception
// we must ensure it won't be called twice. #5684
complete=options.complete;if(complete){options.complete=false;complete.call(elem);}}return false;}else{// classical easing cannot be used with an Infinity duration
if(options.duration==Infinity){this.now=t;}else{n=t-this.startTime;this.state=n/options.duration;// Perform the easing function, defaults to swing
this.pos=jQuery.easing[options.animatedProperties[this.prop]](this.state,n,0,1,options.duration);this.now=this.start+(this.end-this.start)*this.pos;}// Perform the next step of the animation
this.update();}return true;}};jQuery.extend(jQuery.fx,{tick:function tick(){var timer,timers=jQuery.timers,i=0;for(;i<timers.length;i++){timer=timers[i];// Checks the timer has not already been removed
if(!timer()&&timers[i]===timer){timers.splice(i--,1);}}if(!timers.length){jQuery.fx.stop();}},interval:13,stop:function stop(){clearInterval(timerId);timerId=null;},speeds:{slow:600,fast:200,// Default speed
_default:400},step:{opacity:function opacity(fx){jQuery.style(fx.elem,"opacity",fx.now);},_default:function _default(fx){if(fx.elem.style&&fx.elem.style[fx.prop]!=null){fx.elem.style[fx.prop]=fx.now+fx.unit;}else{fx.elem[fx.prop]=fx.now;}}}});// Adds width/height step functions
// Do not set anything below 0
jQuery.each(["width","height"],function(i,prop){jQuery.fx.step[prop]=function(fx){jQuery.style(fx.elem,prop,Math.max(0,fx.now)+fx.unit);};});if(jQuery.expr&&jQuery.expr.filters){jQuery.expr.filters.animated=function(elem){return jQuery.grep(jQuery.timers,function(fn){return elem===fn.elem;}).length;};}// Try to restore the default display value of an element
function defaultDisplay(nodeName){if(!elemdisplay[nodeName]){var body=document.body,elem=jQuery("<"+nodeName+">").appendTo(body),display=elem.css("display");elem.remove();// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if(display==="none"||display===""){// No iframe to use yet, so create it
if(!iframe){iframe=document.createElement("iframe");iframe.frameBorder=iframe.width=iframe.height=0;}body.appendChild(iframe);// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if(!iframeDoc||!iframe.createElement){iframeDoc=(iframe.contentWindow||iframe.contentDocument).document;iframeDoc.write((document.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>");iframeDoc.close();}elem=iframeDoc.createElement(nodeName);iframeDoc.body.appendChild(elem);display=jQuery.css(elem,"display");body.removeChild(iframe);}// Store the correct default display
elemdisplay[nodeName]=display;}return elemdisplay[nodeName];}var rtable=/^t(?:able|d|h)$/i,rroot=/^(?:body|html)$/i;if("getBoundingClientRect"in document.documentElement){jQuery.fn.offset=function(options){var elem=this[0],box;if(options){return this.each(function(i){jQuery.offset.setOffset(this,options,i);});}if(!elem||!elem.ownerDocument){return null;}if(elem===elem.ownerDocument.body){return jQuery.offset.bodyOffset(elem);}try{box=elem.getBoundingClientRect();}catch(e){}var doc=elem.ownerDocument,docElem=doc.documentElement;// Make sure we're not dealing with a disconnected DOM node
if(!box||!jQuery.contains(docElem,elem)){return box?{top:box.top,left:box.left}:{top:0,left:0};}var body=doc.body,win=getWindow(doc),clientTop=docElem.clientTop||body.clientTop||0,clientLeft=docElem.clientLeft||body.clientLeft||0,scrollTop=win.pageYOffset||jQuery.support.boxModel&&docElem.scrollTop||body.scrollTop,scrollLeft=win.pageXOffset||jQuery.support.boxModel&&docElem.scrollLeft||body.scrollLeft,top=box.top+scrollTop-clientTop,left=box.left+scrollLeft-clientLeft;return{top:top,left:left};};}else{jQuery.fn.offset=function(options){var elem=this[0];if(options){return this.each(function(i){jQuery.offset.setOffset(this,options,i);});}if(!elem||!elem.ownerDocument){return null;}if(elem===elem.ownerDocument.body){return jQuery.offset.bodyOffset(elem);}var computedStyle,offsetParent=elem.offsetParent,prevOffsetParent=elem,doc=elem.ownerDocument,docElem=doc.documentElement,body=doc.body,defaultView=doc.defaultView,prevComputedStyle=defaultView?defaultView.getComputedStyle(elem,null):elem.currentStyle,top=elem.offsetTop,left=elem.offsetLeft;while((elem=elem.parentNode)&&elem!==body&&elem!==docElem){if(jQuery.support.fixedPosition&&prevComputedStyle.position==="fixed"){break;}computedStyle=defaultView?defaultView.getComputedStyle(elem,null):elem.currentStyle;top-=elem.scrollTop;left-=elem.scrollLeft;if(elem===offsetParent){top+=elem.offsetTop;left+=elem.offsetLeft;if(jQuery.support.doesNotAddBorder&&!(jQuery.support.doesAddBorderForTableAndCells&&rtable.test(elem.nodeName))){top+=parseFloat(computedStyle.borderTopWidth)||0;left+=parseFloat(computedStyle.borderLeftWidth)||0;}prevOffsetParent=offsetParent;offsetParent=elem.offsetParent;}if(jQuery.support.subtractsBorderForOverflowNotVisible&&computedStyle.overflow!=="visible"){top+=parseFloat(computedStyle.borderTopWidth)||0;left+=parseFloat(computedStyle.borderLeftWidth)||0;}prevComputedStyle=computedStyle;}if(prevComputedStyle.position==="relative"||prevComputedStyle.position==="static"){top+=body.offsetTop;left+=body.offsetLeft;}if(jQuery.support.fixedPosition&&prevComputedStyle.position==="fixed"){top+=Math.max(docElem.scrollTop,body.scrollTop);left+=Math.max(docElem.scrollLeft,body.scrollLeft);}return{top:top,left:left};};}jQuery.offset={bodyOffset:function bodyOffset(body){var top=body.offsetTop,left=body.offsetLeft;if(jQuery.support.doesNotIncludeMarginInBodyOffset){top+=parseFloat(jQuery.css(body,"marginTop"))||0;left+=parseFloat(jQuery.css(body,"marginLeft"))||0;}return{top:top,left:left};},setOffset:function setOffset(elem,options,i){var position=jQuery.css(elem,"position");// set position first, in-case top/left are set even on static elem
if(position==="static"){elem.style.position="relative";}var curElem=jQuery(elem),curOffset=curElem.offset(),curCSSTop=jQuery.css(elem,"top"),curCSSLeft=jQuery.css(elem,"left"),calculatePosition=(position==="absolute"||position==="fixed")&&jQuery.inArray("auto",[curCSSTop,curCSSLeft])>-1,props={},curPosition={},curTop,curLeft;// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if(calculatePosition){curPosition=curElem.position();curTop=curPosition.top;curLeft=curPosition.left;}else{curTop=parseFloat(curCSSTop)||0;curLeft=parseFloat(curCSSLeft)||0;}if(jQuery.isFunction(options)){options=options.call(elem,i,curOffset);}if(options.top!=null){props.top=options.top-curOffset.top+curTop;}if(options.left!=null){props.left=options.left-curOffset.left+curLeft;}if("using"in options){options.using.call(elem,props);}else{curElem.css(props);}}};jQuery.fn.extend({position:function position(){if(!this[0]){return null;}var elem=this[0],// Get *real* offsetParent
offsetParent=this.offsetParent(),// Get correct offsets
offset=this.offset(),parentOffset=rroot.test(offsetParent[0].nodeName)?{top:0,left:0}:offsetParent.offset();// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top-=parseFloat(jQuery.css(elem,"marginTop"))||0;offset.left-=parseFloat(jQuery.css(elem,"marginLeft"))||0;// Add offsetParent borders
parentOffset.top+=parseFloat(jQuery.css(offsetParent[0],"borderTopWidth"))||0;parentOffset.left+=parseFloat(jQuery.css(offsetParent[0],"borderLeftWidth"))||0;// Subtract the two offsets
return{top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};},offsetParent:function offsetParent(){return this.map(function(){var offsetParent=this.offsetParent||document.body;while(offsetParent&&!rroot.test(offsetParent.nodeName)&&jQuery.css(offsetParent,"position")==="static"){offsetParent=offsetParent.offsetParent;}return offsetParent;});}});// Create scrollLeft and scrollTop methods
jQuery.each(["Left","Top"],function(i,name){var method="scroll"+name;jQuery.fn[method]=function(val){var elem,win;if(val===undefined){elem=this[0];if(!elem){return null;}win=getWindow(elem);// Return the scroll offset
return win?"pageXOffset"in win?win[i?"pageYOffset":"pageXOffset"]:jQuery.support.boxModel&&win.document.documentElement[method]||win.document.body[method]:elem[method];}// Set the scroll offset
return this.each(function(){win=getWindow(this);if(win){win.scrollTo(!i?val:jQuery(win).scrollLeft(),i?val:jQuery(win).scrollTop());}else{this[method]=val;}});};});function getWindow(elem){return jQuery.isWindow(elem)?elem:elem.nodeType===9?elem.defaultView||elem.parentWindow:false;}// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();// innerHeight and innerWidth
jQuery.fn["inner"+name]=function(){var elem=this[0];return elem?elem.style?parseFloat(jQuery.css(elem,type,"padding")):this[type]():null;};// outerHeight and outerWidth
jQuery.fn["outer"+name]=function(margin){var elem=this[0];return elem?elem.style?parseFloat(jQuery.css(elem,type,margin?"margin":"border")):this[type]():null;};jQuery.fn[type]=function(size){// Get window width or height
var elem=this[0];if(!elem){return size==null?null:this;}if(jQuery.isFunction(size)){return this.each(function(i){var self=jQuery(this);self[type](size.call(this,i,self[type]()));});}if(jQuery.isWindow(elem)){// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp=elem.document.documentElement["client"+name],body=elem.document.body;return elem.document.compatMode==="CSS1Compat"&&docElemProp||body&&body["client"+name]||docElemProp;// Get document width or height
}else if(elem.nodeType===9){// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(elem.documentElement["client"+name],elem.body["scroll"+name],elem.documentElement["scroll"+name],elem.body["offset"+name],elem.documentElement["offset"+name]);// Get or set width or height on the element
}else if(size===undefined){var orig=jQuery.css(elem,type),ret=parseFloat(orig);return jQuery.isNumeric(ret)?ret:orig;// Set the width or height on the element (default to pixels if value is unitless)
}else{return this.css(type,typeof size==="string"?size:size+"px");}};});// Expose jQuery to the global object
window.jQuery=window.$=jQuery;// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if(typeof define==="function"&&define.amd&&define.amd.jQuery){define("jquery",[],function(){return jQuery;});}})(window);window.jQuery.noConflict();return window.jQuery;}module.exports=create('undefined'===typeof window?undefined:window);module.exports.create=create;})();},{}],8:[function(require,module,exports){/*
 * Copyright 2012 Small Batch, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */;(function(window,document,undefined){function i(a){return function(){return this[a];};}var j;function n(a,b){var c=arguments.length>2?Array.prototype.slice.call(arguments,2):[];return function(){c.push.apply(c,arguments);return b.apply(a,c);};};function o(a,b){this.K=a;this.c=b;}o.prototype.createElement=function(a,b,c){a=this.K.createElement(a);if(b)for(var d in b){if(b.hasOwnProperty(d))d=="style"?q(this,a,b[d]):a.setAttribute(d,b[d]);}c&&a.appendChild(this.K.createTextNode(c));return a;};function r(a,b,c){a=a.K.getElementsByTagName(b)[0];if(!a)a=document.documentElement;if(a&&a.lastChild){a.insertBefore(c,a.lastChild);return true;}return false;}function aa(a,b){function c(){document.body?b():setTimeout(c,0);}c();}function s(a,b){if(b.parentNode){b.parentNode.removeChild(b);return true;}return false;}function t(a,b){return a.createElement("link",{rel:"stylesheet",href:b});}function u(a,b){return a.createElement("script",{src:b});}function v(a,b,c){a=b.className.split(/\s+/);for(var d=0,e=a.length;d<e;d++){if(a[d]==c)return;}a.push(c);b.className=a.join(" ").replace(/^\s+/,"");}function w(a,b,c){a=b.className.split(/\s+/);for(var d=[],e=0,f=a.length;e<f;e++){a[e]!=c&&d.push(a[e]);}b.className=d.join(" ").replace(/^\s+/,"").replace(/\s+$/,"");}function x(a,b,c){a=b.className.split(/\s+/);b=0;for(var d=a.length;b<d;b++){if(a[b]==c)return true;}return false;}function q(a,b,c){if(a.c.getName()=="MSIE")b.style.cssText=c;else b.setAttribute("style",c);};function y(a,b,c,d,e,f,g,h){this.Ba=a;this.Ha=b;this.oa=c;this.na=d;this.Ea=e;this.Da=f;this.ma=g;this.Ia=h;}j=y.prototype;j.getName=i("Ba");j.xa=i("Ha");j.Y=i("oa");j.ua=i("na");j.va=i("Ea");j.wa=i("Da");j.ta=i("ma");j.w=i("Ia");function z(a,b){this.c=a;this.k=b;}var ba=new y("Unknown","Unknown","Unknown","Unknown","Unknown","Unknown",undefined,false);z.prototype.parse=function(){return this.c.indexOf("MSIE")!=-1?ca(this):this.c.indexOf("Opera")!=-1?da(this):this.c.indexOf("AppleWebKit")!=-1?ea(this):this.c.indexOf("Gecko")!=-1?fa(this):ba;};function A(a){var b=C(a,a.c,/(iPod|iPad|iPhone|Android)/,1);if(b!="")return b;a=C(a,a.c,/(Linux|Mac_PowerPC|Macintosh|Windows)/,1);if(a!=""){if(a=="Mac_PowerPC")a="Macintosh";return a;}return"Unknown";}function D(a){var b=C(a,a.c,/(OS X|Windows NT|Android) ([^;)]+)/,2);if(b)return b;if(b=C(a,a.c,/(iPhone )?OS ([\d_]+)/,2))return b;if(a=C(a,a.c,/Linux ([i\d]+)/,1))return a;return"Unknown";}function ca(a){var b=C(a,a.c,/(MSIE [\d\w\.]+)/,1);if(b!=""){var c=b.split(" ");b=c[0];c=c[1];return new y(b,c,b,c,A(a),D(a),E(a,a.k),F(a,c)>=6);}return new y("MSIE","Unknown","MSIE","Unknown",A(a),D(a),E(a,a.k),false);}function da(a){var b="Unknown",c="Unknown",d=C(a,a.c,/(Presto\/[\d\w\.]+)/,1);if(d!=""){c=d.split("/");b=c[0];c=c[1];}else{if(a.c.indexOf("Gecko")!=-1)b="Gecko";d=C(a,a.c,/rv:([^\)]+)/,1);if(d!="")c=d;}if(a.c.indexOf("Version/")!=-1){d=C(a,a.c,/Version\/([\d\.]+)/,1);if(d!="")return new y("Opera",d,b,c,A(a),D(a),E(a,a.k),F(a,d)>=10);}d=C(a,a.c,/Opera[\/ ]([\d\.]+)/,1);if(d!="")return new y("Opera",d,b,c,A(a),D(a),E(a,a.k),F(a,d)>=10);return new y("Opera","Unknown",b,c,A(a),D(a),E(a,a.k),false);}function ea(a){var b=A(a),c=D(a),d=C(a,a.c,/AppleWebKit\/([\d\.\+]+)/,1);if(d=="")d="Unknown";var e="Unknown";if(a.c.indexOf("Chrome")!=-1)e="Chrome";else if(a.c.indexOf("Safari")!=-1)e="Safari";else if(a.c.indexOf("AdobeAIR")!=-1)e="AdobeAIR";var f="Unknown";if(a.c.indexOf("Version/")!=-1)f=C(a,a.c,/Version\/([\d\.\w]+)/,1);else if(e=="Chrome")f=C(a,a.c,/Chrome\/([\d\.]+)/,1);else if(e=="AdobeAIR")f=C(a,a.c,/AdobeAIR\/([\d\.]+)/,1);var g=false;if(e=="AdobeAIR"){g=C(a,f,/\d+\.(\d+)/,1);g=F(a,f)>2||F(a,f)==2&&parseInt(g,10)>=5;}else{g=C(a,d,/\d+\.(\d+)/,1);g=F(a,d)>=526||F(a,d)>=525&&parseInt(g,10)>=13;}return new y(e,f,"AppleWebKit",d,b,c,E(a,a.k),g);}function fa(a){var b="Unknown",c="Unknown",d=false;if(a.c.indexOf("Firefox")!=-1){b="Firefox";var e=C(a,a.c,/Firefox\/([\d\w\.]+)/,1);if(e!=""){d=C(a,e,/\d+\.(\d+)/,1);c=e;d=e!=""&&F(a,e)>=3&&parseInt(d,10)>=5;}}else if(a.c.indexOf("Mozilla")!=-1)b="Mozilla";e=C(a,a.c,/rv:([^\)]+)/,1);if(e=="")e="Unknown";else if(!d){d=F(a,e);var f=parseInt(C(a,e,/\d+\.(\d+)/,1),10),g=parseInt(C(a,e,/\d+\.\d+\.(\d+)/,1),10);d=d>1||d==1&&f>9||d==1&&f==9&&g>=2||e.match(/1\.9\.1b[123]/)!=null||e.match(/1\.9\.1\.[\d\.]+/)!=null;}return new y(b,c,"Gecko",e,A(a),D(a),E(a,a.k),d);}function F(a,b){a=C(a,b,/(\d+)/,1);if(a!="")return parseInt(a,10);return-1;}function C(a,b,c,d){if((a=b.match(c))&&a[d])return a[d];return"";}function E(a,b){if(b.documentMode)return b.documentMode;};function ga(a,b,c,d){this.a=a;this.g=b;this.U=c;this.j=d||ha;this.h=new G("-");}var ha="wf";function H(a){v(a.a,a.g,a.h.e(a.j,"loading"));I(a,"loading");}function J(a){w(a.a,a.g,a.h.e(a.j,"loading"));x(a.a,a.g,a.h.e(a.j,"active"))||v(a.a,a.g,a.h.e(a.j,"inactive"));I(a,"inactive");}function ia(a){w(a.a,a.g,a.h.e(a.j,"loading"));w(a.a,a.g,a.h.e(a.j,"inactive"));v(a.a,a.g,a.h.e(a.j,"active"));I(a,"active");}function I(a,b,c,d){a.U[b]&&a.U[b](c,d);};function ja(){this.fa={};}function ka(a,b){var c=[];for(var d in b){if(b.hasOwnProperty(d)){var e=a.fa[d];e&&c.push(e(b[d]));}}return c;};function L(a,b,c,d,e){this.a=a;this.A=b;this.n=c;this.u=d;this.D=e;this.V=0;this.ja=this.ea=false;}L.prototype.watch=function(a,b,c,d,e){for(var f=a.length,g=0;g<f;g++){var h=a[g];b[h]||(b[h]=["n4"]);this.V+=b[h].length;}if(e)this.ea=e;for(g=0;g<f;g++){h=a[g];e=b[h];for(var l=c[h],k=0,m=e.length;k<m;k++){var B=e[k],p=this.A,K=h;v(p.a,p.g,p.h.e(p.j,K,B,"loading"));I(p,"fontloading",K,B);p=n(this,this.qa);K=n(this,this.ra);new d(p,K,this.a,this.n,this.u,this.D,h,B,l).start();}}};L.prototype.qa=function(a,b){var c=this.A;w(c.a,c.g,c.h.e(c.j,a,b,"loading"));w(c.a,c.g,c.h.e(c.j,a,b,"inactive"));v(c.a,c.g,c.h.e(c.j,a,b,"active"));I(c,"fontactive",a,b);this.ja=true;M(this);};L.prototype.ra=function(a,b){var c=this.A;w(c.a,c.g,c.h.e(c.j,a,b,"loading"));x(c.a,c.g,c.h.e(c.j,a,b,"active"))||v(c.a,c.g,c.h.e(c.j,a,b,"inactive"));I(c,"fontinactive",a,b);M(this);};function M(a){if(--a.V==0&&a.ea)a.ja?ia(a.A):J(a.A);};function N(a,b,c,d,e,f,g,h,l){this.H=a;this.$=b;this.a=c;this.n=d;this.u=e;this.D=f;this.Aa=new la();this.v=new O();this.L=g;this.B=h;this.sa=l||ma;this.O=na(this,oa);this.P=na(this,pa);this.ca=this.O;this.da=this.P;this.Q=P(this,oa);this.R=P(this,pa);}var oa="arial,'URW Gothic L',sans-serif",pa="Georgia,'Century Schoolbook L',serif",ma="BESbswy";N.prototype.start=function(){this.ia=this.D();this.J();};N.prototype.J=function(){var a=this.n.p(this.Q),b=this.n.p(this.R);if((this.O!=a||this.P!=b)&&this.ca==a&&this.da==b)Q(this,this.H);else if(this.D()-this.ia>=5E3)Q(this,this.$);else{this.ca=a;this.da=b;qa(this);}};function qa(a){a.u(function(b,c){return function(){c.call(b);};}(a,a.J),25);}function Q(a,b){s(a.a,a.Q);s(a.a,a.R);b(a.L,a.B);}function na(a,b){b=P(a,b,true);var c=a.n.p(b);s(a.a,b);return c;}function P(a,b,c){b=a.a.createElement("span",{style:R(a,b,a.B,c)},a.sa);r(a.a,"body",b);return b;}function R(a,b,c,d){c=a.v.expand(c);return"position:absolute;top:-999px;left:-999px;font-size:300px;width:auto;height:auto;line-height:normal;margin:0;padding:0;font-variant:normal;font-family:"+(d?"":a.Aa.quote(a.L)+",")+b+";"+c;};function S(a,b,c,d,e){this.a=a;this.X=b;this.g=c;this.u=d;this.c=e;this.M=this.N=0;}S.prototype.q=function(a,b){this.X.fa[a]=b;};S.prototype.load=function(a){var b=new ga(this.a,this.g,a);this.c.w()?ra(this,b,a):J(b);};S.prototype.ya=function(a,b,c,d){var e=a.Z?a.Z():N;if(d)a.load(n(this,this.Ca,b,c,e));else{a=--this.N==0;this.M--;if(a)this.M==0?J(b):H(b);c.watch([],{},{},e,a);}};S.prototype.Ca=function(a,b,c,d,e,f){var g=--this.N==0;g&&H(a);this.u(n(this,function(h,l,k,m,B,p){h.watch(l,k||{},m||{},B,p);},b,d,e,f,c,g));};function ra(a,b,c){c=ka(a.X,c);a.M=a.N=c.length;for(var d=new L(a.a,b,{p:function p(h){return h.offsetWidth;}},a.u,function(){return new Date().getTime();}),e=0,f=c.length;e<f;e++){var g=c[e];g.z(a.c,n(a,a.ya,g,b,d));}};function G(a){this.za=a||sa;}var sa="-";G.prototype.e=function(){for(var a=[],b=0;b<arguments.length;b++){a.push(arguments[b].replace(/[\W_]+/g,"").toLowerCase());}return a.join(this.za);};function la(){this.ha="'";}la.prototype.quote=function(a){var b=[];a=a.split(/,\s*/);for(var c=0;c<a.length;c++){var d=a[c].replace(/['"]/g,"");d.indexOf(" ")==-1?b.push(d):b.push(this.ha+d+this.ha);}return b.join(",");};function O(){this.G=ta;this.o=ua;}var ta=["font-style","font-weight"],ua={"font-style":[["n","normal"],["i","italic"],["o","oblique"]],"font-weight":[["1","100"],["2","200"],["3","300"],["4","400"],["5","500"],["6","600"],["7","700"],["8","800"],["9","900"],["4","normal"],["7","bold"]]};function T(a,b,c){this.aa=a;this.Fa=b;this.o=c;}T.prototype.compact=function(a,b){for(var c=0;c<this.o.length;c++){if(b==this.o[c][1]){a[this.aa]=this.o[c][0];return;}}};T.prototype.expand=function(a,b){for(var c=0;c<this.o.length;c++){if(b==this.o[c][0]){a[this.aa]=this.Fa+":"+this.o[c][1];return;}}};O.prototype.compact=function(a){var b=["n","4"];a=a.split(";");for(var c=0,d=a.length;c<d;c++){var e=a[c].replace(/\s+/g,"").split(":");if(e.length==2){var f=e[1];a:{e=e[0];for(var g=0;g<this.G.length;g++){if(e==this.G[g]){e=new T(g,e,this.o[e]);break a;}}e=null;}e&&e.compact(b,f);}}return b.join("");};O.prototype.expand=function(a){if(a.length!=2)return null;for(var b=[null,null],c=0,d=this.G.length;c<d;c++){var e=this.G[c],f=a.substr(c,1);new T(c,e,this.o[e]).expand(b,f);}return b[0]&&b[1]?b.join(";")+";":null;};window.WebFont=function(){var a=new z(navigator.userAgent,document).parse();return new S(new o(document,a),new ja(),document.documentElement,function(b,c){setTimeout(b,c);},a);}();window.WebFont.load=window.WebFont.load;window.WebFont.addModule=window.WebFont.q;y.prototype.getName=y.prototype.getName;y.prototype.getVersion=y.prototype.xa;y.prototype.getEngine=y.prototype.Y;y.prototype.getEngineVersion=y.prototype.ua;y.prototype.getPlatform=y.prototype.va;y.prototype.getPlatformVersion=y.prototype.wa;y.prototype.getDocumentMode=y.prototype.ta;y.prototype.isSupportingWebFont=y.prototype.w;function U(a,b){this.a=a;this.d=b;}var va={regular:"n4",bold:"n7",italic:"i4",bolditalic:"i7",r:"n4",b:"n7",i:"i4",bi:"i7"};U.prototype.z=function(a,b){return b(a.w());};U.prototype.load=function(a){r(this.a,"head",t(this.a,("https:"==document.location.protocol?"https:":"http:")+"//webfonts.fontslive.com/css/"+this.d.key+".css"));var b;b=this.d.families;var c,d,e;c=[];d={};for(var f=0,g=b.length;f<g;f++){e=void 0;var h=void 0;h=void 0;h=b[f].split(":");e=h[0];h=h[1]?wa(this,h[1]):["n4"];e={W:e,T:h};c.push(e.W);d[e.W]=e.T;}b={pa:c,T:d};a(b.pa,b.T);};function wa(a,b){a=b.split(",");b=[];for(var c=0,d=a.length;c<d;c++){var e=a[c];if(e){var f=va[e];b.push(f?f:e);}}return b;}window.WebFont.q("ascender",function(a){var b=new z(navigator.userAgent,document).parse();return new U(new o(document,b),a);});function V(a,b,c,d,e,f,g,h,l){V.Ga.call(this,a,b,c,d,e,f,g,h,l);a=["Times New Roman","Lucida Sans Unicode","Courier New","Tahoma","Arial","Microsoft Sans Serif","Times","Lucida Console","Sans","Serif","Monospace"];b=a.length;c={};d=P(this,a[0],true);c[this.n.p(d)]=true;for(e=1;e<b;e++){f=a[e];q(this.a,d,R(this,f,this.B,true));c[this.n.p(d)]=true;if(this.B[1]!="4"){q(this.a,d,R(this,f,this.B[0]+"4",true));c[this.n.p(d)]=true;}}s(this.a,d);this.t=c;this.la=false;}(function(a,b){function c(){}c.prototype=a.prototype;b.prototype=new c();b.Ga=a;b.Ja=a.prototype;})(N,V);var xa={Arimo:true,Cousine:true,Tinos:true};V.prototype.J=function(){var a=this.n.p(this.Q),b=this.n.p(this.R);if(!this.la&&a==b&&this.t[a]){this.t={};this.la=this.t[a]=true;}if((this.O!=a||this.P!=b)&&!this.t[a]&&!this.t[b])Q(this,this.H);else if(this.D()-this.ia>=5E3)this.t[a]&&this.t[b]&&xa[this.L]?Q(this,this.H):Q(this,this.$);else qa(this);};function ya(a){this.I=a?a:("https:"==window.location.protocol?"https:":"http:")+za;this.f=[];this.S=[];}var za="//fonts.googleapis.com/css";ya.prototype.e=function(){if(this.f.length==0)throw new Error("No fonts to load !");if(this.I.indexOf("kit=")!=-1)return this.I;for(var a=this.f.length,b=[],c=0;c<a;c++){b.push(this.f[c].replace(/ /g,"+"));}a=this.I+"?family="+b.join("%7C");if(this.S.length>0)a+="&subset="+this.S.join(",");return a;};function Aa(a){this.f=a;this.ga=[];this.ka={};this.F={};this.v=new O();}var Ba={ultralight:"n2",light:"n3",regular:"n4",bold:"n7",italic:"i4",bolditalic:"i7",ul:"n2",l:"n3",r:"n4",b:"n7",i:"i4",bi:"i7"},Ca={latin:ma,cyrillic:"&#1081;&#1103;&#1046;",greek:"&#945;&#946;&#931;",khmer:"&#x1780;&#x1781;&#x1782;",Hanuman:"&#x1780;&#x1781;&#x1782;"};Aa.prototype.parse=function(){for(var a=this.f.length,b=0;b<a;b++){var c=this.f[b].split(":"),d=c[0],e=["n4"];if(c.length>=2){var f=c[1],g=[];if(f){f=f.split(",");for(var h=f.length,l=0;l<h;l++){var k;k=f[l];if(k.match(/^[\w ]+$/)){var m=Ba[k];if(m)k=m;else{m=k.match(/^(\d*)(\w*)$/);k=m[1];m=m[2];k=(k=this.v.expand([m?m:"n",k?k.substr(0,1):"4"].join("")))?this.v.compact(k):null;}}else k="";k&&g.push(k);}}if(g.length>0)e=g;if(c.length==3){c=c[2];g=[];c=c?c.split(","):g;if(c.length>0)if(c=Ca[c[0]])this.F[d]=c;}}if(!this.F[d])if(c=Ca[d])this.F[d]=c;this.ga.push(d);this.ka[d]=e;}};function W(a,b,c){this.c=a;this.a=b;this.d=c;}W.prototype.z=function(a,b){b(a.w());};W.prototype.Z=function(){if(this.c.Y()=="AppleWebKit")return V;return N;};W.prototype.load=function(a){var b=this.a;this.c.getName()=="MSIE"&&this.d.blocking!=true?aa(b,n(this,this.ba,a)):this.ba(a);};W.prototype.ba=function(a){for(var b=this.a,c=new ya(this.d.api),d=this.d.families,e=d.length,f=0;f<e;f++){var g=d[f].split(":");g.length==3&&c.S.push(g.pop());c.f.push(g.join(":"));}d=new Aa(d);d.parse();r(b,"head",t(b,c.e()));a(d.ga,d.ka,d.F);};window.WebFont.q("google",function(a){var b=new z(navigator.userAgent,document).parse();return new W(b,new o(document,b),a);});function X(a,b){this.a=a;this.d=b;}X.prototype.load=function(a){for(var b=this.d.urls||[],c=this.d.families||[],d=0,e=b.length;d<e;d++){r(this.a,"head",t(this.a,b[d]));}a(c);};X.prototype.z=function(a,b){return b(a.w());};window.WebFont.q("custom",function(a){var b=new z(navigator.userAgent,document).parse();return new X(new o(document,b),a);});function Y(a,b,c){this.m=a;this.a=b;this.d=c;this.f=[];this.s={};this.v=new O();}Y.prototype.C=function(a){return("https:"==this.m.location.protocol?"https:":"http:")+(this.d.api||"//f.fontdeck.com/s/css/js/")+this.m.document.location.hostname+"/"+a+".js";};Y.prototype.z=function(a,b){a=this.d.id;var c=this;if(a){this.m.__webfontfontdeckmodule__||(this.m.__webfontfontdeckmodule__={});this.m.__webfontfontdeckmodule__[a]=function(d,e){for(var f=0,g=e.fonts.length;f<g;++f){var h=e.fonts[f];c.f.push(h.name);c.s[h.name]=[c.v.compact("font-weight:"+h.weight+";font-style:"+h.style)];}b(d);};r(this.a,"head",u(this.a,this.C(a)));}else b(true);};Y.prototype.load=function(a){a(this.f,this.s);};window.WebFont.q("fontdeck",function(a){var b=new z(navigator.userAgent,document).parse();return new Y(window,new o(document,b),a);});function Z(a,b,c,d,e){this.m=a;this.c=b;this.a=c;this.k=d;this.d=e;this.f=[];this.s={};}Z.prototype.z=function(a,b){var c=this,d=c.d.projectId;if(d){var e=u(c.a,c.C(d));e.id="__MonotypeAPIScript__"+d;e.onreadystatechange=function(f){if(e.readyState==="loaded"||e.readyState==="complete"){e.onreadystatechange=null;e.onload(f);}};e.onload=function(){if(c.m["__mti_fntLst"+d]){var f=c.m["__mti_fntLst"+d]();if(f&&f.length){var g;for(g=0;g<f.length;g++){c.f.push(f[g].fontfamily);}}}b(a.w());};r(this.a,"head",e);}else b(true);};Z.prototype.C=function(a){var b=this.protocol(),c=(this.d.api||"fast.fonts.com/jsapi").replace(/^.*http(s?):(\/\/)?/,"");return b+"//"+c+"/"+a+".js";};Z.prototype.load=function(a){a(this.f,this.s);};Z.prototype.protocol=function(){var a=["http:","https:"],b=a[0];if(this.k&&this.k.location&&this.k.location.protocol){var c=0;for(c=0;c<a.length;c++){if(this.k.location.protocol===a[c])return this.k.location.protocol;}}return b;};window.WebFont.q("monotype",function(a){var b=new z(navigator.userAgent,document).parse();return new Z(window,b,new o(document,b),document,a);});function $(a,b,c){this.m=a;this.a=b;this.d=c;this.f=[];this.s={};}$.prototype.C=function(a){var b="https:"==window.location.protocol?"https:":"http:";return(this.d.api||b+"//use.typekit.com")+"/"+a+".js";};$.prototype.z=function(a,b){var c=this.d.id,d=this.d,e=this;if(c){this.m.__webfonttypekitmodule__||(this.m.__webfonttypekitmodule__={});this.m.__webfonttypekitmodule__[c]=function(f){f(a,d,function(g,h,l){e.f=h;e.s=l;b(g);});};r(this.a,"head",u(this.a,this.C(c)));}else b(true);};$.prototype.load=function(a){a(this.f,this.s);};window.WebFont.q("typekit",function(a){var b=new z(navigator.userAgent,document).parse();return new $(window,new o(document,b),a);});window.WebFontConfig&&window.WebFont.load(window.WebFontConfig);})(this,document);},{}],9:[function(require,module,exports){// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*-
// vim:set ft=javascript ts=2 sw=2 sts=2 cindent:
var Ajax=function($,window,undefined){var Ajax=function Ajax(dispatcher){var that=this;var pending=0;var count=0;var pendingList={};// merge data will get merged into the response data
// before calling the callback
var ajaxCall=function ajaxCall(data,callback,merge){merge=merge||{};dispatcher.post('spin');pending++;var id=count++;// special value: `merge.keep = true` prevents obsolescence
pendingList[id]=merge.keep||false;delete merge.keep;// If no protocol version is explicitly set, set it to current
if(data['protocol']===undefined){// TODO: Extract the protocol version somewhere global
data['protocol']=1;}//var url = "test-json/";
var url="test-json-simple/";var method="GET";switch(data.action){case"whoami":url+="user.json";break;case"getDocument":url+="document.json";break;case"loadConf":url+="config.json";break;case"getCollectionInformation":url+="collection.json";break;case"login":url+="login.json";break;case"createArc":url+="addRelation.json";//TODO method = "POST";
break;case"arcOpenDialog":url+="addRelation2.json";break;case"createSpan":url+="createToken.json";//TODO method = "POST";
break;default:url+="empty.json";}$.ajax({//Removed by Renaud on 2016-03-10
/*url: 'ajax.cgi',
           data: data,
           type: 'POST',*///
data:data,url:url,type:method,success:function success(response){pending--;// If no exception is set, verify the server results
if(response.exception==undefined&&response.action!==data.action){console.error('Action '+data.action+' returned the results of action '+response.action);response.exception=true;dispatcher.post('messages',[[['Protocol error: Action'+data.action+' returned the results of action '+response.action+' maybe the server is unable to run, please run tools/troubleshooting.sh from your installation to diagnose it','error',-1]]]);}// If the request is obsolete, do nothing; if not...
if(pendingList.hasOwnProperty(id)){dispatcher.post('messages',[response.messages]);if(response.exception=='configurationError'||response.exception=='protocolVersionMismatch'){// this is a no-rescue critical failure.
// Stop *everything*.
pendingList={};dispatcher.post('screamingHalt');// If we had a protocol mismatch, prompt the user for a reload
if(response.exception=='protocolVersionMismatch'){if(confirm('The server is running a different version '+'from brat than your client, possibly due to a '+'server upgrade. Would you like to reload the '+'current page to update your client to the latest '+'version?')){window.location.reload(true);}else{dispatcher.post('messages',[[['Fatal Error: Protocol '+'version mismatch, please contact the administrator','error',-1]]]);}}return;}delete pendingList[id];// if .exception is just Boolean true, do not process
// the callback; if it is anything else, the
// callback is responsible for handling it
if(response.exception==true){$('#waiter').dialog('close');}else if(callback){$.extend(response,merge);dispatcher.post(0,callback,[response]);}}dispatcher.post('unspin');},error:function error(response,textStatus,errorThrown){pending--;dispatcher.post('unspin');$('#waiter').dialog('close');dispatcher.post('messages',[[['Error: Action'+data.action+' failed on error '+response.statusText,'error']]]);console.error(textStatus+':',errorThrown,response);}});return id;};var isReloadOkay=function isReloadOkay(){// do not reload while data is pending
return pending==0;};var makeObsolete=function makeObsolete(all){if(all){pendingList={};}else{$.each(pendingList,function(id,keep){if(!keep)delete pendingList[id];});}};dispatcher.on('isReloadOkay',isReloadOkay).on('makeAjaxObsolete',makeObsolete).on('ajax',ajaxCall);};return Ajax;}(jQuery,window);module.exports=Ajax;},{}],10:[function(require,module,exports){// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*-
// vim:set ft=javascript ts=2 sw=2 sts=2 cindent:
var AnnotatorUI=function($,window,undefined){var AnnotatorUI=function AnnotatorUI(dispatcher,svg){var _initForm;var that=this;var arcDragOrigin=null;var arcDragOriginBox=null;var arcDragOriginGroup=null;var arcDragArc=null;var arcDragJustStarted=false;var sourceData=null;var data=null;var searchConfig=null;var spanOptions=null;var rapidSpanOptions=null;var arcOptions=null;var spanKeymap=null;var keymap=null;var coll=null;var doc=null;var reselectedSpan=null;var selectedFragment=null;var editedSpan=null;var editedFragment=null;var repeatingArcTypes=[];var spanTypes=null;var entityAttributeTypes=null;var eventAttributeTypes=null;var allAttributeTypes=null;// TODO: temp workaround, remove
var relationTypesHash=null;var showValidAttributes;// callback function
var showValidNormalizations;// callback function
var dragStartedAt=null;var selRect=null;var lastStartRec=null;var lastEndRec=null;var draggedArcHeight=30;var spanTypesToShowBeforeCollapse=30;var maxNormSearchHistory=10;// TODO: this is an ugly hack, remove (see comment with assignment)
var lastRapidAnnotationEvent=null;// TODO: another avoidable global; try to work without
var rapidAnnotationDialogVisible=false;// amount by which to lighten (adjust "L" in HSL space) span
// colors for type selection box BG display. 0=no lightening,
// 1=white BG (no color)
var spanBoxTextBgColorLighten=0.4;// for double-click selection simulation hack
var lastDoubleClickedChunkId=null;// for normalization: URLs bases by norm DB name
var normDbUrlByDbName={};var normDbUrlBaseByDbName={};// for normalization: appropriate DBs per type
var normDbsByType={};// for normalization
var oldSpanNormIdValue='';var lastNormSearches=[];that.user=null;var svgElement=$(svg._svg);var svgId=svgElement.parent().attr('id');var stripNumericSuffix=function stripNumericSuffix(s){// utility function, originally for stripping numerix suffixes
// from arc types (e.g. "Theme2" -> "Theme"). For values
// without suffixes (including non-strings), returns given value.
if(typeof s!="string"){return s;// can't strip
}var m=s.match(/^(.*?)(\d*)$/);return m[1];// always matches
};var hideForm=function hideForm(){keymap=null;rapidAnnotationDialogVisible=false;};var clearSelection=function clearSelection(){window.getSelection().removeAllRanges();if(selRect!=null){for(var s=0;s!=selRect.length;s++){selRect[s].parentNode.removeChild(selRect[s]);}selRect=null;lastStartRec=null;lastEndRec=null;}};var makeSelRect=function makeSelRect(rx,ry,rw,rh,col){var selRect=document.createElementNS("http://www.w3.org/2000/svg","rect");selRect.setAttributeNS(null,"width",rw);selRect.setAttributeNS(null,"height",rh);selRect.setAttributeNS(null,"x",rx);selRect.setAttributeNS(null,"y",ry);selRect.setAttributeNS(null,"fill",col==undefined?"lightblue":col);return selRect;};var onKeyDown=function onKeyDown(evt){var code=evt.which;if(code===$.ui.keyCode.ESCAPE){stopArcDrag();if(reselectedSpan){$(reselectedSpan.rect).removeClass('reselect');reselectedSpan=null;svgElement.removeClass('reselect');}return;}// in rapid annotation mode, prioritize the keys 0..9 for the
// ordered choices in the quick annotation dialog.
if(Configuration.rapidModeOn&&rapidAnnotationDialogVisible&&"0".charCodeAt()<=code&&code<="9".charCodeAt()){var idx=String.fromCharCode(code);var $input=$('#rapid_span_'+idx);if($input.length){$input.click();}}if(!keymap)return;// disable shortcuts when working with elements that you could
// conceivably type in
var target=evt.target;var nodeName=target.nodeName.toLowerCase();var nodeType=target.type&&target.type.toLowerCase();if(nodeName=='input'&&(nodeType=='text'||nodeType=='password'))return;if(nodeName=='textarea'||nodeName=='select')return;var prefix='';if(evt.altKey){prefix="A-";}if(evt.ctrlKey){prefix="C-";}if(evt.shiftKey){prefix="S-";}var binding=keymap[prefix+code];if(!binding)binding=keymap[prefix+String.fromCharCode(code)];if(binding){var boundInput=$('#'+binding)[0];if(boundInput&&!boundInput.disabled){boundInput.click();evt.preventDefault();return false;}}};var onDblClick=function onDblClick(evt){// must be logged in
//Removed by Renaud on 2016-03-10
//if (that.user === null) return;
// must not be reselecting a span or an arc
if(reselectedSpan||arcDragOrigin)return;var target=$(evt.target);var id;// do we edit an arc?
if(id=target.attr('data-arc-role')){// TODO
clearSelection();var originSpanId=target.attr('data-arc-origin');var targetSpanId=target.attr('data-arc-target');var type=target.attr('data-arc-role');var originSpan=data.spans[originSpanId];var targetSpan=data.spans[targetSpanId];arcOptions={action:'createArc',origin:originSpanId,target:targetSpanId,old_target:targetSpanId,type:type,old_type:type,collection:coll,'document':doc};var eventDescId=target.attr('data-arc-ed');if(eventDescId){var eventDesc=data.eventDescs[eventDescId];if(eventDesc.equiv){arcOptions['left']=eventDesc.leftSpans.join(',');arcOptions['right']=eventDesc.rightSpans.join(',');}}$('#arc_origin').text(Util.spanDisplayForm(spanTypes,originSpan.type)+' ("'+originSpan.text+'")');$('#arc_target').text(Util.spanDisplayForm(spanTypes,targetSpan.type)+' ("'+targetSpan.text+'")');var arcId=eventDescId||[originSpanId,type,targetSpanId];fillArcTypesAndDisplayForm(evt,originSpan.type,targetSpan.type,type,arcId);// for precise timing, log dialog display to user.
dispatcher.post('logAction',['arcEditSelected']);// if not an arc, then do we edit a span?
}else if(id=target.attr('data-span-id')){clearSelection();editedSpan=data.spans[id];editedFragment=target.attr('data-fragment-id');var offsets=[];$.each(editedSpan.fragments,function(fragmentNo,fragment){offsets.push([fragment.from,fragment.to]);});spanOptions={action:'createSpan',offsets:offsets,type:editedSpan.type,id:id};fillSpanTypesAndDisplayForm(evt,editedSpan.text,editedSpan);// for precise timing, log annotation display to user.
dispatcher.post('logAction',['spanEditSelected']);}// if not an arc or a span, is this a double-click on text?
else if(id=target.attr('data-chunk-id')){// remember what was clicked (this is in preparation for
// simulating double-click selection on browsers that do
// not support it.
lastDoubleClickedChunkId=id;}};var startArcDrag=function startArcDrag(originId){clearSelection();svgElement.addClass('unselectable');svgPosition=svgElement.offset();arcDragOrigin=originId;arcDragArc=svg.path(svg.createPath(),{markerEnd:'url(#drag_arrow)','class':'drag_stroke',fill:'none'});arcDragOriginGroup=$(data.spans[arcDragOrigin].group);arcDragOriginGroup.addClass('highlight');arcDragOriginBox=Util.realBBox(data.spans[arcDragOrigin].headFragment);arcDragOriginBox.center=arcDragOriginBox.x+arcDragOriginBox.width/2;arcDragJustStarted=true;};var getValidArcTypesForDrag=function getValidArcTypesForDrag(targetId,targetType){var arcType=stripNumericSuffix(arcOptions&&arcOptions.type);if(!arcDragOrigin||targetId==arcDragOrigin)return null;var originType=data.spans[arcDragOrigin].type;var spanType=spanTypes[originType];var result=[];if(spanType&&spanType.arcs){$.each(spanType.arcs,function(arcNo,arc){if(arcType&&arcType!=arc.type)return;if($.inArray(targetType,arc.targets)!=-1){result.push(arc.type);}});}return result;};var onMouseDown=function onMouseDown(evt){dragStartedAt=evt;// XXX do we really need the whole evt?
//Removed by Renaud on 2016-03-10
//if (!that.user || arcDragOrigin) return;
if(arcDragOrigin)return;var target=$(evt.target);var id;// is it arc drag start?
if(id=target.attr('data-span-id')){arcOptions=null;startArcDrag(id);return false;}};var onMouseMove=function onMouseMove(evt){if(arcDragOrigin){if(arcDragJustStarted){// show the possible targets
var span=data.spans[arcDragOrigin]||{};var spanDesc=spanTypes[span.type]||{};// separate out possible numeric suffix from type for highight
// (instead of e.g. "Theme3", need to look for "Theme")
var noNumArcType=stripNumericSuffix(arcOptions&&arcOptions.type);// var targetClasses = [];
var $targets=$();$.each(spanDesc.arcs||[],function(possibleArcNo,possibleArc){if(arcOptions&&possibleArc.type==noNumArcType||!(arcOptions&&arcOptions.old_target)){$.each(possibleArc.targets||[],function(possibleTargetNo,possibleTarget){// speedup for #642: relevant browsers should support
// this function: http://www.quirksmode.org/dom/w3c_core.html#t11
// so we get off jQuery and get down to the metal:
// targetClasses.push('.span_' + possibleTarget);
$targets=$targets.add(svgElement[0].getElementsByClassName('span_'+possibleTarget));});}});//$(targetClasses.join(',')).not('[data-span-id="' + arcDragOrigin + '"]').addClass('reselectTarget');
//TODO next one should be working but doesn't. Renaud on 2016-03-10
$targets.not('[data-span-id="'+arcDragOrigin+'"]').addClass('reselectTarget');}clearSelection();var mx=evt.pageX-svgPosition.left;var my=evt.pageY-svgPosition.top+5;// TODO FIXME why +5?!?
var y=Math.min(arcDragOriginBox.y,my)-draggedArcHeight;var dx=(arcDragOriginBox.center-mx)/4;var path=svg.createPath().move(arcDragOriginBox.center,arcDragOriginBox.y).curveC(arcDragOriginBox.center-dx,y,mx+dx,y,mx,my);arcDragArc.setAttribute('d',path.path());}else{// A. Scerri FireFox chunk
// if not, then is it span selection? (ctrl key cancels)
var sel=window.getSelection();var chunkIndexFrom=sel.anchorNode&&$(sel.anchorNode.parentNode).attr('data-chunk-id');var chunkIndexTo=sel.focusNode&&$(sel.focusNode.parentNode).attr('data-chunk-id');// fallback for firefox (at least):
// it's unclear why, but for firefox the anchor and focus
// node parents are always undefined, the the anchor and
// focus nodes themselves do (often) have the necessary
// chunk ID. However, anchor offsets are almost always
// wrong, so we'll just make a guess at what the user might
// be interested in tagging instead of using what's given.
var anchorOffset=null;var focusOffset=null;if(chunkIndexFrom===undefined&&chunkIndexTo===undefined&&$(sel.anchorNode).attr('data-chunk-id')&&$(sel.focusNode).attr('data-chunk-id')){// Lets take the actual selection range and work with that
// Note for visual line up and more accurate positions a vertical offset of 8 and horizontal of 2 has been used!
var range=sel.getRangeAt(0);var svgOffset=$(svg._svg).offset();var flip=false;var tries=0;// First try and match the start offset with a position, if not try it against the other end
while(tries<2){var sp=svg._svg.createSVGPoint();sp.x=(flip?evt.pageX:dragStartedAt.pageX)-svgOffset.left;sp.y=(flip?evt.pageY:dragStartedAt.pageY)-(svgOffset.top+8);var startsAt=range.startContainer;anchorOffset=startsAt.getCharNumAtPosition(sp);chunkIndexFrom=startsAt&&$(startsAt).attr('data-chunk-id');if(anchorOffset!=-1){break;}flip=true;tries++;}// Now grab the end offset
sp.x=(flip?dragStartedAt.pageX:evt.pageX)-svgOffset.left;sp.y=(flip?dragStartedAt.pageY:evt.pageY)-(svgOffset.top+8);var endsAt=range.endContainer;focusOffset=endsAt.getCharNumAtPosition(sp);// If we cannot get a start and end offset stop here
if(anchorOffset==-1||focusOffset==-1){return;}// If we are in the same container it does the selection back to front when dragged right to left, across different containers the start is the start and the end if the end!
if(range.startContainer==range.endContainer&&anchorOffset>focusOffset){var t=anchorOffset;anchorOffset=focusOffset;focusOffset=t;flip=false;}chunkIndexTo=endsAt&&$(endsAt).attr('data-chunk-id');// Now take the start and end character rectangles
startRec=startsAt.getExtentOfChar(anchorOffset);startRec.y+=2;endRec=endsAt.getExtentOfChar(focusOffset);endRec.y+=2;// If nothing has changed then stop here
if(lastStartRec!=null&&lastStartRec.x==startRec.x&&lastStartRec.y==startRec.y&&lastEndRec!=null&&lastEndRec.x==endRec.x&&lastEndRec.y==endRec.y){return;}if(selRect==null){var rx=startRec.x;var ry=startRec.y;var rw=endRec.x+endRec.width-startRec.x;if(rw<0){rx+=rw;rw=-rw;}var rh=Math.max(startRec.height,endRec.height);selRect=new Array();var activeSelRect=makeSelRect(rx,ry,rw,rh);selRect.push(activeSelRect);startsAt.parentNode.parentNode.parentNode.insertBefore(activeSelRect,startsAt.parentNode.parentNode);}else{if(startRec.x!=lastStartRec.x&&endRec.x!=lastEndRec.x&&(startRec.y!=lastStartRec.y||endRec.y!=lastEndRec.y)){if(startRec.y<lastStartRec.y){selRect[0].setAttributeNS(null,"width",lastStartRec.width);lastEndRec=lastStartRec;}else if(endRec.y>lastEndRec.y){selRect[selRect.length-1].setAttributeNS(null,"x",parseFloat(selRect[selRect.length-1].getAttributeNS(null,"x"))+parseFloat(selRect[selRect.length-1].getAttributeNS(null,"width"))-lastEndRec.width);selRect[selRect.length-1].setAttributeNS(null,"width",0);lastStartRec=lastEndRec;}}// Start has moved
var flip=!(startRec.x==lastStartRec.x&&startRec.y==lastStartRec.y);// If the height of the start or end changed we need to check whether
// to remove multi line highlights no longer needed if the user went back towards their start line
// and whether to create new ones if we moved to a newline
if(endRec.y!=lastEndRec.y||startRec.y!=lastStartRec.y){// First check if we have to remove the first highlights because we are moving towards the end on a different line
var ss=0;for(;ss!=selRect.length;ss++){if(startRec.y<=parseFloat(selRect[ss].getAttributeNS(null,"y"))){break;}}// Next check for any end highlights if we are moving towards the start on a different line
var es=selRect.length-1;for(;es!=-1;es--){if(endRec.y>=parseFloat(selRect[es].getAttributeNS(null,"y"))){break;}}// TODO put this in loops above, for efficiency the array slicing could be done separate still in single call
var trunc=false;if(ss<selRect.length){for(var s2=0;s2!=ss;s2++){selRect[s2].parentNode.removeChild(selRect[s2]);es--;trunc=true;}selRect=selRect.slice(ss);}if(es>-1){for(var s2=selRect.length-1;s2!=es;s2--){selRect[s2].parentNode.removeChild(selRect[s2]);trunc=true;}selRect=selRect.slice(0,es+1);}// If we have truncated the highlights we need to readjust the last one
if(trunc){var activeSelRect=flip?selRect[0]:selRect[selRect.length-1];if(flip){var rw=0;if(startRec.y==endRec.y){rw=endRec.x+endRec.width-startRec.x;}else{rw=parseFloat(activeSelRect.getAttributeNS(null,"x"))+parseFloat(activeSelRect.getAttributeNS(null,"width"))-startRec.x;}activeSelRect.setAttributeNS(null,"x",startRec.x);activeSelRect.setAttributeNS(null,"y",startRec.y);activeSelRect.setAttributeNS(null,"width",rw);}else{var rw=endRec.x+endRec.width-parseFloat(activeSelRect.getAttributeNS(null,"x"));activeSelRect.setAttributeNS(null,"width",rw);}}else{// We didnt truncate anything but we have moved to a new line so we need to create a new highlight
var lastSel=flip?selRect[0]:selRect[selRect.length-1];var startBox=startsAt.parentNode.getBBox();var endBox=endsAt.parentNode.getBBox();if(flip){lastSel.setAttributeNS(null,"width",parseFloat(lastSel.getAttributeNS(null,"x"))+parseFloat(lastSel.getAttributeNS(null,"width"))-endBox.x);lastSel.setAttributeNS(null,"x",endBox.x);}else{lastSel.setAttributeNS(null,"width",startBox.x+startBox.width-parseFloat(lastSel.getAttributeNS(null,"x")));}var rx=0;var ry=0;var rw=0;var rh=0;if(flip){rx=startRec.x;ry=startRec.y;rw=$(svg._svg).width()-startRec.x;rh=startRec.height;}else{rx=endBox.x;ry=endRec.y;rw=endRec.x+endRec.width-endBox.x;rh=endRec.height;}var newRect=makeSelRect(rx,ry,rw,rh);if(flip){selRect.unshift(newRect);}else{selRect.push(newRect);}// Place new highlight in appropriate slot in SVG graph
startsAt.parentNode.parentNode.parentNode.insertBefore(newRect,startsAt.parentNode.parentNode);}}else{// The user simply moved left or right along the same line so just adjust the current highlight
var activeSelRect=flip?selRect[0]:selRect[selRect.length-1];// If the start moved shift the highlight and adjust width
if(flip){var rw=parseFloat(activeSelRect.getAttributeNS(null,"x"))+parseFloat(activeSelRect.getAttributeNS(null,"width"))-startRec.x;activeSelRect.setAttributeNS(null,"x",startRec.x);activeSelRect.setAttributeNS(null,"y",startRec.y);activeSelRect.setAttributeNS(null,"width",rw);}else{// If the end moved then simple change the width
var rw=endRec.x+endRec.width-parseFloat(activeSelRect.getAttributeNS(null,"x"));activeSelRect.setAttributeNS(null,"width",rw);}}}lastStartRec=startRec;lastEndRec=endRec;}}arcDragJustStarted=false;};var adjustToCursor=function adjustToCursor(evt,element,centerX,centerY){var screenHeight=$(window).height()-8;// TODO HACK - no idea why -8 is needed
var screenWidth=$(window).width()-8;var elementHeight=element.height();var elementWidth=element.width();var cssSettings={};var eLeft;var eTop;if(centerX){eLeft=evt.clientX-elementWidth/2;}else{eLeft=evt.clientX;}if(centerY){eTop=evt.clientY-elementHeight/2;}else{eTop=evt.clientY;}// Try to make sure the element doesn't go off-screen.
// If this isn't possible (the element is larger than the screen),
// alight top-left corner of screen and dialog as a compromise.
if(screenWidth>elementWidth){eLeft=Math.min(Math.max(eLeft,0),screenWidth-elementWidth);}else{eLeft=0;}if(screenHeight>elementHeight){eTop=Math.min(Math.max(eTop,0),screenHeight-elementHeight);}else{eTop=0;}element.css({top:eTop,left:eLeft});};var updateCheckbox=function updateCheckbox($input){var $widget=$input.button('widget');var $textspan=$widget.find('.ui-button-text');$textspan.html(($input[0].checked?'&#x2611; ':'&#x2610; ')+$widget.attr('data-bare'));};var fillSpanTypesAndDisplayForm=function fillSpanTypesAndDisplayForm(evt,spanText,span){keymap=spanKeymap;// Figure out whether we should show or hide one of the two
// main halves of the selection frame (entities / events).
// This depends on the type of the current span, if any, and
// the availability of types to select.
var hideFrame;if(span){// existing span; only show relevant half
if(span.generalType=='entity'){hideFrame='event';}else{hideFrame='entity';}spanForm.dialog('option',{title:'Edit Annotation'});}else{// new span; show everything that's available
if($('#event_types').find('input').length==0){hideFrame='event';}else if($('#entity_types').find('input').length==0){hideFrame='entity';}else{hideFrame='none';}spanForm.dialog('option',{title:'New Annotation'});}if(hideFrame=='event'){$('#span_event_section').hide();$('#span_entity_section').show().removeClass('wrapper_half_left').addClass('wrapper_full_width');}else if(hideFrame=='entity'){$('#span_entity_section').hide();$('#span_event_section').show().removeClass('wrapper_half_right').addClass('wrapper_full_width');}else{// show both entity and event halves
$('#span_entity_section').show().removeClass('wrapper_full_width').addClass('wrapper_half_left');$('#span_event_section').show().removeClass('wrapper_full_width').addClass('wrapper_half_right');}// only show "delete" button if there's an existing annotation to delete
if(span){$('#del_span_button').show();}else{$('#del_span_button').hide();}$('#span_selected').text(spanText);var encodedText=encodeURIComponent(spanText);$.each(searchConfig,function(searchNo,search){$('#span_'+search[0]).attr('href',search[1].replace('%s',encodedText));});// enable all inputs by default (see setSpanTypeSelectability)
$('#span_form input:not([unused])').removeAttr('disabled');// close span types if there's over spanTypesToShowBeforeCollapse
if($('#entity_types .item').length>spanTypesToShowBeforeCollapse){$('#entity_types .open').removeClass('open');}if($('#event_types .item').length>spanTypesToShowBeforeCollapse){$('#event_types .open').removeClass('open');}var showAllAttributes=false;if(span){var hash=new URLHash(coll,doc,{focus:[[span.id]]}).getHash();$('#span_highlight_link').attr('href',hash).show();var el=$('#span_'+span.type);if(el.length){el[0].checked=true;}else{$('#span_form input:radio:checked').each(function(radioNo,radio){radio.checked=false;});}// open the span type
$('#span_'+span.type).parents('.collapsible').each(function(){toggleCollapsible($(this).parent().prev(),true);});// count the repeating arc types
var arcTypeCount={};repeatingArcTypes=[];$.each(span.outgoing,function(arcNo,arc){// parse out possible number suffixes to allow e.g. splitting
// on "Theme" for args ("Theme1", "Theme2").
var splitArcType=arc.type.match(/^(.*?)(\d*)$/);var noNumArcType=splitArcType[1];if((arcTypeCount[noNumArcType]=(arcTypeCount[noNumArcType]||0)+1)==2){repeatingArcTypes.push(noNumArcType);}});if(repeatingArcTypes.length){$('#span_form_split').show();}else{$('#span_form_split').hide();}}else{$('#span_highlight_link').hide();var firstRadio=$('#span_form input:radio:not([unused]):first')[0];if(firstRadio){firstRadio.checked=true;}else{dispatcher.post('hideForm');dispatcher.post('messages',[[['No valid span types defined','error']]]);return;}$('#span_form_split').hide();$('#span_notes').val('');showAllAttributes=true;}if(span&&!reselectedSpan){$('#span_form_reselect, #span_form_delete, #span_form_add_fragment').show();keymap[$.ui.keyCode.DELETE]='span_form_delete';keymap[$.ui.keyCode.INSERT]='span_form_reselect';keymap['S-'+$.ui.keyCode.ENTER]='span_form_add_fragment';$('#span_notes').val(span.annotatorNotes||'');}else{$('#span_form_reselect, #span_form_delete, #span_form_add_fragment').hide();keymap[$.ui.keyCode.DELETE]=null;keymap[$.ui.keyCode.INSERT]=null;keymap['S-'+$.ui.keyCode.ENTER]=null;}if(span&&!reselectedSpan&&span.offsets.length>1){$('#span_form_reselect_fragment, #span_form_delete_fragment').show();keymap['S-'+$.ui.keyCode.DELETE]='span_form_delete_fragment';keymap['S-'+$.ui.keyCode.INSERT]='span_form_reselect_fragment';}else{$('#span_form_reselect_fragment, #span_form_delete_fragment').hide();keymap['S-'+$.ui.keyCode.DELETE]=null;keymap['S-'+$.ui.keyCode.INSERT]=null;}// TODO: lots of redundancy in the next two blocks, clean up
if(!span){// no existing annotation, reset attributes
var attrCategoryAndTypes=[['entity',entityAttributeTypes],['event',eventAttributeTypes]];$.each(attrCategoryAndTypes,function(ctNo,ct){var category=ct[0];var attributeTypes=ct[1];$.each(attributeTypes,function(attrNo,attr){$input=$('#'+category+'_attr_'+Util.escapeQuotes(attr.type));if(attr.unused){$input.val('');}else if(attr.bool){$input[0].checked=false;updateCheckbox($input);$input.button('refresh');}else{$input.val('').change();}});});}else if(!reselectedSpan){// existing annotation, fill attribute values from span
var attributeTypes;var category;if(span.generalType=='entity'){attributeTypes=entityAttributeTypes;category='entity';}else if(span.generalType=='trigger'){attributeTypes=eventAttributeTypes;// TODO: unify category/generalType values ('trigger' vs. 'event')
category='event';}else{console.error('Unrecognized generalType:',span.generalType);}$.each(attributeTypes,function(attrNo,attr){$input=$('#'+category+'_attr_'+Util.escapeQuotes(attr.type));var val=span.attributes[attr.type];if(attr.unused){$input.val(val||'');}else if(attr.bool){$input[0].checked=val;updateCheckbox($input);$input.button('refresh');}else{$input.val(val||'').change();}});}var showValidNormalizationsFor=function showValidNormalizationsFor(type){// set DB selector to the first appropriate for the type.
// TODO: actually disable inappropriate ones.
// TODO: support specific IDs, not just DB specifiers
var firstDb=type&&normDbsByType[type]?normDbsByType[type][0]:null;if(firstDb){$('#span_norm_db').val(firstDb);}};showValidNormalizations=function showValidNormalizations(){// set norm DB selector according to the first selected type
var firstSelected=$('#entity_and_event_wrapper input:radio:checked')[0];var selectedType=firstSelected?firstSelected.value:null;showValidNormalizationsFor(selectedType);};// fill normalizations (if any)
if(!reselectedSpan){// clear first
clearNormalizationUI();var $normDb=$('#span_norm_db');var $normId=$('#span_norm_id');var $normText=$('#span_norm_txt');// fill if found (NOTE: only shows last on multiple)
var normFilled=false;$.each(span?span.normalizations:[],function(normNo,norm){var refDb=norm[0],refId=norm[1],refText=norm[2];$normDb.val(refDb);// could the DB selector be set? (i.e. is refDb configured?)
if($normDb.val()==refDb){// DB is OK, set the rest also
$normId.val(refId);oldSpanNormIdValue=refId;$normText.val(refText);// TODO: check if ID is valid
$normId.addClass('valid_value');normFilled=true;}else{// can't set the DB selector; assume DB is not configured,
// warn and leave blank (will remove norm when dialog is OK'd)
dispatcher.post('messages',[[['Warning: '+refDb+' not configured, removing normalization.','warning']]]);}});// if there is no existing normalization, show valid ones
if(!normFilled){showValidNormalizations();}// update links
updateNormalizationRefLink();updateNormalizationDbLink();}var showAttributesFor=function showAttributesFor(attrTypes,category,type){var validAttrs=type?spanTypes[type].attributes:[];var shownCount=0;$.each(attrTypes,function(attrNo,attr){var $input=$('#'+category+'_attr_'+Util.escapeQuotes(attr.type));var showAttr=showAllAttributes||$.inArray(attr.type,validAttrs)!=-1;if(showAttr){$input.button('widget').show();shownCount++;}else{$input.button('widget').hide();}});return shownCount;};showValidAttributes=function showValidAttributes(){var type=$('#span_form input:radio:checked').val();var entityAttrCount=showAttributesFor(entityAttributeTypes,'entity',type);var eventAttrCount=showAttributesFor(eventAttributeTypes,'event',type);showAllAttributes=false;// show attribute frames only if at least one attribute is
// shown, and set size classes appropriately
if(eventAttrCount>0){$('#event_attributes').show();$('#event_attribute_label').show();$('#event_types').removeClass('scroll_wrapper_full').addClass('scroll_wrapper_upper');}else{$('#event_attributes').hide();$('#event_attribute_label').hide();$('#event_types').removeClass('scroll_wrapper_upper').addClass('scroll_wrapper_full');}if(entityAttrCount>0){$('#entity_attributes').show();$('#entity_attribute_label').show();$('#entity_types').removeClass('scroll_wrapper_full').addClass('scroll_wrapper_upper');}else{$('#entity_attributes').hide();$('#entity_attribute_label').hide();$('#entity_types').removeClass('scroll_wrapper_upper').addClass('scroll_wrapper_full');}};showValidAttributes();// TODO XXX: if seemed quite unexpected/unintuitive that the
// form was re-displayed while the document still shows the
// annotation in its old location in the background (check it).
// The fix of skipping confirm is not really good either, though.
if(reselectedSpan){// && !Configuration.confirmModeOn) {
submitReselect();}else{dispatcher.post('showForm',[spanForm,spanOptions]);$('#span_form-ok').focus();adjustToCursor(evt,spanForm.parent());}};var submitReselect=function submitReselect(){$(reselectedSpan.rect).removeClass('reselect');reselectedSpan=null;spanForm.submit();};var rapidFillSpanTypesAndDisplayForm=function rapidFillSpanTypesAndDisplayForm(start,end,text,types){// variant of fillSpanTypesAndDisplayForm for rapid annotation mode
keymap=spanKeymap;$('#rapid_span_selected').text(text);// fill types
var $spanTypeDiv=$('#rapid_span_types_div');// remove previously filled, if any
$spanTypeDiv.empty();$.each(types,function(typeNo,typeAndProb){// TODO: this duplicates a part of addSpanTypesToDivInner, unify
var type=typeAndProb[0];var prob=typeAndProb[1];var $numlabel=$('<span class="accesskey">'+(typeNo+1)+'</span><span>:</span>');var $input=$('<input type="radio" name="rapid_span_type"/>').attr('id','rapid_span_'+(typeNo+1)).attr('value',type);var spanBgColor=spanTypes[type]&&spanTypes[type].bgColor||'#ffffff';spanBgColor=Util.adjustColorLightness(spanBgColor,spanBoxTextBgColorLighten);// use preferred label instead of type name if available
var name=spanTypes[type]&&spanTypes[type].name||type;var $label=$('<label class="span_type_label"/>').attr('for','rapid_span_'+(typeNo+1)).text(name+' ('+(100.0*prob).toFixed(1)+'%)');$label.css('background-color',spanBgColor);// TODO: check for unnecessary extra wrapping here
var $content=$('<div class="item_content"/>').append($numlabel).append($input).append($label);$spanTypeDiv.append($content);// highlight configured hotkey (if any) in text.
// NOTE: this bit doesn't actually set up the hotkey.
var hotkeyType='span_'+type;// TODO: this is clumsy; there should be a better way
var typeHotkey=null;$.each(keymap,function(key,keyType){if(keyType==hotkeyType){typeHotkey=key;return false;}});if(typeHotkey){var name=$label.html();var replace=true;name=name.replace(new RegExp("(&[^;]*?)?("+typeHotkey+")",'gi'),function(all,entity,letter){if(replace&&!entity){replace=false;var hotkey=typeHotkey.toLowerCase()==letter?typeHotkey.toLowerCase():typeHotkey.toUpperCase();return'<span class="accesskey">'+Util.escapeHTML(hotkey)+'</span>';}return all;});$label.html(name);}// Limit the number of suggestions to the number of numeric keys
if(typeNo>=8){return false;}});// fill in some space and the special "Other" option, with key "0" (zero)
$spanTypeDiv.append($('<div class="item_content">&#160;</div>'));// non-breaking space
var $numlabel=$('<span class="accesskey">0</span><span>:</span>');var $input=$('<input type="radio" name="rapid_span_type" id="rapid_span_0" value=""/>');var $label=$('<label class="span_type_label" for="rapid_span_0" style="background-color:lightgray">Other...</label>');var $content=$('<div class="item_content"/>').append($numlabel).append($input).append($label);$spanTypeDiv.append($content);// set up click event handlers
rapidSpanForm.find('#rapid_span_types input:radio').click(rapidSpanFormSubmitRadio);var firstRadio=$('#rapid_span_form input:radio:first')[0];if(firstRadio){firstRadio.checked=true;}else{dispatcher.post('hideForm');dispatcher.post('messages',[[['No valid span types defined','error']]]);return;}dispatcher.post('showForm',[rapidSpanForm]);rapidAnnotationDialogVisible=true;$('#rapid_span_form-ok').focus();// TODO: avoid using global for stored click event
//         adjustToCursor(lastRapidAnnotationEvent, rapidSpanForm.parent(),
//                        true, true);
// TODO: avoid coordinate hack to position roughly at first
// available selection
lastRapidAnnotationEvent.clientX-=55;lastRapidAnnotationEvent.clientY-=115;adjustToCursor(lastRapidAnnotationEvent,rapidSpanForm.parent(),false,false);};var clearSpanNotes=function clearSpanNotes(evt){$('#span_notes').val('');};$('#clear_notes_button').button();$('#clear_notes_button').click(clearSpanNotes);var clearSpanNorm=function clearSpanNorm(evt){clearNormalizationUI();};$('#clear_norm_button').button();$('#clear_norm_button').click(clearSpanNorm);// invoked on response to ajax request for id lookup
var setSpanNormText=function setSpanNormText(response){if(response.exception){// TODO: better response to failure
dispatcher.post('messages',[[['Lookup error','warning',-1]]]);return false;}// set input style according to whether we have a valid value
var $idinput=$('#span_norm_id');// TODO: make sure the key echo in the response matches the
// current value of the $idinput
$idinput.removeClass('valid_value').removeClass('invalid_value');if(response.value===null){$idinput.addClass('invalid_value');hideNormalizationRefLink();}else{$idinput.addClass('valid_value');updateNormalizationRefLink();}$('#span_norm_txt').val(response.value);};// on any change to the normalization DB, clear everything and
// update link
var spanNormDbUpdate=function spanNormDbUpdate(evt){clearNormalizationUI();updateNormalizationDbLink();};$('#span_norm_db').change(spanNormDbUpdate);// on any change to the normalization ID, update the text of the
// reference
var spanNormIdUpdate=function spanNormIdUpdate(evt){var key=$(this).val();var db=$('#span_norm_db').val();if(key!=oldSpanNormIdValue){if(key.match(/^\s*$/)){// don't query empties, just clear instead
clearNormalizationUI();}else{dispatcher.post('ajax',[{action:'normGetName',database:db,key:key,collection:coll},'normGetNameResult']);}oldSpanNormIdValue=key;}};// see http://stackoverflow.com/questions/1948332/detect-all-changes-to-a-input-type-text-immediately-using-jquery
$('#span_norm_id').bind('propertychange keyup input paste',spanNormIdUpdate);// nice-looking select for normalization
$('#span_norm_db').addClass('ui-widget ui-state-default ui-button-text');var normSearchDialog=$('#norm_search_dialog');initForm(normSearchDialog,(_initForm={width:800},_defineProperty(_initForm,"width",600),_defineProperty(_initForm,"resizable",true),_defineProperty(_initForm,"alsoResize",'#norm_search_result_select'),_defineProperty(_initForm,"open",function open(evt){keymap={};}),_defineProperty(_initForm,"close",function close(evt){// assume that we always want to return to the span dialog
// on normalization dialog close
dispatcher.post('showForm',[spanForm]);}),_initForm));// BRAT STAND ALONE LIBRARY BEGIN
/*
      $('#norm_search_query').autocomplete({
        source: function(request, callback) {
          var query = $.ui.autocomplete.escapeRegex(request.term);
          var pattern = new RegExp('\\b' + query, 'i');
          callback($.grep(lastNormSearches, function(search) {
            return pattern.test(search.value) || pattern.test(search.id);
          }));
        },
        minLength: 0,
        select: function(evt, ui) {
          evt.stopPropagation();
          normSubmit(ui.item.id, ui.item.value);
        },
        focus: function(evt, ui) {
          // do nothing
        },
      }).data('autocomplete')._renderItem = function($ul, item) {
        return $('<li></li>').
          data('item.autocomplete', item).
          append('<a>' + Util.escapeHTML(item.value) + '<div class="autocomplete-id">' + Util.escapeHTML(item.id) + "</div></a>").
          appendTo($ul);
      };
*/// BRAT STAND ALONE LIBRARY END
var normSubmit=function normSubmit(selectedId,selectedTxt){// we got a value; act if it was a submit
$('#span_norm_id').val(selectedId);// don't forget to update this reference value
oldSpanNormIdValue=selectedId;$('#span_norm_txt').val(selectedTxt);updateNormalizationRefLink();// update history
var nextLastNormSearches=[{value:selectedTxt,id:selectedId}];$.each(lastNormSearches,function(searchNo,search){if(search.id!=selectedId||search.value!=selectedTxt){nextLastNormSearches.push(search);}});lastNormSearches=nextLastNormSearches;lastNormSearches.slice(0,maxNormSearchHistory);// Switch dialogs. NOTE: assuming we closed the spanForm when
// bringing up the normSearchDialog.
normSearchDialog.dialog('close');};var normSearchSubmit=function normSearchSubmit(evt){if(normSearchSubmittable){var selectedId=$('#norm_search_id').val();var selectedTxt=$('#norm_search_query').val();normSubmit(selectedId,selectedTxt);}else{performNormSearch();}return false;};var normSearchSubmittable=false;var setNormSearchSubmit=function setNormSearchSubmit(enable){$('#norm_search_dialog-ok').button(enable?'enable':'disable');normSearchSubmittable=enable;};normSearchDialog.submit(normSearchSubmit);var chooseNormId=function chooseNormId(evt){var $element=$(evt.target).closest('tr');$('#norm_search_result_select tr').removeClass('selected');$element.addClass('selected');$('#norm_search_query').val($element.attr('data-txt'));$('#norm_search_id').val($element.attr('data-id'));setNormSearchSubmit(true);};var chooseNormIdAndSubmit=function chooseNormIdAndSubmit(evt){chooseNormId(evt);normSearchSubmit(evt);};var setSpanNormSearchResults=function setSpanNormSearchResults(response){if(response.exception){// TODO: better response to failure
dispatcher.post('messages',[[['Lookup error','warning',-1]]]);return false;}if(response.items.length==0){// no results
$('#norm_search_result_select thead').empty();$('#norm_search_result_select tbody').empty();dispatcher.post('messages',[[['No matches to search.','comment']]]);return false;}// TODO: avoid code duplication with showFileBrowser()
var html=['<tr>'];$.each(response.header,function(headNo,head){html.push('<th>'+Util.escapeHTML(head[0])+'</th>');});html.push('</tr>');$('#norm_search_result_select thead').html(html.join(''));html=[];var len=response.header.length;$.each(response.items,function(itemNo,item){// NOTE: assuming ID is always the first datum in the item
// and that the preferred text is always the second
// TODO: Util.escapeQuotes would be expected to be
// sufficient here, but that appears to give "DOM Exception
// 11" in cases (try e.g. $x.html('<p a="A&B"/>'). Why? Is
// this workaround OK?
html.push('<tr'+' data-id="'+Util.escapeHTMLandQuotes(item[0])+'"'+' data-txt="'+Util.escapeHTMLandQuotes(item[1])+'"'+'>');for(var i=0;i<len;i++){html.push('<td>'+Util.escapeHTML(item[i])+'</td>');}html.push('</tr>');});$('#norm_search_result_select tbody').html(html.join(''));$('#norm_search_result_select tbody').find('tr').click(chooseNormId).dblclick(chooseNormIdAndSubmit);// TODO: sorting on click on header (see showFileBrowser())
};var performNormSearch=function performNormSearch(){var val=$('#norm_search_query').val();var db=$('#span_norm_db').val();dispatcher.post('ajax',[{action:'normSearch',database:db,name:val,collection:coll},'normSearchResult']);};$('#norm_search_button').click(performNormSearch);$('#norm_search_query').focus(function(){setNormSearchSubmit(false);});var showNormSearchDialog=function showNormSearchDialog(){// if we already have non-empty ID and normalized string,
// use these as default; otherwise take default search string
// from annotated span and clear ID entry
if(!$('#span_norm_id').val().match(/^\s*$/)&&!$('#span_norm_txt').val().match(/^\s*$/)){$('#norm_search_id').val($('#span_norm_id').val());$('#norm_search_query').val($('#span_norm_txt').val());}else{$('#norm_search_id').val('');$('#norm_search_query').val($('#span_selected').text());}// blank the table
$('#norm_search_result_select thead').empty();$('#norm_search_result_select tbody').empty();// TODO: support for two (or more) dialogs open at the same time
// so we don't need to hide this before showing normSearchDialog
dispatcher.post('hideForm');$('#norm_search_button').val('Search '+$('#span_norm_db').val());setNormSearchSubmit(false);dispatcher.post('showForm',[normSearchDialog]);$('#norm_search_query').focus().select();};$('#span_norm_txt').click(showNormSearchDialog);$('#norm_search_button').button();var arcFormSubmitRadio=function arcFormSubmitRadio(evt){// TODO: check for confirm_mode?
arcFormSubmit(evt,$(evt.target));};var arcFormSubmit=function arcFormSubmit(evt,typeRadio){typeRadio=typeRadio||$('#arc_form input:radio:checked');var type=typeRadio.val();dispatcher.post('hideForm',[arcForm]);arcOptions.type=type;arcOptions.comment=$('#arc_notes').val();dispatcher.post('ajax',[arcOptions,'edited']);return false;};var fillArcTypesAndDisplayForm=function fillArcTypesAndDisplayForm(evt,originType,targetType,arcType,arcId){var noArcs=true;keymap={};// separate out possible numeric suffix from type
var noNumArcType;if(arcType){var splitType=arcType.match(/^(.*?)(\d*)$/);noNumArcType=splitType[1];}var isEquiv=relationTypesHash&&relationTypesHash[noNumArcType]&&relationTypesHash[noNumArcType].properties&&relationTypesHash[noNumArcType].properties.symmetric&&relationTypesHash[noNumArcType].properties.transitive;var $scroller=$();if(spanTypes[originType]){var arcTypes=spanTypes[originType].arcs;$scroller=$('#arc_roles .scroller').empty();// lay them out into the form
$.each(arcTypes||[],function(arcTypeNo,arcDesc){if(arcDesc.targets&&arcDesc.targets.indexOf(targetType)!=-1){var arcTypeName=arcDesc.type;var isThisEquiv=relationTypesHash&&relationTypesHash[arcTypeName]&&relationTypesHash[arcTypeName].properties&&relationTypesHash[arcTypeName].properties.symmetric&&relationTypesHash[arcTypeName].properties.transitive;// do not allow equiv<->non-equiv change options
if(arcType&&isEquiv!=isThisEquiv)return;var displayName=arcDesc.labels&&arcDesc.labels[0]||arcTypeName;var $checkbox=$('<input id="arc_'+arcTypeName+'" type="radio" name="arc_type" value="'+arcTypeName+'"/>');var $label=$('<label class="arc_type_label" for="arc_'+arcTypeName+'"/>').text(displayName);var $div=$('<div/>').append($checkbox).append($label);$scroller.append($div);if(arcDesc.hotkey){keymap[arcDesc.hotkey]='#arc_'+arcTypeName;var name=$label.html();var replace=true;name=name.replace(new RegExp("(&[^;]*?)?("+arcDesc.hotkey+")",'gi'),function(all,entity,letter){if(replace&&!entity){replace=false;var hotkey=arcDesc.hotkey.toLowerCase()==letter?arcDesc.hotkey.toLowerCase():arcDesc.hotkey.toUpperCase();return'<span class="accesskey">'+Util.escapeHTML(hotkey)+'</span>';}return all;});$label.html(name);}noArcs=false;}});}if(noArcs){if(arcId){// let the user delete or whatever, even on bad config
// (note that what's shown to the user is w/o possible num suffix)
var $checkbox=$('<input id="arc_'+arcType+'" type="hidden" name="arc_type" value="'+noNumArcType+'"/>');$scroller.append($checkbox);}else{// can't make a new arc
dispatcher.post('messages',[[["No choices for "+Util.spanDisplayForm(spanTypes,originType)+" -> "+Util.spanDisplayForm(spanTypes,targetType),'warning']]]);return;}}var reversalPossible=false;if(arcId){// something was selected
var focus=arcId instanceof Array?arcId:[arcId];var hash=new URLHash(coll,doc,{focus:[focus]}).getHash();$('#arc_highlight_link').attr('href',hash).show();// TODO incorrect
var el=$('#arc_'+arcType)[0];if(el){el.checked=true;}else{// try w/o numeric suffix
el=$('#arc_'+noNumArcType)[0];if(el){el.checked=true;}}$('#arc_form_reselect, #arc_form_delete').show();keymap[$.ui.keyCode.DELETE]='arc_form_delete';keymap[$.ui.keyCode.INSERT]='arc_form_reselect';var backTargetType=spanTypes[targetType];if(backTargetType){$.each(backTargetType.arcs||[],function(backArcTypeNo,backArcDesc){if($.inArray(originType,backArcDesc.targets||[])!=-1){reversalPossible=true;return false;// terminate the loop
}});}arcForm.dialog('option',{title:'Edit Annotation'});}else{// new arc
$('#arc_highlight_link').hide();el=$('#arc_form input:radio:first')[0];if(el){el.checked=true;}$('#arc_form_reselect, #arc_form_delete, #arc_form_reverse').hide();arcForm.dialog('option',{title:'New Annotation'});}if(reversalPossible){$('#arc_form_reverse').show();keymap['S-'+$.ui.keyCode.INSERT]='arc_form_reverse';}else{$('#arc_form_reverse').hide();}if(!Configuration.confirmModeOn){arcForm.find('#arc_roles input:radio').click(arcFormSubmitRadio);}var arcAnnotatorNotes;var isBinaryRelation=arcId&&!(arcId instanceof Array);if(isBinaryRelation){// only for relation arcs
var ed=data.eventDescs[arcId];arcAnnotatorNotes=ed&&ed.annotatorNotes;}if(arcAnnotatorNotes){$('#arc_notes').val(arcAnnotatorNotes);}else{$('#arc_notes').val('');}// disable notes for arc types that don't support storage (#945)
if(!isBinaryRelation||isEquiv){// disable the actual input
$('#arc_notes').attr('disabled','disabled');// add to fieldset for style
$('#arc_notes_fieldset').attr('disabled','disabled');}else{$('#arc_notes').removeAttr('disabled');$('#arc_notes_fieldset').removeAttr('disabled');}dispatcher.post('showForm',[arcForm]);$('#arc_form-ok').focus();adjustToCursor(evt,arcForm.parent());};var reverseArc=function reverseArc(evt){var eventDataId=$(evt.target).attr('data-arc-ed');dispatcher.post('hideForm');arcOptions.action='reverseArc';delete arcOptions.old_target;delete arcOptions.old_type;dispatcher.post('ajax',[arcOptions,'edited']);};var deleteArc=function deleteArc(evt){if(Configuration.confirmModeOn&&!confirm("Are you sure you want to delete this annotation?")){return;}var eventDataId=$(evt.target).attr('data-arc-ed');dispatcher.post('hideForm');arcOptions.action='deleteArc';dispatcher.post('ajax',[arcOptions,'edited']);};var reselectArc=function reselectArc(evt){dispatcher.post('hideForm');svgElement.addClass('reselect');$('g[data-from="'+arcOptions.origin+'"][data-to="'+arcOptions.target+'"]').addClass('reselect');startArcDrag(arcOptions.origin);};var arcForm=$('#arc_form');dispatcher.post('initForm',[arcForm,{width:500,buttons:[{id:'arc_form_reverse',text:"Reverse",click:reverseArc},{id:'arc_form_delete',text:"Delete",click:deleteArc},{id:'arc_form_reselect',text:'Reselect',click:reselectArc}],alsoResize:'#arc_roles',close:function close(evt){keymap=null;}}]);arcForm.submit(arcFormSubmit);// set button tooltips (@amadanmath: can this be done in init?)
$('#arc_form_reselect').attr('title','Re-select the annotation this connects into.');$('#arc_form_delete').attr('title','Delete this annotation.');var stopArcDrag=function stopArcDrag(target){if(arcDragOrigin){if(!target){target=$('.badTarget');}target.removeClass('badTarget');arcDragOriginGroup.removeClass('highlight');if(target){target.parent().removeClass('highlight');}if(arcDragArc){svg.remove(arcDragArc);arcDrag=null;}arcDragOrigin=null;if(arcOptions){$('g[data-from="'+arcOptions.origin+'"][data-to="'+arcOptions.target+'"]').removeClass('reselect');}svgElement.removeClass('reselect');}svgElement.removeClass('unselectable');$('.reselectTarget').removeClass('reselectTarget');};var onMouseUp=function onMouseUp(evt){//Removed by Renaud on 2016-03-10
//if (that.user === null) return;
var target=$(evt.target);// three things that are clickable in SVG
var targetSpanId=target.data('span-id');var targetChunkId=target.data('chunk-id');var targetArcRole=target.data('arc-role');if(!(targetSpanId!==undefined||targetChunkId!==undefined||targetArcRole!==undefined)){// misclick
clearSelection();stopArcDrag(target);return;}// is it arc drag end?
if(arcDragOrigin){var origin=arcDragOrigin;var targetValid=target.hasClass('reselectTarget');stopArcDrag(target);if((id=target.attr('data-span-id'))&&origin!=id&&targetValid){var originSpan=data.spans[origin];var targetSpan=data.spans[id];if(arcOptions&&arcOptions.old_target){arcOptions.target=targetSpan.id;dispatcher.post('ajax',[arcOptions,'edited']);}else{arcOptions={action:'createArc',origin:originSpan.id,target:targetSpan.id,collection:coll,'document':doc};$('#arc_origin').text(Util.spanDisplayForm(spanTypes,originSpan.type)+' ("'+originSpan.text+'")');$('#arc_target').text(Util.spanDisplayForm(spanTypes,targetSpan.type)+' ("'+targetSpan.text+'")');fillArcTypesAndDisplayForm(evt,originSpan.type,targetSpan.type);// for precise timing, log dialog display to user.
dispatcher.post('logAction',['arcSelected']);}}}else if(!evt.ctrlKey){// if not, then is it span selection? (ctrl key cancels)
var sel=window.getSelection();var chunkIndexFrom=sel.anchorNode&&$(sel.anchorNode.parentNode).attr('data-chunk-id');var chunkIndexTo=sel.focusNode&&$(sel.focusNode.parentNode).attr('data-chunk-id');// fallback for firefox (at least):
// it's unclear why, but for firefox the anchor and focus
// node parents are always undefined, the the anchor and
// focus nodes themselves do (often) have the necessary
// chunk ID. However, anchor offsets are almost always
// wrong, so we'll just make a guess at what the user might
// be interested in tagging instead of using what's given.
var anchorOffset=null;var focusOffset=null;if(chunkIndexFrom===undefined&&chunkIndexTo===undefined&&$(sel.anchorNode).attr('data-chunk-id')&&$(sel.focusNode).attr('data-chunk-id')){// A. Scerri FireFox chunk
var range=sel.getRangeAt(0);var svgOffset=$(svg._svg).offset();var flip=false;var tries=0;while(tries<2){var sp=svg._svg.createSVGPoint();sp.x=(flip?evt.pageX:dragStartedAt.pageX)-svgOffset.left;sp.y=(flip?evt.pageY:dragStartedAt.pageY)-(svgOffset.top+8);var startsAt=range.startContainer;anchorOffset=startsAt.getCharNumAtPosition(sp);chunkIndexFrom=startsAt&&$(startsAt).attr('data-chunk-id');if(anchorOffset!=-1){break;}flip=true;tries++;}sp.x=(flip?dragStartedAt.pageX:evt.pageX)-svgOffset.left;sp.y=(flip?dragStartedAt.pageY:evt.pageY)-(svgOffset.top+8);var endsAt=range.endContainer;focusOffset=endsAt.getCharNumAtPosition(sp);if(range.startContainer==range.endContainer&&anchorOffset>focusOffset){var t=anchorOffset;anchorOffset=focusOffset;focusOffset=t;flip=false;}if(focusOffset!=-1){focusOffset++;}chunkIndexTo=endsAt&&$(endsAt).attr('data-chunk-id');//console.log('fallback from', data.chunks[chunkIndexFrom], anchorOffset);
//console.log('fallback to', data.chunks[chunkIndexTo], focusOffset);
}else{// normal case, assume the exact offsets are usable
anchorOffset=sel.anchorOffset;focusOffset=sel.focusOffset;}if(chunkIndexFrom!==undefined&&chunkIndexTo!==undefined){var chunkFrom=data.chunks[chunkIndexFrom];var chunkTo=data.chunks[chunkIndexTo];var selectedFrom=chunkFrom.from+anchorOffset;var selectedTo=chunkTo.from+focusOffset;sel.removeAllRanges();if(selectedFrom>selectedTo){var tmp=selectedFrom;selectedFrom=selectedTo;selectedTo=tmp;}// trim
while(selectedFrom<selectedTo&&" \n\t".indexOf(data.text.substr(selectedFrom,1))!==-1){selectedFrom++;}while(selectedFrom<selectedTo&&" \n\t".indexOf(data.text.substr(selectedTo-1,1))!==-1){selectedTo--;}// shift+click allows zero-width spans
if(selectedFrom===selectedTo&&!evt.shiftKey){// simple click (zero-width span)
return;}var newOffset=[selectedFrom,selectedTo];if(reselectedSpan){var newOffsets=reselectedSpan.offsets.slice(0);// clone
spanOptions.old_offsets=JSON.stringify(reselectedSpan.offsets);if(selectedFragment!==null){if(selectedFragment!==false){newOffsets.splice(selectedFragment,1);}newOffsets.push(newOffset);newOffsets.sort(Util.cmpArrayOnFirstElement);spanOptions.offsets=newOffsets;}else{spanOptions.offsets=[newOffset];}}else{spanOptions={action:'createSpan',offsets:[newOffset]};}/* In relation to #786, removed the cross-sentence checking code
            var crossSentence = true;
            $.each(sourceData.sentence_offsets, function(sentNo, startEnd) {
              if (selectedTo <= startEnd[1]) {
                // this is the sentence

                if (selectedFrom >= startEnd[0]) {
                  crossSentence = false;
                }
                return false;
              }
            });

            if (crossSentence) {
              // attempt to annotate across sentence boundaries; not supported
              dispatcher.post('messages', [[['Error: cannot annotate across a sentence break', 'error']]]);
              if (reselectedSpan) {
                $(reselectedSpan.rect).removeClass('reselect');
              }
              reselectedSpan = null;
              svgElement.removeClass('reselect');
            } else
*/if(!Configuration.rapidModeOn||reselectedSpan!=null){// normal span select in standard annotation mode
// or reselect: show selector
var spanText=data.text.substring(selectedFrom,selectedTo);fillSpanTypesAndDisplayForm(evt,spanText,reselectedSpan);// for precise timing, log annotation display to user.
dispatcher.post('logAction',['spanSelected']);}else{// normal span select in rapid annotation mode: call
// server for span type candidates
var spanText=data.text.substring(selectedFrom,selectedTo);// TODO: we're currently storing the event to position the
// span form using adjustToCursor() (which takes an event),
// but this is clumsy and suboptimal (user may have scrolled
// during the ajax invocation); think of a better way.
lastRapidAnnotationEvent=evt;dispatcher.post('ajax',[{action:'suggestSpanTypes',collection:coll,'document':doc,start:selectedFrom,end:selectedTo,text:spanText,model:$('#rapid_model').val()},'suggestedSpanTypes']);}}}};var receivedSuggestedSpanTypes=function receivedSuggestedSpanTypes(sugg){if(sugg.exception){// failed in one way or another; assume rapid mode cannot be
// used.
dispatcher.post('messages',[[['Rapid annotation mode error; returning to normal mode.','warning',-1]]]);setAnnotationSpeed(2);dispatcher.post('configurationUpdated');return false;}// make sure the suggestions are for the current collection and document
if(sugg.collection!=coll||sugg.document!=doc){dispatcher.post('messages',[[['Error: collection/document mismatch for span suggestions','error']]]);return false;}// initialize for submission
// TODO: is this a reasonable place to do this?
rapidSpanOptions={offsets:[[sugg.start,sugg.end]]};rapidFillSpanTypesAndDisplayForm(sugg.start,sugg.end,sugg.text,sugg.types);};var toggleCollapsible=function toggleCollapsible($el,state){var opening=state!==undefined?state:!$el.hasClass('open');var $collapsible=$el.parent().find('.collapsible:first');if(opening){$collapsible.addClass('open');$el.addClass('open');}else{$collapsible.removeClass('open');$el.removeClass('open');}};var collapseHandler=function collapseHandler(evt){toggleCollapsible($(evt.target));};var spanFormSubmitRadio=function spanFormSubmitRadio(evt){if(Configuration.confirmModeOn){showValidAttributes();showValidNormalizations();$('#span_form-ok').focus();}else{spanFormSubmit(evt,$(evt.target));}};var rapidSpanFormSubmitRadio=function rapidSpanFormSubmitRadio(evt){rapidSpanFormSubmit(evt,$(evt.target));};var rememberData=function rememberData(_data){if(_data&&!_data.exception){data=_data;}};var addSpanTypesToDivInner=function addSpanTypesToDivInner($parent,types,category){if(!types)return;$.each(types,function(typeNo,type){if(type===null){$parent.append('<hr/>');}else{var name=type.name;var $input=$('<input type="radio" name="span_type"/>').attr('id','span_'+type.type).attr('value',type.type);if(category){$input.attr('category',category);}// use a light version of the span color as BG
var spanBgColor=spanTypes[type.type]&&spanTypes[type.type].bgColor||'#ffffff';spanBgColor=Util.adjustColorLightness(spanBgColor,spanBoxTextBgColorLighten);var $label=$('<label class="span_type_label"/>').attr('for','span_'+type.type).text(name);if(type.unused){$input.attr({disabled:'disabled',unused:'unused'});$label.css('font-weight','bold');}else{$label.css('background-color',spanBgColor);}var $collapsible=$('<div class="collapsible open"/>');var $content=$('<div class="item_content"/>').append($input).append($label).append($collapsible);var $collapser=$('<div class="collapser open"/>');var $div=$('<div class="item"/>');if(type.children.length){$div.append($collapser);}$div.append($content);addSpanTypesToDivInner($collapsible,type.children,category);$parent.append($div);if(type.hotkey){spanKeymap[type.hotkey]='span_'+type.type;var name=$label.html();var replace=true;name=name.replace(new RegExp("(&[^;]*?)?("+type.hotkey+")",'gi'),function(all,entity,letter){if(replace&&!entity){replace=false;var hotkey=type.hotkey.toLowerCase()==letter?type.hotkey.toLowerCase():type.hotkey.toUpperCase();return'<span class="accesskey">'+Util.escapeHTML(hotkey)+'</span>';}return all;});$label.html(name);}}});};var addSpanTypesToDiv=function addSpanTypesToDiv($top,types,heading){$scroller=$('<div class="scroller"/>');$legend=$('<legend/>').text(heading);$fieldset=$('<fieldset/>').append($legend).append($scroller);$top.append($fieldset);addSpanTypesToDivInner($scroller,types);};var addAttributeTypesToDiv=function addAttributeTypesToDiv($top,types,category){$.each(types,function(attrNo,attr){var escapedType=Util.escapeQuotes(attr.type);var attrId=category+'_attr_'+escapedType;if(attr.unused){var $input=$('<input type="hidden" id="'+attrId+'" value=""/>');$top.append($input);}else if(attr.bool){var escapedName=Util.escapeQuotes(attr.name);var $input=$('<input type="checkbox" id="'+attrId+'" value="'+escapedType+'" category="'+category+'"/>');var $label=$('<label class="attribute_type_label" for="'+attrId+'" data-bare="'+escapedName+'">&#x2610; '+escapedName+'</label>');$top.append($input).append($label);$input.button();$input.change(onBooleanAttrChange);}else{var $div=$('<div class="ui-button ui-button-text-only attribute_type_label"/>');var $select=$('<select id="'+attrId+'" class="ui-widget ui-state-default ui-button-text" category="'+category+'"/>');var $option=$('<option class="ui-state-default" value=""/>').text(attr.name+': ?');$select.append($option);$.each(attr.values,function(valType,value){$option=$('<option class="ui-state-active" value="'+Util.escapeQuotes(valType)+'"/>').text(attr.name+': '+(value.name||valType));$select.append($option);});$div.append($select);$top.append($div);$select.change(onMultiAttrChange);}});};var setSpanTypeSelectability=function setSpanTypeSelectability(category){// TODO: this implementation is incomplete: we should ideally
// disable not only categories of types (events or entities),
// but the specific set of types that are incompatible with
// the current attribute settings.
// just assume all attributes are event attributes
// TODO: support for entity attributes
// TODO2: the above comment is almost certainly false, check and remove
$('#span_form input:not([unused])').removeAttr('disabled');var $toDisable;if(category=="event"){$toDisable=$('#span_form input[category="entity"]');}else if(category=="entity"){$toDisable=$('#span_form input[category="event"]');}else{console.error('Unrecognized attribute category:',category);$toDisable=$();}var $checkedToDisable=$toDisable.filter(':checked');$toDisable.attr('disabled',true);// the disable may leave the dialog in a state where nothing
// is checked, which would cause error on "OK". In this case,
// check the first valid choice.
if($checkedToDisable.length){var $toCheck=$('#span_form input[category="'+category+'"]:first');// so weird, attr('checked', 'checked') fails sometimes, so
// replaced with more "metal" version
$toCheck[0].checked=true;}};var onMultiAttrChange=function onMultiAttrChange(evt){if($(this).val()==''){$('#span_form input:not([unused])').removeAttr('disabled');}else{var attrCategory=evt.target.getAttribute('category');setSpanTypeSelectability(attrCategory);if(evt.target.selectedIndex){$(evt.target).addClass('ui-state-active');}else{$(evt.target).removeClass('ui-state-active');}}};var onBooleanAttrChange=function onBooleanAttrChange(evt){var attrCategory=evt.target.getAttribute('category');setSpanTypeSelectability(attrCategory);updateCheckbox($(evt.target));};var rememberSpanSettings=function rememberSpanSettings(response){spanKeymap={};// TODO: check for exceptions in response
// fill in entity and event types
var $entityScroller=$('#entity_types div.scroller').empty();addSpanTypesToDivInner($entityScroller,response.entity_types,'entity');var $eventScroller=$('#event_types div.scroller').empty();addSpanTypesToDivInner($eventScroller,response.event_types,'event');// fill in attributes
var $entattrs=$('#entity_attributes div.scroller').empty();addAttributeTypesToDiv($entattrs,entityAttributeTypes,'entity');var $eveattrs=$('#event_attributes div.scroller').empty();addAttributeTypesToDiv($eveattrs,eventAttributeTypes,'event');// fill search options in span dialog
searchConfig=response.search_config;var $searchlinks=$('#span_search_links').empty();var $searchlinks2=$('#viewspan_search_links').empty();var firstLink=true;var linkFilled=false;if(searchConfig){$.each(searchConfig,function(searchNo,search){if(!firstLink){$searchlinks.append(',\n');$searchlinks2.append(',\n');}firstLink=false;$searchlinks.append('<a target="_blank" id="span_'+search[0]+'" href="#">'+search[0]+'</a>');$searchlinks2.append('<a target="_blank" id="viewspan_'+search[0]+'" href="#">'+search[0]+'</a>');linkFilled=true;});}if(linkFilled){$('#span_search_fieldset').show();$('#viewspan_search_fieldset').show();}else{$('#span_search_fieldset').hide();$('#viewspan_search_fieldset').hide();}spanForm.find('#entity_types input:radio').click(spanFormSubmitRadio);spanForm.find('#event_types input:radio').click(spanFormSubmitRadio);spanForm.find('.collapser').click(collapseHandler);};var tagCurrentDocument=function tagCurrentDocument(taggerId){var tagOptions={action:'tag',collection:coll,'document':doc,tagger:taggerId};dispatcher.post('ajax',[tagOptions,'edited']);};var setupTaggerUI=function setupTaggerUI(response){var taggers=response.ner_taggers||[];$taggerButtons=$('#tagger_buttons').empty();$.each(taggers,function(taggerNo,tagger){// expect a tuple with ID, name, model, and URL
var taggerId=tagger[0];var taggerName=tagger[1];var taggerModel=tagger[2];if(!taggerId||!taggerName||!taggerModel){dispatcher.post('messages',[[['Invalid tagger specification received from server','error']]]);return true;// continue
}var $row=$('<div class="optionRow"/>');var $label=$('<span class="optionLabel">'+Util.escapeHTML(taggerName)+'</span>');var $button=$('<input id="tag_'+Util.escapeHTML(taggerId)+'_button" type="button" value="'+Util.escapeHTML(taggerModel)+'" tabindex="-1" title="Automatically tag the current document."/>');$row.append($label).append($button);$taggerButtons.append($row);$button.click(function(evt){tagCurrentDocument(taggerId);});});$taggerButtons.find('input').button();// if nothing was set up, hide the whole fieldset and show
// a message to this effect, else the other way around
if($taggerButtons.find('input').length==0){$('#auto_tagging_fieldset').hide();$('#no_tagger_message').show();}else{$('#auto_tagging_fieldset').show();$('#no_tagger_message').hide();}};// recursively traverses type hierarchy (entity_types or
// event_types) and stores normalizations in normDbsByType.
var rememberNormDbsForType=function rememberNormDbsForType(types){if(!types)return;$.each(types,function(typeNo,type){if(type===null){// spacer, no-op
}else{normDbsByType[type.type]=type.normalizations||[];if(type.children.length){rememberNormDbsForType(type.children);}}});};var setupNormalizationUI=function setupNormalizationUI(response){var norm_resources=response.normalization_config||[];var $norm_select=$('#span_norm_db');// clear possible existing
$norm_select.empty();// fill in new
html=[];$.each(norm_resources,function(normNo,norm){var normName=norm[0],normUrl=norm[1],normUrlBase=norm[2];var serverDb=norm[3];html.push('<option value="'+Util.escapeHTML(normName)+'">'+Util.escapeHTML(normName)+'</option>');// remember the urls for updates
normDbUrlByDbName[normName]=normUrl;normDbUrlBaseByDbName[normName]=normUrlBase;});// remember per-type appropriate DBs
normDbsByType={};rememberNormDbsForType(response.entity_types);rememberNormDbsForType(response.event_types);// set up HTML
$norm_select.html(html.join(''));// if we have nothing, just hide the whole thing
if(!norm_resources.length){$('#norm_fieldset').hide();}else{$('#norm_fieldset').show();}};// hides the reference link in the normalization UI
var hideNormalizationRefLink=function hideNormalizationRefLink(){$('#span_norm_ref_link').hide();};// updates the reference link in the normalization UI according
// to the current value of the normalization DB and ID.
var updateNormalizationRefLink=function updateNormalizationRefLink(){var $normId=$('#span_norm_id');var $normLink=$('#span_norm_ref_link');var normId=$normId.val();var $normDb=$('#span_norm_db');var normDb=$normDb.val();if(!normId||!normDb||normId.match(/^\s*$/)){$normLink.hide();}else{var base=normDbUrlBaseByDbName[normDb];// assume hidden unless everything goes through
$normLink.hide();if(!base){// base URL is now optional, just skip link generation if not set
;}else if(base.indexOf('%s')==-1){dispatcher.post('messages',[[['Base URL "'+base+'" for '+normDb+' does not contain "%s"','error']]]);}else{// TODO: protect against strange chars in ID
link=base.replace('%s',normId);$normLink.attr('href',link);$normLink.show();}}};// updates the DB search link in the normalization UI according
// to the current value of the normalization DB.
var updateNormalizationDbLink=function updateNormalizationDbLink(){var $dbLink=$('#span_norm_db_link');var $normDb=$('#span_norm_db');var normDb=$normDb.val();if(!normDb)return;// no normalisation configured
var link=normDbUrlByDbName[normDb];if(!link||link.match(/^\s*$/)){dispatcher.post('messages',[[['No URL for '+normDb,'error']]]);$dbLink.hide();}else{// TODO: protect against weirdness in DB link
$dbLink.attr('href',link);$dbLink.show();}};// resets user-settable normalization-related UI elements to a
// blank state (does not blank #span_norm_db <select>).
var clearNormalizationUI=function clearNormalizationUI(){var $normId=$('#span_norm_id');var $normText=$('#span_norm_txt');$normId.val('');oldSpanNormIdValue='';$normId.removeClass('valid_value').removeClass('invalid_value');$normText.val('');updateNormalizationRefLink();};// returns the normalizations currently filled in the span
// dialog, or empty list if there are none
var spanNormalizations=function spanNormalizations(){// Note that only no or one normalization is supported in the
// UI at the moment.
var normalizations=[];var normDb=$('#span_norm_db').val();var normId=$('#span_norm_id').val();var normText=$('#span_norm_txt').val();// empty ID -> no normalization
if(!normId.match(/^\s*$/)){normalizations.push([normDb,normId,normText]);}return normalizations;};// returns attributes that are valid for the selected type in
// the span dialog
var spanAttributes=function spanAttributes(typeRadio){typeRadio=typeRadio||$('#span_form input:radio:checked');var attributes={};var attributeTypes;var category=typeRadio.attr('category');if(category=='entity'){attributeTypes=entityAttributeTypes;}else if(category=='event'){attributeTypes=eventAttributeTypes;}else{console.error('Unrecognized type category:',category);}$.each(attributeTypes,function(attrNo,attr){var $input=$('#'+category+'_attr_'+Util.escapeQuotes(attr.type));if(attr.bool){attributes[attr.type]=$input[0].checked;}else if($input[0].selectedIndex){attributes[attr.type]=$input.val();}});return attributes;};var spanAndAttributeTypesLoaded=function spanAndAttributeTypesLoaded(_spanTypes,_entityAttributeTypes,_eventAttributeTypes,_relationTypesHash){spanTypes=_spanTypes;entityAttributeTypes=_entityAttributeTypes;eventAttributeTypes=_eventAttributeTypes;relationTypesHash=_relationTypesHash;// for easier access
allAttributeTypes=$.extend({},entityAttributeTypes,eventAttributeTypes);};var gotCurrent=function gotCurrent(_coll,_doc,_args){coll=_coll;doc=_doc;args=_args;};var undoStack=[];var edited=function edited(response){var x=response.exception;if(x){if(x=='annotationIsReadOnly'){dispatcher.post('messages',[[["This document is read-only and can't be edited.",'error']]]);}else if(x=='spanOffsetOverlapError'){// createSpan with overlapping frag offsets; reset offsets
// @amadanmath: who holds the list of offsets for a span?
// how to reset this?
}else{dispatcher.post('messages',[[['Unknown error '+x,'error']]]);}if(reselectedSpan){$(reselectedSpan.rect).removeClass('reselect');reselectedSpan=null;}svgElement.removeClass('reselect');$('#waiter').dialog('close');}else{if(response.edited==undefined){console.warn('Warning: server response to edit has',response.edited,'value for "edited"');}else{args.edited=response.edited;}var sourceData=response.annotations;sourceData.document=doc;sourceData.collection=coll;// this "prevent" is to protect against reloading (from the
// server) the very data that we just received as part of the
// response to the edit.
if(response.undo!=undefined){undoStack.push([coll,sourceData.document,response.undo]);}dispatcher.post('preventReloadByURL');dispatcher.post('setArguments',[args]);dispatcher.post('renderData',[sourceData]);}};// TODO: why are these globals defined here instead of at the top?
var spanForm=$('#span_form');var rapidSpanForm=$('#rapid_span_form');var deleteSpan=function deleteSpan(){if(Configuration.confirmModeOn&&!confirm("Are you sure you want to delete this annotation?")){return;}$.extend(spanOptions,{action:'deleteSpan',collection:coll,'document':doc});spanOptions.offsets=JSON.stringify(spanOptions.offsets);dispatcher.post('ajax',[spanOptions,'edited']);dispatcher.post('hideForm');$('#waiter').dialog('open');};var reselectSpan=function reselectSpan(){dispatcher.post('hideForm');svgElement.addClass('reselect');$(editedSpan.rect).addClass('reselect');reselectedSpan=editedSpan;selectedFragment=null;};var splitForm=$('#split_form');splitForm.submit(function(evt){var splitRoles=[];$('#split_roles input:checked').each(function(){splitRoles.push($(this).val());});$.extend(spanOptions,{action:'splitSpan','args':$.toJSON(splitRoles),collection:coll,'document':doc});spanOptions.offsets=JSON.stringify(spanOptions.offsets);dispatcher.post('hideForm');dispatcher.post('ajax',[spanOptions,'edited']);return false;});dispatcher.post('initForm',[splitForm,{alsoResize:'.scroll_fset',width:400}]);var splitSpan=function splitSpan(){dispatcher.post('hideForm');var $roles=$('#split_roles').empty();var numRoles=repeatingArcTypes.length;var roles=$.each(repeatingArcTypes,function(){var $role=$('<input id="split_on_'+Util.escapeQuotes(this)+'" type="checkbox" name="'+Util.escapeQuotes(this)+'" value="'+Util.escapeQuotes(this)+'"/>');if(numRoles==1){// a single role will be selected automatically
$role.click();}var $label=$('<label for="split_on_'+Util.escapeQuotes(this)+'">'+Util.escapeQuotes(this)+'</label>');$roles.append($role).append($label);});var $roleButtons=$roles.find('input').button();dispatcher.post('showForm',[splitForm]);};var addFragment=function addFragment(){dispatcher.post('hideForm');svgElement.addClass('reselect');$(editedSpan.rect).addClass('reselect');reselectedSpan=editedSpan;selectedFragment=false;};var reselectFragment=function reselectFragment(){addFragment();selectedFragment=editedFragment;};var deleteFragment=function deleteFragment(){if(Configuration.confirmModeOn&&!confirm("Are you sure you want to delete this fragment?")){return;}var offsets=editedSpan.offsets;spanOptions.old_offsets=JSON.stringify(offsets);offsets.splice(editedFragment,1);$.extend(spanOptions,{collection:coll,'document':doc,offsets:JSON.stringify(offsets)});spanOptions.attributes=$.toJSON(spanAttributes());spanOptions.normalizations=$.toJSON(spanNormalizations());dispatcher.post('ajax',[spanOptions,'edited']);dispatcher.post('hideForm');$('#waiter').dialog('open');};dispatcher.post('initForm',[spanForm,{alsoResize:'#entity_and_event_wrapper',width:760,buttons:[{id:'span_form_add_fragment',text:"Add Frag.",click:addFragment},{id:'span_form_delete',text:"Delete",click:deleteSpan},{id:'span_form_delete_fragment',text:"Delete Frag.",click:deleteFragment},{id:'span_form_reselect',text:'Move',click:reselectSpan},{id:'span_form_reselect_fragment',text:'Move Frag.',click:reselectFragment},{id:'span_form_split',text:'Split',click:splitSpan}],close:function close(evt){keymap=null;if(reselectedSpan){$(reselectedSpan.rect).removeClass('reselect');reselectedSpan=null;svgElement.removeClass('reselect');}}}]);// set button tooltips (@amadanmath: can this be done in init?)
$('#span_form_reselect').attr('title','Re-select the text span that this annotation marks.');$('#span_form_delete').attr('title','Delete this annotation.');$('#span_form_split').attr('title','Split this annotation into multiple similar annotations, distributing its arguments.');dispatcher.post('initForm',[rapidSpanForm,{alsoResize:'#rapid_span_types',width:400,close:function close(evt){keymap=null;}}]);var spanFormSubmit=function spanFormSubmit(evt,typeRadio){typeRadio=typeRadio||$('#span_form input:radio:checked');var type=typeRadio.val();$('#span_form-ok').blur();dispatcher.post('hideForm');$.extend(spanOptions,{action:'createSpan',collection:coll,'document':doc,type:type,comment:$('#span_notes').val()});spanOptions.attributes=$.toJSON(spanAttributes());spanOptions.normalizations=$.toJSON(spanNormalizations());if(spanOptions.offsets){spanOptions.offsets=$.toJSON(spanOptions.offsets);}// unfocus all elements to prevent focus being kept after
// hiding them
spanForm.parent().find('*').blur();$('#waiter').dialog('open');dispatcher.post('ajax',[spanOptions,'edited']);return false;};$('#span_notes').focus(function(){keymap=null;}).blur(function(){keymap=spanKeymap;});spanForm.submit(spanFormSubmit);var rapidSpanFormSubmit=function rapidSpanFormSubmit(evt,typeRadio){typeRadio=typeRadio||$('#rapid_span_form input:radio:checked');var type=typeRadio.val();// unfocus all elements to prevent focus being kept after
// hiding them
rapidSpanForm.parent().find('*').blur();dispatcher.post('hideForm');if(type==""){// empty type value signals the special case where the user
// selected "none of the above" of the proposed types and
// the normal dialog should be brought up for the same span.
spanOptions={action:'createSpan',offsets:rapidSpanOptions.offsets};// TODO: avoid using the stored mouse event
fillSpanTypesAndDisplayForm(lastRapidAnnotationEvent,$('#rapid_span_selected').text());dispatcher.post('logAction',['normalSpanSelected']);}else{// normal type selection; submit createSpan with the selected type.
$.extend(rapidSpanOptions,{action:'createSpan',collection:coll,'document':doc,type:type});$('#waiter').dialog('open');rapidSpanOptions.offsets=JSON.stringify(rapidSpanOptions.offsets);dispatcher.post('ajax',[rapidSpanOptions,'edited']);}return false;};rapidSpanForm.submit(rapidSpanFormSubmit);var importForm=$('#import_form');var importFormSubmit=function importFormSubmit(evt){var _docid=$('#import_docid').val();var _doctitle=$('#import_title').val();var _doctext=$('#import_text').val();var opts={action:'importDocument',collection:coll,docid:_docid,title:_doctitle,text:_doctext};dispatcher.post('ajax',[opts,function(response){var x=response.exception;if(x){if(x=='fileExistsError'){dispatcher.post('messages',[[["A file with the given name exists. Please give a different name to the file to import.",'error']]]);}else{dispatcher.post('messages',[[['Unknown error: '+response.exception,'error']]]);}}else{dispatcher.post('hideForm');dispatcher.post('setDocument',[response.document]);}}]);return false;};importForm.submit(importFormSubmit);dispatcher.post('initForm',[importForm,{width:500,alsoResize:'#import_text',open:function open(evt){keymap={};}}]);$('#import_button').click(function(){dispatcher.post('hideForm');dispatcher.post('showForm',[importForm]);importForm.find('input, textarea').val('');});/* BEGIN delete button - related */$('#delete_document_button').click(function(){if(!doc){dispatcher.post('messages',[[['No document selected','error']]]);return false;}if(!confirm('Are you sure you want to permanently remove this document and its annotations from the collection? This action cannot be undone.')){return;}var delOptions={action:'deleteDocument',collection:coll,'document':doc};dispatcher.post('ajax',[delOptions,'docDeleted']);});$('#delete_collection_button').click(function(){if(!coll){dispatcher.post('messages',[[['No collection selected','error']]]);return false;}if(!confirm('Are you sure you want to permanently REMOVE the ENTIRE COLLECTION '+coll+', including all its documents and their annotations?  This action CANNOT BE UNDONE.')){return;}var delOptions={action:'deleteCollection',collection:coll};dispatcher.post('ajax',[delOptions,'collDeleted']);});/* END delete button - related */$('#undo_button').click(function(){if(coll&&doc){if(undoStack.length>0){var storedUndo=undoStack.pop();var collection=storedUndo[0];var dok=storedUndo[1];var token=storedUndo[2];var options={'action':'undo','collection':collection,'document':dok,'token':token};dispatcher.post('ajax',[options,'edited']);}else{dispatcher.post('messages',[[['No action to be undone','error']]]);}}else{dispatcher.post('messages',[[['No document loaded, can not undo changes','error']]]);}});var preventDefault=function preventDefault(evt){evt.preventDefault();};var $waiter=$('#waiter');$waiter.dialog({closeOnEscape:false,buttons:{},modal:true,open:function open(evt,ui){$(evt.target).parent().find(".ui-dialog-titlebar-close").hide();}});// hide the waiter (Sampo said it's annoying)
// we don't elliminate it altogether because it still provides the
// overlay to prevent interaction
// $waiter.parent().css('opacity', '0');
var isReloadOkay=function isReloadOkay(){// do not reload while the user is in the middle of editing
return arcDragOrigin==null&&reselectedSpan==null;};var userReceived=function userReceived(_user){that.user=_user;};var setAnnotationSpeed=function setAnnotationSpeed(speed){if(speed==1){Configuration.confirmModeOn=true;}else{Configuration.confirmModeOn=false;}if(speed==3){Configuration.rapidModeOn=true;}else{Configuration.rapidModeOn=false;}dispatcher.post('configurationChanged');};var onNewSourceData=function onNewSourceData(_sourceData){sourceData=_sourceData;};var init=function init(){dispatcher.post('annotationIsAvailable');};var collectionLoaded=function collectionLoaded(collData){coll=collData;};var requestRenderData=function requestRenderData(docData){doc=docData;};dispatcher.on('init',init).on('getValidArcTypesForDrag',getValidArcTypesForDrag).on('dataReady',rememberData).on('requestRenderData',requestRenderData).on('collectionLoaded',collectionLoaded).on('collectionLoaded',rememberSpanSettings).on('collectionLoaded',setupTaggerUI).on('collectionLoaded',setupNormalizationUI).on('spanAndAttributeTypesLoaded',spanAndAttributeTypesLoaded).on('newSourceData',onNewSourceData).on('hideForm',hideForm).on('user',userReceived).on('edited',edited).on('current',gotCurrent).on('isReloadOkay',isReloadOkay).on('keydown',onKeyDown).on('dblclick',onDblClick).on('dragstart',preventDefault).on('mousedown',onMouseDown).on('mouseup',onMouseUp).on('mousemove',onMouseMove).on('annotationSpeed',setAnnotationSpeed).on('suggestedSpanTypes',receivedSuggestedSpanTypes).on('normGetNameResult',setSpanNormText).on('normSearchResult',setSpanNormSearchResults);};return AnnotatorUI;}(jQuery,window);// BRAT STANDALONE LIBRARY BEGIN
// Browserify export
module.exports=AnnotatorUI;// BRAT STANDALONE LIBRARY END
},{}],11:[function(require,module,exports){// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*-
// vim:set ft=javascript ts=2 sw=2 sts=2 cindent:
var Configuration=function(window,undefined){var Configuration=function Configuration(){var that=this;that.abbrevsOn=true;that.textBackgrounds="striped";that.svgWidth='100%';that.rapidModeOn=false;that.confirmModeOn=true;that.autorefreshOn=false;that.visual={margin:{x:2,y:1},arcTextMargin:1,boxSpacing:1,curlyHeight:4,arcSpacing:9,//10;
arcStartHeight:19//23; //25;
};};return Configuration;}(window);// BRAT STANDALONE LIBRARY BEGIN
// Browserify export
module.exports=Configuration;// BRAT STANDALONE LIBRARY END
},{}],12:[function(require,module,exports){// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*-
// vim:set ft=javascript ts=2 sw=2 sts=2 cindent:
// TODO: does 'arguments.callee.caller' work?
var Dispatcher=function($,window,undefined){var Dispatcher=function Dispatcher(){var that=this;var table={};var on=function on(message,host,handler){if(handler===undefined){handler=host;host=arguments.callee.caller;}if(table[message]===undefined){table[message]=[];}table[message].push([host,handler]);return this;};// Notify listeners that we encountered an error in an asynch call
var inAsynchError=false;// To avoid error avalanches
var handleAsynchError=function handleAsynchError(e){if(!inAsynchError){inAsynchError=true;// TODO: Hook printout into dispatch elsewhere?
console.warn('Handled async error:',e);that.post('dispatchAsynchError',[e]);inAsynchError=false;}else{console.warn('Dropped asynch error:',e);}};var post=function post(asynch,message,args,returnType){if(typeof asynch!=='number'){// no asynch parameter
returnType=args;args=message;message=asynch;asynch=null;}if(args===undefined){args=[];}var results=[];// DEBUG: if (typeof(message) != "string" || !(message.match(/mouse/) || message == "hideComment")) console.log(message, args);
if(typeof message==='function'){// someone was lazy and sent a simple function
var host=arguments.callee.caller;if(asynch!==null){result=setTimeout(function(){/*try {*/message.apply(host,args);/*} catch(e) {
                that.handleAsynchError(e);
              }*/},asynch);}else{result=message.apply(host,args);}results.push(result);}else{// a proper message, propagate to all interested parties
var todo=table[message];if(todo!==undefined){$.each(todo,function(itemNo,item){var result;if(asynch!==null){result=setTimeout(function(){/*try {*/item[1].apply(item[0],args);/*} catch (e) {
                    that.handleAsynchError(e);
                  }*/},asynch);}else{result=item[1].apply(item[0],args);}results.push(result);});/* DEBUG
          } else {
            console.warn('Message ' + message + ' has no subscribers.'); // DEBUG
*/}}if(returnType=='any'){var i=results.length;while(i--){if(results[i]!==false)return results[i];}return false;}if(returnType=='all'){var i=results.length;while(i--){if(results[i]===false)return results[i];}}return results;};var proxy=function proxy(destination,message){this.on(message,function(){destination.post(message,Array.prototype.slice.call(arguments));});};var dispatcher={on:on,post:post,proxy:proxy};Dispatcher.dispatchers.push(dispatcher);return dispatcher;};Dispatcher.dispatchers=[];Dispatcher.post=function(asynch,message,args,returnType){$.each(Dispatcher.dispatchers,function(dispatcherNo,dispatcher){dispatcher.post(asynch,message,args,returnType);});};return Dispatcher;}(jQuery,window);// BRAT STANDALONE LIBRARY BEGIN
// Browserify export
module.exports=Dispatcher;// BRAT STANDALONE LIBRARY END
},{}],13:[function(require,module,exports){var _require=require("uuidv4"),uuid=_require.uuid;var LocalAjax=function($,window,undefined){var LocalAjax=function LocalAjax(dispatcher,maxFragmentLength){var that=this;var findType=function findType(entityTypes,type){for(var i=0;i<entityTypes.length;i++){var entityType=entityTypes[i];if(entityType.type===type){return entityType;}else{if(entityType.children&&entityType.children.length){var result=findType(entityType.children,type);if(result!==null){return result;}}}}return null;};var createAnnotation=function createAnnotation(data){var attrs=JSON.parse(data.attributes),offsets=JSON.parse(data.offsets),e_type=findType(data.collection.entity_types,data.type);e_id="";//Entity or Trigger
if(!e_type){//Trigger
e_type=data.collection.event_types.find(function(x){return x.type===data.type;});if(e_type){var trigger_id="T"+(that.document.triggers.length+1);//TODO: must absolutely be unique
e_id="E"+(that.document.triggers.length+1);//TODO: must absolutely be unique
data.document.triggers.push([trigger_id,data.type,offsets]);data.document.events.push([e_id,trigger_id,[]]);}}else{var e_id="N"+uuid(),//TODO: must absolutely be unique
new_offsets=splitTooLongFragment(offsets,data,e_id);console.log("new entity id",e_id);//Entity
data.document.entities.push([e_id,data.type,new_offsets]);}for(var key in attrs){if(attrs.hasOwnProperty(key)&&attrs[key]){data.document.attributes.push(["A"+(that.document.attributes.length+1),//TODO: must absolutely be unique,
key,e_id,attrs[key]]);}}if(data.comment.length){data.document.comments.push([e_id,"AnnotatorNotes",data.comment]);}return{data:data,action:data.action,annotations:{"source_files":data.document.source_files,"modifications":data.document.modifications,"normalizations":data.document.normalizations,"text":data.document.text,"entities":data.document.entities,"attributes":data.document.attributes,"relations":data.document.relations,"triggers":data.document.triggers,"events":data.document.events,"comments":data.document.comments},edited:[[e_id]],messages:[],protocol:1};};// Validate max fragment length based on options.maxFragmentLength
// Use discontinguity to fix long annotations glitches before calling BRAT rendering engine.
var splitTooLongFragment=function splitTooLongFragment(offsets,data,e_id){var new_offsets=[];if(maxFragmentLength>0&&offsets.find(function(x){return x[1]-x[0]>maxFragmentLength;})){offsets.forEach(function(fragment){var from=fragment[0],to=fragment[1],subtext=data.document.text.substring(from,to);if(to-from>maxFragmentLength){var from_end=from+subtext.indexOf(' '),to_start=to-(subtext.length-(subtext.lastIndexOf(' ')+1));new_offsets.push([from,from_end]);new_offsets.push([to_start,to]);// Add special attribute for symbolic representation
data.document.attributes.push(["A"+(that.document.attributes.length+1),//TODO: must absolutely be unique,
LONG_ANNOTATION_CONST,e_id,[from,to]]);}else{new_offsets.push([from,to]);}});}else{new_offsets=offsets;}return new_offsets;};var editAnnotation=function editAnnotation(data){var e_type={},//Entity or Trigger
attrs=JSON.parse(data.attributes),offsets=JSON.parse(data.offsets);//Edit annotation TODO: Validation is based on id, fix this
if(data.id.substring(0,1)=="E"){//Event annotation
//data.normalisations ??
var annotation=data.document.events.find(function(x){return x[0]===data.id;});var trigger_id=annotation[1];var trigger=data.document.triggers.find(function(x){return x[0]===trigger_id;});trigger[1]=data.type;trigger[2]=offsets;e_type=data.collection.event_types.find(function(x){return x.type===data.type;});}else if(data.id.substring(0,1)=="N"){//Entity annotation
var entity=data.document.entities.find(function(x){return x[0]===data.id;});entity[1]=data.type;entity[2]=splitTooLongFragment(offsets,data,data.id);e_type=findType(data.collection.entity_types,data.type);}else{//TODO: Error
}if(e_type){//Removed all attributes for this particular annotation id
var existing_attrs=data.document.attributes.filter(function(x){return x[2]===data.id;});existing_attrs.forEach(function(attr){var index=data.document.attributes.indexOf(function(x){return x[0]===attr[0];});//TODO: this always returns -1
data.document.attributes.splice(index,1);});//Re-add all attributes
for(var key in attrs){if(attrs.hasOwnProperty(key)&&attrs[key]){existing_attrs.find(function(x){return x[1]===key;});data.document.attributes.push(["A"+(that.document.attributes.length+1),//TODO: must absolutely be unique,
key,data.id,attrs[key]]);}}//Add/Edit comment content
if(data.comment.length){var comment=data.document.comments.find(function(x){return x[0]===data.id;});if(comment){//Edit
comment[2]=data.comment;}else{//Add
data.document.comments.push([data.id,"AnnotatorNotes",data.comment]);}}//Comments && Attributes are deactivated for relations at this point
return{data:data,action:data.action,annotations:{"source_files":data.document.source_files,"modifications":data.document.modifications,"normalizations":data.document.normalizations,"text":data.document.text,"entities":data.document.entities,"attributes":data.document.attributes,"relations":data.document.relations,"triggers":data.document.triggers,"events":data.document.events,"comments":data.document.comments},edited:[[data.id]],messages:[],protocol:1};}else{return{};//TODO: Error handling
}};var deleteAnnotation=function deleteAnnotation(data){// delete the entity. TODO: also delete events etc
var entities=data.document.entities;for(var i=0;i<entities.length;i++){if(entities[i][0]===data.id){// entity format [id, type, offsets], e.g. ["N1", "Person", Array[2]]
entities.splice(i,1);break;}}// delete relations containing the entity TODO: attributes etc?
var relations=data.document.relations;for(var i=relations.length-1;i>=0;i--){// relation format: ["R1", "Friend", Array[2]]
var relation=relations[i][2];// e.g. [['From', "N1"], ['To', 'N2']]
if(relation[0][1]===data.id||relation[1][1]===data.id){relations.splice(i,1);}}return{action:data.action,annotations:data.document,edited:[],messages:[],protocol:1};};var createRelation=function createRelation(data){var e_type=data.collection.relation_types.find(function(x){return x.type===data.type;});//Entity or Event
if(!e_type){//Event relation
/*data.collection.event_types.forEach(function(event){
                    event.arcs.forEach(function(eRelation){
                        if(eRelation.type === data.type){
                            e_type = event;
                            //TODO: Exit loop
                        }
                    })
                });*/e_type=data.document.events.find(function(x){return x[0]===data.origin;});if(e_type){e_type[2].push([data.type,data.target]);}}else{//Entity relation
var obj=["R"+(that.document.relations.length+1),//TODO: must absolutely me unique
data.type,[[e_type.args[0].role,data.origin],[e_type.args[1].role,data.target]]];data.document.relations.push(obj);}return{action:data.action,annotations:{"source_files":data.document.source_files,"modifications":data.document.modifications,"normalizations":data.document.normalizations,"text":data.document.text,"entities":data.document.entities,"attributes":data.document.attributes,"relations":data.document.relations,"triggers":data.document.triggers,"events":data.document.events//"ctime": 1.0,
//"collection": "",
//"document": "",
//"equivs": [],
//"mtime": 1.0,
//"sentences_offsets": [],
//"token_offsets": [],
},edited:[[data.origin],[data.target]],messages:[],protocol:1};};var editRelation=function editRelation(data){var e_type=data.collection.relation_types.find(function(x){return x.type===data.type;});//Entity or Event
if(!e_type){//Event relation
e_type=data.document.events.find(function(x){return x[0]===data.origin;});if(e_type){}}else{//Entity relation
var relation=data.document.relations.find(function(x){return x[1]===data.old_type&&x[2][0][1]===data.origin&&x[2][1][1]===data.old_target;});relation[1]=data.type;relation[2]=[[e_type.args[0].role,data.origin],[e_type.args[1].role,data.target]];}return{action:data.action,annotations:{"source_files":data.document.source_files,"modifications":data.document.modifications,"normalizations":data.document.normalizations,"text":data.document.text,"entities":data.document.entities,"attributes":data.document.attributes,"relations":data.document.relations,"triggers":data.document.triggers,"events":data.document.events,"comments":data.document.comments},edited:[[data.origin],[data.target]],messages:[],protocol:1};};var localExecution=function localExecution(data,callback,merge){dispatcher.post('spin');dispatcher.post('local-ajax-begin',[data]);that.collection=data.collection;that.document=data.document;var response={};switch(data.action){case"getDocument"://TODO
break;case"loadConf"://TODO
break;case"getCollectionInformation"://TODO
break;case"createArc"://TODO: Validate model with inputs
if(data.old_target||data.old_type){response=editRelation(data);}else{response=createRelation(data);}break;case"deleteArc"://TODO
case"reverseArc"://TODO
break;case"createSpan"://Edit and Created actions on Entities as well as Triggers(Events)
//TODO: Validate model with inputs
if(data.id){response=editAnnotation(data);}else{response=createAnnotation(data);}break;case"deleteSpan":response=deleteAnnotation(data);break;case"deleteFragmentxyz?"://TODO
break;case"splitSpan"://TODO
break;case"tag"://TODO ??
var obj={collection:data.collection,document:data.document,tagger:data.tagger};case"login":case"logout":case"whoami":case"normGetName":case"normSearch":case"suggestSpanTypes":case"importDocument":case"deleteDocument":case"deleteCollection":case"undo":case"normData":case"InDocument":case"InCollection":case"storeSVG":case"getDocumentTimestamp":case"saveConf":break;default://TODO
break;}dispatcher.post(0,callback,[response]);dispatcher.post('local-ajax-done',[response]);dispatcher.post('unspin');};dispatcher.on('ajax',localExecution);};return LocalAjax;}(jQuery,window);// BRAT STANDALONE LIBRARY BEGIN
// Browserify export
module.exports=LocalAjax;// BRAT STANDALONE LIBRARY END
},{"uuidv4":40}],14:[function(require,module,exports){// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*-
// vim:set ft=javascript ts=2 sw=2 sts=2 cindent:
var Spinner=function($,window,undefined){var Spinner=function Spinner(dispatcher,spinElement){var that=this;var spinElement=$(spinElement);var count=0;var spin=function spin(){if(count===0){spinElement.css('display','block');}count++;};var unspin=function unspin(){count--;if(count===0){spinElement.css('display','none');}};dispatcher.on('spin',spin).on('unspin',unspin);};return Spinner;}(jQuery,window);// BRAT STANDALONE LIBRARY BEGIN
// Browserify export
module.exports=Spinner;// BRAT STANDALONE LIBRARY END
},{}],15:[function(require,module,exports){var URLHash=function($,window,undefined){var URLHash=function URLHash(collection,_document,_arguments){var that=this;that.collection=collection;that.document=_document||'';that.arguments=_arguments||{};that.calcArgs();};URLHash.prototype={calcArgs:function calcArgs(){var args=URLHash.splitArgs(this.arguments);this.intArguments=args[0];this.extArguments=args[1];},setArgument:function setArgument(argument,value){if(!this.arguments){this.arguments={};}this.arguments[argument]=value;this.calcArgs();return this;},setArguments:function setArguments(_arguments){// the $.extend here basically takes a copy; raw assignment
// would allow changes of the args to alter original, which
// could be e.g. the "args" of search results
this.arguments=$.extend({},_arguments||{});this.calcArgs();return this;},setDocument:function setDocument(_document){this.document=_document;return this;},setCollection:function setCollection(collection){this.collection=collection;return this;},getHash:function getHash(){var url_hash=this.collection+this.document;var url_args=Util.param(this.extArguments);if(url_args.length){url_hash+='?'+url_args;}if(url_hash.length){url_hash='#'+url_hash;}return url_hash;}};// arguments that do not appear in the URL
var INT_ARGS=['match','matchfocus','edited'];URLHash.splitArgs=function(args){var intArgs={};var extArgs=$.extend({},args);var intArgNameLen=INT_ARGS.length;for(var i=0;i<intArgNameLen;i++){intArgs[INT_ARGS[i]]=extArgs[INT_ARGS[i]];delete extArgs[INT_ARGS[i]];}return[intArgs,extArgs];};// TODO: Document and conform variables to the rest of the object
URLHash.parse=function(hash){if(hash.length){// Remove the leading hash (#)
hash=hash.substr(1);}var pathAndArgs=hash.split('?');var path=pathAndArgs[0]||'';var argsStr=pathAndArgs[1]||'';var coll;var slashPos=path.lastIndexOf('/');if(slashPos===-1){coll='/';}else{coll=path.substr(0,slashPos+1);if(coll[coll.length-1]!=='/'){coll+='/';}if(coll[0]!=='/'){coll='/'+coll;}}var doc=path.substr(slashPos+1);var args=Util.deparam(argsStr);return new URLHash(coll,doc,args);};return URLHash;}(jQuery,window);// BRAT STANDALONE LIBRARY BEGIN
// Browserify export
module.exports=URLHash;// BRAT STANDALONE LIBRARY END
},{}],16:[function(require,module,exports){// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*-
// vim:set ft=javascript ts=2 sw=2 sts=2 cindent:
var Util=function(window,undefined){var monthNames=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];var cmp=function cmp(a,b){return a<b?-1:a>b?1:0;};var cmpArrayOnFirstElement=function cmpArrayOnFirstElement(a,b){a=a[0];b=b[0];return a<b?-1:a>b?1:0;};var unitAgo=function unitAgo(n,unit){if(n==1)return""+n+" "+unit+" ago";return""+n+" "+unit+"s ago";};var formatTimeAgo=function formatTimeAgo(time){if(time==-1000){return"never";// FIXME make the server return the server time!
}var nowDate=new Date();var now=nowDate.getTime();var diff=Math.floor((now-time)/1000);if(!diff)return"just now";if(diff<60)return unitAgo(diff,"second");diff=Math.floor(diff/60);if(diff<60)return unitAgo(diff,"minute");diff=Math.floor(diff/60);if(diff<24)return unitAgo(diff,"hour");diff=Math.floor(diff/24);if(diff<7)return unitAgo(diff,"day");if(diff<28)return unitAgo(Math.floor(diff/7),"week");var thenDate=new Date(time);var result=thenDate.getDate()+' '+monthNames[thenDate.getMonth()];if(thenDate.getYear()!=nowDate.getYear()){result+=' '+thenDate.getFullYear();}return result;};var realBBox=function realBBox(span){var box=span.rect.getBBox();var chunkTranslation=span.chunk.translation;var rowTranslation=span.chunk.row.translation;box.x+=chunkTranslation.x+rowTranslation.x;box.y+=chunkTranslation.y+rowTranslation.y;return box;};var escapeHTML=function escapeHTML(str){return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');};var escapeHTMLandQuotes=function escapeHTMLandQuotes(str){return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\"/g,'&quot;');};var escapeHTMLwithNewlines=function escapeHTMLwithNewlines(str){return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g,'<br/>');};var escapeQuotes=function escapeQuotes(str){// we only use double quotes for HTML attributes
return str.replace(/\"/g,'&quot;');};var getSpanLabels=function getSpanLabels(spanTypes,spanType){var type=spanTypes[spanType];return type&&type.labels||[];};var spanDisplayForm=function spanDisplayForm(spanTypes,spanType){var labels=getSpanLabels(spanTypes,spanType);return labels[0]||spanType;};var getArcLabels=function getArcLabels(spanTypes,spanType,arcType,relationTypesHash){var type=spanTypes[spanType];var arcTypes=type&&type.arcs||[];var arcDesc=null;// also consider matches without suffix number, if any
var noNumArcType;if(arcType){var splitType=arcType.match(/^(.*?)(\d*)$/);noNumArcType=splitType[1];}$.each(arcTypes,function(arcno,arcDescI){if(arcDescI.type==arcType||arcDescI.type==noNumArcType){arcDesc=arcDescI;return false;}});// fall back to relation types for unconfigured or missing def
if(!arcDesc){arcDesc=$.extend({},relationTypesHash[arcType]||relationTypesHash[noNumArcType]);}return arcDesc&&arcDesc.labels||[];};var arcDisplayForm=function arcDisplayForm(spanTypes,spanType,arcType,relationTypesHash){var labels=getArcLabels(spanTypes,spanType,arcType,relationTypesHash);return labels[0]||arcType;};// TODO: switching to use of $.param(), this function should
// be deprecated and removed.
var objectToUrlStr=function objectToUrlStr(o){a=[];$.each(o,function(key,value){a.push(key+"="+encodeURIComponent(value));});return a.join("&");};// color name RGB list, converted from
// http://www.w3schools.com/html/html_colornames.asp
// with perl as
//     perl -e 'print "var colors = {\n"; while(<>) { /(\S+)\s+\#([0-9a-z]{2})([0-9a-z]{2})([0-9a-z]{2})\s*/i or die "Failed to parse $_"; ($r,$g,$b)=(hex($2),hex($3),hex($4)); print "    '\''",lc($1),"'\'':\[$r,$g,$b\],\n" } print "};\n" '
var colors={'aliceblue':[240,248,255],'antiquewhite':[250,235,215],'aqua':[0,255,255],'aquamarine':[127,255,212],'azure':[240,255,255],'beige':[245,245,220],'bisque':[255,228,196],'black':[0,0,0],'blanchedalmond':[255,235,205],'blue':[0,0,255],'blueviolet':[138,43,226],'brown':[165,42,42],'burlywood':[222,184,135],'cadetblue':[95,158,160],'chartreuse':[127,255,0],'chocolate':[210,105,30],'coral':[255,127,80],'cornflowerblue':[100,149,237],'cornsilk':[255,248,220],'crimson':[220,20,60],'cyan':[0,255,255],'darkblue':[0,0,139],'darkcyan':[0,139,139],'darkgoldenrod':[184,134,11],'darkgray':[169,169,169],'darkgrey':[169,169,169],'darkgreen':[0,100,0],'darkkhaki':[189,183,107],'darkmagenta':[139,0,139],'darkolivegreen':[85,107,47],'darkorange':[255,140,0],'darkorchid':[153,50,204],'darkred':[139,0,0],'darksalmon':[233,150,122],'darkseagreen':[143,188,143],'darkslateblue':[72,61,139],'darkslategray':[47,79,79],'darkslategrey':[47,79,79],'darkturquoise':[0,206,209],'darkviolet':[148,0,211],'deeppink':[255,20,147],'deepskyblue':[0,191,255],'dimgray':[105,105,105],'dimgrey':[105,105,105],'dodgerblue':[30,144,255],'firebrick':[178,34,34],'floralwhite':[255,250,240],'forestgreen':[34,139,34],'fuchsia':[255,0,255],'gainsboro':[220,220,220],'ghostwhite':[248,248,255],'gold':[255,215,0],'goldenrod':[218,165,32],'gray':[128,128,128],'grey':[128,128,128],'green':[0,128,0],'greenyellow':[173,255,47],'honeydew':[240,255,240],'hotpink':[255,105,180],'indianred':[205,92,92],'indigo':[75,0,130],'ivory':[255,255,240],'khaki':[240,230,140],'lavender':[230,230,250],'lavenderblush':[255,240,245],'lawngreen':[124,252,0],'lemonchiffon':[255,250,205],'lightblue':[173,216,230],'lightcoral':[240,128,128],'lightcyan':[224,255,255],'lightgoldenrodyellow':[250,250,210],'lightgray':[211,211,211],'lightgrey':[211,211,211],'lightgreen':[144,238,144],'lightpink':[255,182,193],'lightsalmon':[255,160,122],'lightseagreen':[32,178,170],'lightskyblue':[135,206,250],'lightslategray':[119,136,153],'lightslategrey':[119,136,153],'lightsteelblue':[176,196,222],'lightyellow':[255,255,224],'lime':[0,255,0],'limegreen':[50,205,50],'linen':[250,240,230],'magenta':[255,0,255],'maroon':[128,0,0],'mediumaquamarine':[102,205,170],'mediumblue':[0,0,205],'mediumorchid':[186,85,211],'mediumpurple':[147,112,216],'mediumseagreen':[60,179,113],'mediumslateblue':[123,104,238],'mediumspringgreen':[0,250,154],'mediumturquoise':[72,209,204],'mediumvioletred':[199,21,133],'midnightblue':[25,25,112],'mintcream':[245,255,250],'mistyrose':[255,228,225],'moccasin':[255,228,181],'navajowhite':[255,222,173],'navy':[0,0,128],'oldlace':[253,245,230],'olive':[128,128,0],'olivedrab':[107,142,35],'orange':[255,165,0],'orangered':[255,69,0],'orchid':[218,112,214],'palegoldenrod':[238,232,170],'palegreen':[152,251,152],'paleturquoise':[175,238,238],'palevioletred':[216,112,147],'papayawhip':[255,239,213],'peachpuff':[255,218,185],'peru':[205,133,63],'pink':[255,192,203],'plum':[221,160,221],'powderblue':[176,224,230],'purple':[128,0,128],'red':[255,0,0],'rosybrown':[188,143,143],'royalblue':[65,105,225],'saddlebrown':[139,69,19],'salmon':[250,128,114],'sandybrown':[244,164,96],'seagreen':[46,139,87],'seashell':[255,245,238],'sienna':[160,82,45],'silver':[192,192,192],'skyblue':[135,206,235],'slateblue':[106,90,205],'slategray':[112,128,144],'slategrey':[112,128,144],'snow':[255,250,250],'springgreen':[0,255,127],'steelblue':[70,130,180],'tan':[210,180,140],'teal':[0,128,128],'thistle':[216,191,216],'tomato':[255,99,71],'turquoise':[64,224,208],'violet':[238,130,238],'wheat':[245,222,179],'white':[255,255,255],'whitesmoke':[245,245,245],'yellow':[255,255,0],'yellowgreen':[154,205,50]};// color parsing function originally from
// http://plugins.jquery.com/files/jquery.color.js.txt
// (with slight modifications)
// Parse strings looking for color tuples [255,255,255]
var rgbNumRE=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/;var rgbPercRE=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/;var rgbHash6RE=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/;var rgbHash3RE=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/;var strToRgb=function strToRgb(color){var result;// Check if we're already dealing with an array of colors
//         if ( color && color.constructor == Array && color.length == 3 )
//             return color;
// Look for rgb(num,num,num)
if(result=rgbNumRE.exec(color))return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];// Look for rgb(num%,num%,num%)
if(result=rgbPercRE.exec(color))return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];// Look for #a0b1c2
if(result=rgbHash6RE.exec(color))return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];// Look for #fff
if(result=rgbHash3RE.exec(color))return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];// Otherwise, we're most likely dealing with a named color
return colors[$.trim(color).toLowerCase()];};var rgbToStr=function rgbToStr(rgb){// TODO: there has to be a better way, even in JS
var r=Math.floor(rgb[0]).toString(16);var g=Math.floor(rgb[1]).toString(16);var b=Math.floor(rgb[2]).toString(16);// pad
r=r.length<2?'0'+r:r;g=g.length<2?'0'+g:g;b=b.length<2?'0'+b:b;return'#'+r+g+b;};// Functions rgbToHsl and hslToRgb originally from 
// http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
// implementation of functions in Wikipedia
// (with slight modifications)
// RGB to HSL color conversion
var rgbToHsl=function rgbToHsl(rgb){var r=rgb[0]/255,g=rgb[1]/255,b=rgb[2]/255;var max=Math.max(r,g,b),min=Math.min(r,g,b);var h,s,l=(max+min)/2;if(max==min){h=s=0;// achromatic
}else{var d=max-min;s=l>0.5?d/(2-max-min):d/(max+min);switch(max){case r:h=(g-b)/d+(g<b?6:0);break;case g:h=(b-r)/d+2;break;case b:h=(r-g)/d+4;break;}h/=6;}return[h,s,l];};var hue2rgb=function hue2rgb(p,q,t){if(t<0)t+=1;if(t>1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*(2/3-t)*6;return p;};var hslToRgb=function hslToRgb(hsl){var h=hsl[0],s=hsl[1],l=hsl[2];var r,g,b;if(s==0){r=g=b=l;// achromatic
}else{var q=l<0.5?l*(1+s):l+s-l*s;var p=2*l-q;r=hue2rgb(p,q,h+1/3);g=hue2rgb(p,q,h);b=hue2rgb(p,q,h-1/3);}return[r*255,g*255,b*255];};var adjustLightnessCache={};// given color string and -1<=adjust<=1, returns color string
// where lightness (in the HSL sense) is adjusted by the given
// amount, the larger the lighter: -1 gives black, 1 white, and 0
// the given color.
var adjustColorLightness=function adjustColorLightness(colorstr,adjust){if(!(colorstr in adjustLightnessCache)){adjustLightnessCache[colorstr]={};}if(!(adjust in adjustLightnessCache[colorstr])){var rgb=strToRgb(colorstr);if(rgb===undefined){// failed color string conversion; just return the input
adjustLightnessCache[colorstr][adjust]=colorstr;}else{var hsl=rgbToHsl(rgb);if(adjust>0.0){hsl[2]=1.0-(1.0-hsl[2])*(1.0-adjust);}else{hsl[2]=(1.0+adjust)*hsl[2];}var lightRgb=hslToRgb(hsl);adjustLightnessCache[colorstr][adjust]=rgbToStr(lightRgb);}}return adjustLightnessCache[colorstr][adjust];};// Partially stolen from: http://documentcloud.github.com/underscore/
// MIT-License
// TODO: Mention in LICENSE.md
var isEqual=function isEqual(a,b){// Check object identity.
if(a===b)return true;// Different types?
var atype=typeof a==="undefined"?"undefined":_typeof(a),btype=typeof b==="undefined"?"undefined":_typeof(b);if(atype!=btype)return false;// Basic equality test (watch out for coercions).
if(a==b)return true;// One is falsy and the other truthy.
if(!a&&b||a&&!b)return false;// If a is not an object by this point, we can't handle it.
if(atype!=='object')return false;// Check for different array lengths before comparing contents.
if(a.length&&a.length!==b.length)return false;// Nothing else worked, deep compare the contents.
for(var key in b){if(!(key in a))return false;}// Recursive comparison of contents.
for(var key in a){if(!(key in b)||!isEqual(a[key],b[key]))return false;}return true;};var keyValRE=/^([^=]+)=(.*)$/;// key=value
var isDigitsRE=/^[0-9]+$/;var deparam=function deparam(str){var args=str.split('&');var len=args.length;if(!len)return null;var result={};for(var i=0;i<len;i++){var parts=args[i].match(keyValRE);if(!parts||parts.length!=3)break;var val=[];var arr=parts[2].split(',');var sublen=arr.length;for(var j=0;j<sublen;j++){var innermost=[];// map empty arguments ("" in URL) to empty arrays
// (innermost remains [])
if(arr[j].length){var arrsplit=arr[j].split('~');var subsublen=arrsplit.length;for(var k=0;k<subsublen;k++){if(arrsplit[k].match(isDigitsRE)){// convert digits into ints ...
innermost.push(parseInt(arrsplit[k],10));}else{// ... anything else remains a string.
innermost.push(arrsplit[k]);}}}val.push(innermost);}result[parts[1]]=val;}return result;};var paramArray=function paramArray(val){val=val||[];var len=val.length;var arr=[];for(var i=0;i<len;i++){if($.isArray(val[i])){arr.push(val[i].join('~'));}else{// non-array argument; this is an error from the caller
console.error('param: Error: received non-array-in-array argument [',i,']',':',val[i],'(fix caller)');}}return arr;};var param=function param(args){if(!args)return'';var vals=[];for(var key in args){if(args.hasOwnProperty(key)){var val=args[key];if(val==undefined){console.error('Error: received argument',key,'with value',val);continue;}// values normally expected to be arrays, but some callers screw
// up, so check
if($.isArray(val)){var arr=paramArray(val);vals.push(key+'='+arr.join(','));}else{// non-array argument; this is an error from the caller
console.error('param: Error: received non-array argument',key,':',val,'(fix caller)');}}}return vals.join('&');};var profiles={};var profileStarts={};var profileOn=false;var profileEnable=function profileEnable(on){if(on===undefined)on=true;profileOn=on;};// profileEnable
var profileClear=function profileClear(){if(!profileOn)return;profiles={};profileStarts={};};// profileClear
var profileStart=function profileStart(label){if(!profileOn)return;profileStarts[label]=new Date();};// profileStart
var profileEnd=function profileEnd(label){if(!profileOn)return;var profileElapsed=new Date()-profileStarts[label];if(!profiles[label])profiles[label]=0;profiles[label]+=profileElapsed;};// profileEnd
var profileReport=function profileReport(){if(!profileOn)return;if(window.console){$.each(profiles,function(label,time){console.log("profile "+label,time);});console.log("-------");}};// profileReport
// container: ID or jQuery element
// collData: the collection data (in the format of the result of
//   http://.../brat/ajax.cgi?action=getCollectionInformation&collection=...
// docData: the document data (in the format of the result of
//   http://.../brat/ajax.cgi?action=getDocument&collection=...&document=...
// returns the embedded visualizer's dispatcher object
var embed=function embed(container,collData,docData,webFontURLs){var dispatcher=new Dispatcher();var visualizer=new Visualizer(dispatcher,container,webFontURLs);docData.collection=null;dispatcher.post('collectionLoaded',[collData]);dispatcher.post('requestRenderData',[docData]);return dispatcher;};// container: ID or jQuery element
// collDataURL: the URL of the collection data, or collection data
//   object (if pre-fetched)
// docDataURL: the url of the document data (if pre-fetched, use
//   simple `embed` instead)
// callback: optional; the callback to call afterwards; it will be
//   passed the embedded visualizer's dispatcher object
var embedByURL=function embedByURL(container,collDataURL,docDataURL,callback){var collData,docData;var handler=function handler(){if(collData&&docData){var dispatcher=embed(container,collData,docData);if(callback)callback(dispatcher);}};if(typeof container=='string'){$.getJSON(collDataURL,function(data){collData=data;handler();});}else{collData=collDataURL;}$.getJSON(docDataURL,function(data){docData=data;handler();});};return{profileEnable:profileEnable,profileClear:profileClear,profileStart:profileStart,profileEnd:profileEnd,profileReport:profileReport,formatTimeAgo:formatTimeAgo,realBBox:realBBox,getSpanLabels:getSpanLabels,spanDisplayForm:spanDisplayForm,getArcLabels:getArcLabels,arcDisplayForm:arcDisplayForm,escapeQuotes:escapeQuotes,escapeHTML:escapeHTML,escapeHTMLandQuotes:escapeHTMLandQuotes,escapeHTMLwithNewlines:escapeHTMLwithNewlines,cmp:cmp,rgbToHsl:rgbToHsl,hslToRgb:hslToRgb,adjustColorLightness:adjustColorLightness,objectToUrlStr:objectToUrlStr,isEqual:isEqual,paramArray:paramArray,param:param,deparam:deparam,embed:embed,embedByURL:embedByURL};}(window);// BRAT STANDALONE LIBRARY BEGIN
// Browserify export
module.exports=Util;// BRAT STANDALONE LIBRARY END
},{}],17:[function(require,module,exports){// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*-
// vim:set ft=javascript ts=2 sw=2 sts=2 cindent:
var Visualizer=function($,window,undefined){var DocumentData=function DocumentData(text){this.text=text;this.chunks=[];this.spans={};this.eventDescs={};this.sentComment={};this.arcs=[];this.arcById={};this.markedSent={};this.spanAnnTexts={};this.towers={};// this.sizes = {};
};var Fragment=function Fragment(id,span,from,to){this.id=id;this.span=span;this.from=from;this.to=to;// this.towerId = undefined;
// this.drawOrder = undefined;
};var Span=function Span(id,type,offsets,generalType){this.id=id;this.type=type;this.totalDist=0;this.numArcs=0;this.generalType=generalType;this.offsets=offsets;this.headFragment=null;// this.from = undefined;
// this.to = undefined;
// this.wholeFrom = undefined;
// this.wholeTo = undefined;
// this.headFragment = undefined;
// this.chunk = undefined;
// this.marked = undefined;
// this.avgDist = undefined;
// this.curly = undefined;
// this.comment = undefined; // { type: undefined, text: undefined };
// this.annotatorNotes = undefined;
// this.drawCurly = undefined;
// this.glyphedLabelText = undefined;
// this.group = undefined;
// this.height = undefined;
// this.highlightPos = undefined;
// this.indexNumber = undefined;
// this.labelText = undefined;
// this.nestingDepth = undefined;
// this.nestingDepthLR = undefined;
// this.nestingDepthRL = undefined;
// this.nestingHeight = undefined;
// this.nestingHeightLR = undefined;
// this.nestingHeightRL = undefined;
// this.rect = undefined;
// this.rectBox = undefined;
// this.refedIndexSum = undefined;
// this.right = undefined;
// this.totaldist = undefined;
// this.width = undefined;
this.initContainers(offsets);};Span.prototype.initContainers=function(){this.incoming=[];this.outgoing=[];this.attributes={};this.attributeText=[];this.attributeCues={};this.attributeCueFor={};this.attributeMerge={};// for box, cross, etc. that are span-global
this.fragments=[];this.normalizations=[];};Span.prototype.copy=function(id){var span=$.extend(new Span(),this);// clone
span.id=id;span.initContainers();// protect from shallow copy
return span;};var EventDesc=function EventDesc(id,triggerId,roles,klass){this.id=id;this.triggerId=triggerId;var roleList=this.roles=[];$.each(roles,function(roleNo,role){roleList.push({type:role[0],targetId:role[1]});});if(klass=="equiv"){this.equiv=true;}else if(klass=="relation"){this.relation=true;}// this.leftSpans = undefined;
// this.rightSpans = undefined;
// this.annotatorNotes = undefined;
};var Chunk=function Chunk(index,text,from,to,space,spans){this.index=index;this.text=text;this.from=from;this.to=to;this.space=space;this.fragments=[];// this.sentence = undefined;
// this.group = undefined;
// this.highlightGroup = undefined;
// this.markedTextStart = undefined;
// this.markedTextEnd = undefined;
// this.nextSpace = undefined;
// this.right = undefined;
// this.row = undefined;
// this.textX = undefined;
// this.translation = undefined;
};var Arc=function Arc(eventDesc,role,dist,eventNo){this.origin=eventDesc.id;this.target=role.targetId;this.dist=dist;this.type=role.type;this.shadowClass=eventDesc.shadowClass;this.jumpHeight=0;if(eventDesc.equiv){this.equiv=true;this.eventDescId=eventNo;eventDesc.equivArc=this;}else if(eventDesc.relation){this.relation=true;this.eventDescId=eventNo;}// this.marked = undefined;
};var Row=function Row(svg){this.group=svg.group();this.background=svg.group(this.group);this.chunks=[];this.hasAnnotations=false;this.maxArcHeight=0;this.maxSpanHeight=0;};var Measurements=function Measurements(widths,height,y){this.widths=widths;this.height=height;this.y=y;};// A naive whitespace tokeniser
var tokenise=function tokenise(text){var tokenOffsets=[];var tokenStart=null;var lastCharPos=null;for(var i=0;i<text.length;i++){var c=text[i];// Have we found the start of a token?
if(tokenStart==null&&!/\s/.test(c)){tokenStart=i;lastCharPos=i;// Have we found the end of a token?
}else if(/\s/.test(c)&&tokenStart!=null){tokenOffsets.push([tokenStart,i]);tokenStart=null;// Is it a non-whitespace character?
}else if(!/\s/.test(c)){lastCharPos=i;}}// Do we have a trailing token?
if(tokenStart!=null){tokenOffsets.push([tokenStart,lastCharPos+1]);}return tokenOffsets;};// A naive newline sentence splitter
var sentenceSplit=function sentenceSplit(text){var sentenceOffsets=[];var sentStart=null;var lastCharPos=null;for(var i=0;i<text.length;i++){var c=text[i];// Have we found the start of a sentence?
if(sentStart==null&&!/\s/.test(c)){sentStart=i;lastCharPos=i;// Have we found the end of a sentence?
}else if(c=='\n'&&sentStart!=null){sentenceOffsets.push([sentStart,i]);sentStart=null;// Is it a non-whitespace character?
}else if(!/\s/.test(c)){lastCharPos=i;}}// Do we have a trailing sentence without a closing newline?
if(sentStart!=null){sentenceOffsets.push([sentStart,lastCharPos+1]);}return sentenceOffsets;};// Sets default values for a wide range of optional attributes
var setSourceDataDefaults=function setSourceDataDefaults(sourceData){// The following are empty lists if not set
$.each(['attributes','comments','entities','equivs','events','modifications','normalizations','relations','triggers'],function(attrNo,attr){if(sourceData[attr]===undefined){sourceData[attr]=[];}});// If we lack sentence offsets we fall back on naive sentence splitting
if(sourceData.sentence_offsets===undefined){sourceData.sentence_offsets=sentenceSplit(sourceData.text);}// Similarily we fall back on whitespace tokenisation
if(sourceData.token_offsets===undefined){sourceData.token_offsets=tokenise(sourceData.text);}};// Set default values for a variety of collection attributes
var setCollectionDefaults=function setCollectionDefaults(collectionData){// The following are empty lists if not set
$.each(['entity_attribute_types','entity_types','event_attribute_types','event_types','relation_attribute_types','relation_types','unconfigured_types'],function(attrNo,attr){if(collectionData[attr]===undefined){collectionData[attr]=[];}});};var Visualizer=function Visualizer(element,dispatcher,svgId,webFontURLs,fontLoadTimeout){var $svgDiv=$(element).find('#'+svgId);if(!$svgDiv.length){throw Error('Could not find container with id="'+svgId+'"');}var that=this;// OPTIONS
var roundCoordinates=true;// try to have exact pixel offsets
var boxTextMargin={x:0,y:1.5};// effect is inverse of "margin" for some reason
var highlightRounding={x:3,y:3};// rx, ry for highlight boxes
var spaceWidths={' ':4,"\xA0":4,"\u200B":0,"\u3000":8,"\t":12,//Unicode tabulation
'\n':4};var coloredCurlies=true;// color curlies by box BG
var arcSlant=15;//10;
var minArcSlant=8;var arcHorizontalSpacing=10;// min space boxes with connecting arc
var rowSpacing=-5;// for some funny reason approx. -10 gives "tight" packing.
var sentNumMargin=50;var smoothArcCurves=true;// whether to use curves (vs lines) in arcs
var smoothArcSteepness=0.5;// steepness of smooth curves (control point)
var reverseArcControlx=5;// control point distance for "UFO catchers"
// "shadow" effect settings (note, error, incompelete)
var rectShadowSize=3;var rectShadowRounding=2.5;var arcLabelShadowSize=1;var arcLabelShadowRounding=5;var shadowStroke=2.5;// TODO XXX: this doesn't affect anything..?
// "marked" effect settings (edited, focus, match)
var markedSpanSize=6;var markedArcSize=2;var markedArcStroke=7;// TODO XXX: this doesn't seem to do anything..?
var rowPadding=2;var nestingAdjustYStepSize=2;// size of height adjust for nested/nesting spans
var nestingAdjustXStepSize=1;// size of height adjust for nested/nesting spans
var highlightSequence='#FF9632;#FFCC00;#FF9632';// yellow - deep orange
//var highlightSequence = '#FFFC69;#FFCC00;#FFFC69'; // a bit toned town
var highlightSpanSequence=highlightSequence;var highlightArcSequence=highlightSequence;var highlightTextSequence=highlightSequence;var highlightDuration='2s';// different sequence for "mere" matches (as opposed to "focus" and
// "edited" highlights)
var highlightMatchSequence='#FFFF00';// plain yellow
var fragmentConnectorDashArray='1,3,3,3';var fragmentConnectorColor='#000000';// END OPTIONS
var svg;var $svg;var data=null;var sourceData=null;var requestedData=null;var coll,doc,args;var relationTypesHash;var isRenderRequested;var isCollectionLoaded=false;var entityAttributeTypes=null;var eventAttributeTypes=null;var spanTypes=null;var highlightGroup;// var commentPrioLevels = ['Unconfirmed', 'Incomplete', 'Warning', 'Error', 'AnnotatorNotes'];
// XXX Might need to be tweaked - inserted diff levels
var commentPrioLevels=['Unconfirmed','Incomplete','Warning','Error','AnnotatorNotes','AddedAnnotation','MissingAnnotation','ChangedAnnotation'];this.arcDragOrigin=null;// TODO
// due to silly Chrome bug, I have to make it pay attention
var forceRedraw=function forceRedraw(){if(!$.browser.chrome)return;// not needed
$svg.css('margin-bottom',1);setTimeout(function(){$svg.css('margin-bottom',0);},0);};var rowBBox=function rowBBox(span){var box=$.extend({},span.rectBox);// clone
var chunkTranslation=span.chunk.translation;box.x+=chunkTranslation.x;box.y+=chunkTranslation.y;return box;};var commentPriority=function commentPriority(commentClass){if(commentClass===undefined)return-1;var len=commentPrioLevels.length;for(var i=0;i<len;i++){if(commentClass.indexOf(commentPrioLevels[i])!=-1)return i;}return 0;};var clearSVG=function clearSVG(){data=null;sourceData=null;svg.clear();$svgDiv.hide();};var setMarked=function setMarked(markedType){$.each(args[markedType]||[],function(markedNo,marked){if(marked[0]=='sent'){data.markedSent[marked[1]]=true;}else if(marked[0]=='equiv'){// [equiv, Equiv, T1]
$.each(sourceData.equivs,function(equivNo,equiv){if(equiv[1]==marked[1]){var len=equiv.length;for(var i=2;i<len;i++){if(equiv[i]==marked[2]){// found it
len-=3;for(var i=1;i<=len;i++){var arc=data.eventDescs[equiv[0]+"*"+i].equivArc;arc.marked=markedType;}return;// next equiv
}}}});}else if(marked.length==2){markedText.push([parseInt(marked[0],10),parseInt(marked[1],10),markedType]);}else{var span=data.spans[marked[0]];if(span){if(marked.length==3){// arc
$.each(span.outgoing,function(arcNo,arc){if(arc.target==marked[2]&&arc.type==marked[1]){arc.marked=markedType;}});}else{// span
span.marked=markedType;}}else{var eventDesc=data.eventDescs[marked[0]];if(eventDesc){// relation
var relArc=eventDesc.roles[0];$.each(data.spans[eventDesc.triggerId].outgoing,function(arcNo,arc){if(arc.target==relArc.targetId&&arc.type==relArc.type){arc.marked=markedType;}});}else{// try for trigger
$.each(data.eventDescs,function(eventDescNo,eventDesc){if(eventDesc.triggerId==marked[0]){data.spans[eventDesc.id].marked=markedType;}});}}}});};var fragmentComparator=function fragmentComparator(a,b){var tmp;var aSpan=a.span;var bSpan=b.span;// spans with more fragments go first
tmp=aSpan.fragments.length-bSpan.fragments.length;if(tmp){return tmp<0?1:-1;}// longer arc distances go last
tmp=aSpan.avgDist-bSpan.avgDist;if(tmp){return tmp<0?-1:1;}// spans with more arcs go last
tmp=aSpan.numArcs-bSpan.numArcs;if(tmp){return tmp<0?-1:1;}// compare the span widths,
// put wider on bottom so they don't mess with arcs, or shorter
// on bottom if there are no arcs.
var ad=a.to-a.from;var bd=b.to-b.from;tmp=ad-bd;if(aSpan.numArcs==0&&bSpan.numArcs==0){tmp=-tmp;}if(tmp){return tmp<0?1:-1;}tmp=aSpan.refedIndexSum-bSpan.refedIndexSum;if(tmp){return tmp<0?-1:1;}// if no other criterion is found, sort by type to maintain
// consistency
// TODO: isn't there a cmp() in JS?
if(aSpan.type<bSpan.type){return-1;}else if(aSpan.type>bSpan.type){return 1;}return 0;};var setData=function setData(_sourceData){if(!args)args={};sourceData=_sourceData;dispatcher.post('newSourceData',[sourceData]);data=new DocumentData(sourceData.text);// collect annotation data
$.each(sourceData.entities,function(entityNo,entity){// offsets given as array of (start, end) pairs
var span=//      (id,        type,      offsets,   generalType)
new Span(entity[0],entity[1],entity[2],'entity');data.spans[entity[0]]=span;});var triggerHash={};$.each(sourceData.triggers,function(triggerNo,trigger){triggerHash[trigger[0]]=//       (id,         type,       offsets,    generalType), eventList
[new Span(trigger[0],trigger[1],trigger[2],'trigger'),[]];});$.each(sourceData.events,function(eventNo,eventRow){var eventDesc=data.eventDescs[eventRow[0]]=//           (id,          triggerId,   roles,        klass)
new EventDesc(eventRow[0],eventRow[1],eventRow[2]);var trigger=triggerHash[eventDesc.triggerId];var span=trigger[0].copy(eventDesc.id);trigger[1].push(span);data.spans[eventDesc.id]=span;});// XXX modifications: delete later
$.each(sourceData.modifications,function(modNo,mod){// mod: [id, spanId, modification]
if(!data.spans[mod[2]]){dispatcher.post('messages',[[['<strong>ERROR</strong><br/>Event '+mod[2]+' (referenced from modification '+mod[0]+') does not occur in document '+data.document+'<br/>(please correct the source data)','error',5]]]);return;}data.spans[mod[2]][mod[1]]=true;});var midpointComparator=function midpointComparator(a,b){var tmp=a.from+a.to-b.from-b.to;if(!tmp)return 0;return tmp<0?-1:1;};// split spans into span fragments (for discontinuous spans)
$.each(data.spans,function(spanNo,span){$.each(span.offsets,function(offsetsNo,offsets){var from=parseInt(offsets[0],10);var to=parseInt(offsets[1],10);var fragment=new Fragment(offsetsNo,span,from,to);span.fragments.push(fragment);});// ensure ascending order
span.fragments.sort(midpointComparator);span.wholeFrom=span.fragments[0].from;span.wholeTo=span.fragments[span.fragments.length-1].to;span.headFragment=span.fragments[true?span.fragments.length-1:0];// TODO configurable!
});var spanComparator=function spanComparator(a,b){var aSpan=data.spans[a];var bSpan=data.spans[b];var tmp=aSpan.headFragment.from+aSpan.headFragment.to-bSpan.headFragment.from-bSpan.headFragment.to;if(tmp){return tmp<0?-1:1;}return 0;};$.each(sourceData.equivs,function(equivNo,equiv){// equiv: ['*', 'Equiv', spanId...]
equiv[0]="*"+equivNo;var equivSpans=equiv.slice(2);var okEquivSpans=[];// collect the equiv spans in an array
$.each(equivSpans,function(equivSpanNo,equivSpan){if(data.spans[equivSpan])okEquivSpans.push(equivSpan);// TODO: #404, inform the user with a message?
});// sort spans in the equiv by their midpoint
okEquivSpans.sort(spanComparator);// generate the arcs
var len=okEquivSpans.length;for(var i=1;i<len;i++){var eventDesc=data.eventDescs[equiv[0]+'*'+i]=//           (id,                  triggerId,           roles,                         klass)
new EventDesc(okEquivSpans[i-1],okEquivSpans[i-1],[[equiv[1],okEquivSpans[i]]],'equiv');eventDesc.leftSpans=okEquivSpans.slice(0,i);eventDesc.rightSpans=okEquivSpans.slice(i);}});$.each(sourceData.relations,function(relNo,rel){// rel[2] is args, rel[2][a][0] is role and rel[2][a][1] is value for a in (0,1)
var argsDesc=relationTypesHash[rel[1]];argsDesc=argsDesc&&argsDesc.args;var t1,t2;if(argsDesc){// sort the arguments according to the config
var args={};args[rel[2][0][0]]=rel[2][0][1];args[rel[2][1][0]]=rel[2][1][1];t1=args[argsDesc[0].role];t2=args[argsDesc[1].role];}else{// (or leave as-is in its absence)
t1=rel[2][0][1];t2=rel[2][1][1];}data.eventDescs[rel[0]]=//           (id, triggerId, roles,          klass)
new EventDesc(t1,t1,[[rel[1],t2]],'relation');});// attributes
$.each(sourceData.attributes,function(attrNo,attr){// attr: [id, name, spanId, value, cueSpanId
// TODO: might wish to check what's appropriate for the type
// instead of using the first attribute def found
var attrType=eventAttributeTypes[attr[1]]||entityAttributeTypes[attr[1]];var attrValue=attrType&&attrType.values[attrType.bool||attr[3]];var span=data.spans[attr[2]];if(!span){dispatcher.post('messages',[[['Annotation '+attr[2]+', referenced from attribute '+attr[0]+', does not exist.','error']]]);return;}var valText=attrValue&&attrValue.name||attr[3];var attrText=attrType?attrType.bool?attrType.name:attrType.name+': '+valText:attr[3]==true?attr[1]:attr[1]+': '+attr[3];span.attributeText.push(attrText);span.attributes[attr[1]]=attr[3];if(attr[4]){// cue
span.attributeCues[attr[1]]=attr[4];var cueSpan=data.spans[attr[4]];cueSpan.attributeCueFor[data.spans[1]]=attr[2];cueSpan.cue='CUE';// special css type
}$.extend(span.attributeMerge,attrValue);});// comments
$.each(sourceData.comments,function(commentNo,comment){// comment: [entityId, type, text]
// TODO error handling
// sentence id: ['sent', sentId]
if(comment[0]instanceof Array&&comment[0][0]=='sent'){// sentence comment
var sent=comment[0][1];var text=comment[2];if(data.sentComment[sent]){text=data.sentComment[sent].text+'<br/>'+text;}data.sentComment[sent]={type:comment[1],text:text};}else{var id=comment[0];var trigger=triggerHash[id];var eventDesc=data.eventDescs[id];var commentEntities=trigger?trigger[1]// trigger: [span, ...]
:id in data.spans?[data.spans[id]]// span: [span]
:id in data.eventDescs?[data.eventDescs[id]]// arc: [eventDesc]
:[];$.each(commentEntities,function(entityId,entity){// if duplicate comment for entity:
// overwrite type, concatenate comment with a newline
if(!entity.comment){entity.comment={type:comment[1],text:comment[2]};}else{entity.comment.type=comment[1];entity.comment.text+="\n"+comment[2];}// partially duplicate marking of annotator note comments
if(comment[1]=="AnnotatorNotes"){entity.annotatorNotes=comment[2];}// prioritize type setting when multiple comments are present
if(commentPriority(comment[1])>commentPriority(entity.shadowClass)){entity.shadowClass=comment[1];}});}});// normalizations
$.each(sourceData.normalizations,function(normNo,norm){var id=norm[0];var normType=norm[1];var target=norm[2];var refdb=norm[3];var refid=norm[4];var reftext=norm[5];// grab entity / event the normalization applies to
var span=data.spans[target];if(!span){dispatcher.post('messages',[[['Annotation '+target+', referenced from normalization '+id+', does not exist.','error']]]);return;}// TODO: do we have any possible use for the normType?
span.normalizations.push([refdb,refid,reftext]);// quick hack for span box visual style
span.normalized='Normalized';});// prepare span boundaries for token containment testing
var sortedFragments=[];$.each(data.spans,function(spanNo,span){$.each(span.fragments,function(fragmentNo,fragment){sortedFragments.push(fragment);});});// sort fragments by beginning, then by end
sortedFragments.sort(function(a,b){var x=a.from;var y=b.from;if(x==y){x=a.to;y=b.to;}return x<y?-1:x>y?1:0;});var currentFragmentId=0;var startFragmentId=0;var numFragments=sortedFragments.length;var lastTo=0;var firstFrom=null;var chunkNo=0;var space;var chunk=null;// token containment testing (chunk recognition)
$.each(sourceData.token_offsets,function(){var from=this[0];var to=this[1];if(firstFrom===null)firstFrom=from;// Replaced for speedup; TODO check correctness
// inSpan = false;
// $.each(data.spans, function(spanNo, span) {
//   if (span.from < to && to < span.to) {
//     // it does; no word break
//     inSpan = true;
//     return false;
//   }
// });
// Is the token end inside a span?
if(startFragmentId&&to>sortedFragments[startFragmentId-1].to){while(startFragmentId<numFragments&&to>sortedFragments[startFragmentId].from){startFragmentId++;}}currentFragmentId=startFragmentId;while(currentFragmentId<numFragments&&to>=sortedFragments[currentFragmentId].to){currentFragmentId++;}// if yes, the next token is in the same chunk
if(currentFragmentId<numFragments&&to>sortedFragments[currentFragmentId].from){return;}//Renaud test chunk must not be longer than n
/*var n = 80;
          var loop = 3;
          if(to - firstFrom > n){ //103
            //create 3 chunks
            for(var i = 0; i < loop; ++i){
              var length = Math.floor((to - firstFrom)/loop);
              var to2 = firstFrom + (length * (i + 1));
              var firstFrom2 = (firstFrom + (length * i)) + 1;

              // otherwise, create the chunk found so far
              space = data.text.substring(to2, firstFrom2);
              var text = data.text.substring(firstFrom2, to2);
              if (chunk) chunk.nextSpace = space;
              chunk = new Chunk(chunkNo++, text, firstFrom2, to2, space);
              data.chunks.push(chunk);
            }

          }else{*/// otherwise, create the chunk found so far
space=data.text.substring(lastTo,firstFrom);var text=data.text.substring(firstFrom,to);if(chunk)chunk.nextSpace=space;//               (index,     text, from,      to, space) {
chunk=new Chunk(chunkNo++,text,firstFrom,to,space);data.chunks.push(chunk);/*}*/lastTo=to;firstFrom=null;});var numChunks=chunkNo;// find sentence boundaries in relation to chunks
chunkNo=0;var sentenceNo=0;var pastFirst=false;$.each(sourceData.sentence_offsets,function(){var from=this[0];if(chunkNo>=numChunks)return false;if(data.chunks[chunkNo].from>from)return;var chunk;while(chunkNo<numChunks&&(chunk=data.chunks[chunkNo]).from<from){chunkNo++;}chunkNo++;if(pastFirst&&from<=chunk.from){var numNL=chunk.space.split("\n").length-1;if(!numNL)numNL=1;sentenceNo+=numNL;chunk.sentence=sentenceNo;}else{pastFirst=true;}});// assign fragments to appropriate chunks
var currentChunkId=0;var chunk;$.each(sortedFragments,function(fragmentId,fragment){while(fragment.to>(chunk=data.chunks[currentChunkId]).to){currentChunkId++;}chunk.fragments.push(fragment);fragment.text=chunk.text.substring(fragment.from-chunk.from,fragment.to-chunk.from);fragment.chunk=chunk;});// assign arcs to spans; calculate arc distances
$.each(data.eventDescs,function(eventNo,eventDesc){var dist=0;var origin=data.spans[eventDesc.id];if(!origin){// TODO: include missing trigger ID in error message
dispatcher.post('messages',[[['<strong>ERROR</strong><br/>Trigger for event "'+eventDesc.id+'" not found in '+data.document+'<br/>(please correct the source data)','error',5]]]);return;}var here=origin.headFragment.from+origin.headFragment.to;$.each(eventDesc.roles,function(roleNo,role){var target=data.spans[role.targetId];if(!target){dispatcher.post('messages',[[['<strong>ERROR</strong><br/>"'+role.targetId+'" (referenced from "'+eventDesc.id+'") not found in '+data.document+'<br/>(please correct the source data)','error',5]]]);return;}var there=target.headFragment.from+target.headFragment.to;var dist=Math.abs(here-there);var arc=new Arc(eventDesc,role,dist,eventNo);origin.totalDist+=dist;origin.numArcs++;target.totalDist+=dist;target.numArcs++;data.arcs.push(arc);target.incoming.push(arc);origin.outgoing.push(arc);// ID dict for easy access. TODO: have a function defining the
// (origin,type,target)->id mapping (see also annotator_ui.js)
var arcId=origin.id+'--'+role.type+'--'+target.id;data.arcById[arcId]=arc;});// roles
});// eventDescs
// highlighting
markedText=[];setMarked('edited');// set by editing process
setMarked('focus');// set by URL
setMarked('matchfocus');// set by search process, focused match
setMarked('match');// set by search process, other (non-focused) match
$.each(data.spans,function(spanId,span){// calculate average arc distances
// average distance of arcs (0 for no arcs)
span.avgDist=span.numArcs?span.totalDist/span.numArcs:0;lastSpan=span;// collect fragment texts into span texts
var fragmentTexts=[];$.each(span.fragments,function(fragmentNo,fragment){// TODO heuristics
fragmentTexts.push(fragment.text);});span.text=fragmentTexts.join('');});// data.spans
for(var i=0;i<2;i++){// preliminary sort to assign heights for basic cases
// (first round) and cases resolved in the previous
// round(s).
$.each(data.chunks,function(chunkNo,chunk){// sort
chunk.fragments.sort(fragmentComparator);// renumber
$.each(chunk.fragments,function(fragmentNo,fragment){fragment.indexNumber=fragmentNo;});});// nix the sums, so we can sum again
$.each(data.spans,function(spanNo,span){span.refedIndexSum=0;});// resolved cases will now have indexNumber set
// to indicate their relative order. Sum those for referencing cases
// for use in iterative resorting
$.each(data.arcs,function(arcNo,arc){data.spans[arc.origin].refedIndexSum+=data.spans[arc.target].headFragment.indexNumber;});}// Final sort of fragments in chunks for drawing purposes
// Also identify the marked text boundaries regarding chunks
$.each(data.chunks,function(chunkNo,chunk){// and make the next sort take this into account. Note that this will
// now resolve first-order dependencies between sort orders but not
// second-order or higher.
chunk.fragments.sort(fragmentComparator);$.each(chunk.fragments,function(fragmentNo,fragment){fragment.drawOrder=fragmentNo;});});data.spanDrawOrderPermutation=Object.keys(data.spans);data.spanDrawOrderPermutation.sort(function(a,b){var spanA=data.spans[a];var spanB=data.spans[b];// We're jumping all over the chunks, but it's enough that
// we're doing everything inside each chunk in the right
// order. should it become necessary to actually do these in
// linear order, put in a similar condition for
// spanX.headFragment.chunk.index; but it should not be
// needed.
var tmp=spanA.headFragment.drawOrder-spanB.headFragment.drawOrder;if(tmp)return tmp<0?-1:1;return 0;});// resort the spans for linear order by center
sortedFragments.sort(midpointComparator);// sort fragments into towers, calculate average arc distances
var lastFragment=null;var towerId=-1;$.each(sortedFragments,function(i,fragment){if(!lastFragment||lastFragment.from!=fragment.from||lastFragment.to!=fragment.to){towerId++;}fragment.towerId=towerId;lastFragment=fragment;});// sortedFragments
// find curlies (only the first fragment drawn in a tower)
$.each(data.spanDrawOrderPermutation,function(spanIdNo,spanId){var span=data.spans[spanId];$.each(span.fragments,function(fragmentNo,fragment){if(!data.towers[fragment.towerId]){data.towers[fragment.towerId]=[];fragment.drawCurly=true;fragment.span.drawCurly=true;}data.towers[fragment.towerId].push(fragment);});});var spanAnnTexts={};$.each(data.chunks,function(chunkNo,chunk){chunk.markedTextStart=[];chunk.markedTextEnd=[];$.each(chunk.fragments,function(fragmentNo,fragment){if(chunk.firstFragmentIndex==undefined){chunk.firstFragmentIndex=fragment.towerId;}chunk.lastFragmentIndex=fragment.towerId;var spanLabels=Util.getSpanLabels(spanTypes,fragment.span.type);fragment.labelText=Util.spanDisplayForm(spanTypes,fragment.span.type);// Find the most appropriate label according to text width
if(Configuration.abbrevsOn&&spanLabels){var labelIdx=1;// first abbrev
var maxLength=(fragment.to-fragment.from)/0.8;while(fragment.labelText.length>maxLength&&spanLabels[labelIdx]){fragment.labelText=spanLabels[labelIdx];labelIdx++;}}var svgtext=svg.createText();// one "text" element per row
var postfixArray=[];var prefix='';var postfix='';var warning=false;$.each(fragment.span.attributes,function(attrType,valType){// TODO: might wish to check what's appropriate for the type
// instead of using the first attribute def found
var attr=eventAttributeTypes[attrType]||entityAttributeTypes[attrType];if(!attr){// non-existent type
warning=true;return;}var val=attr.values[attr.bool||valType];if(!val){// non-existent value
warning=true;return;}if($.isEmptyObject(val)){// defined, but lacks any visual presentation
warning=true;return;}if(val.glyph){if(val.position=="left"){prefix=val.glyph+prefix;var css='glyph';if(attr.css)css+=' glyph_'+Util.escapeQuotes(attr.css);svgtext.span(val.glyph,{'class':css});}else{// XXX right is implied - maybe change
postfixArray.push([attr,val]);postfix+=val.glyph;}}});var text=fragment.labelText;if(prefix!==''){text=prefix+' '+text;svgtext.string(' ');}svgtext.string(fragment.labelText);if(postfixArray.length){text+=' '+postfix;svgtext.string(' ');$.each(postfixArray,function(elNo,el){var css='glyph';if(el[0].css)css+=' glyph_'+Util.escapeQuotes(el[0].css);svgtext.span(el[1].glyph,{'class':css});});}if(warning){svgtext.span("#",{'class':'glyph attribute_warning'});text+=' #';}fragment.glyphedLabelText=text;if(!spanAnnTexts[text]){spanAnnTexts[text]=true;data.spanAnnTexts[text]=svgtext;}});// chunk.fragments
});// chunks
var numChunks=data.chunks.length;// note the location of marked text with respect to chunks
var startChunk=0;var currentChunk;// sort by "from"; we don't need to sort by "to" as well,
// because unlike spans, chunks are disjunct
markedText.sort(function(a,b){return Util.cmp(a[0],b[0]);});$.each(markedText,function(textNo,textPos){var from=textPos[0];var to=textPos[1];var markedType=textPos[2];if(from<0)from=0;if(to<0)to=0;if(to>=data.text.length)to=data.text.length-1;if(from>to)from=to;while(startChunk<numChunks){var chunk=data.chunks[startChunk];if(from<=chunk.to){chunk.markedTextStart.push([textNo,true,from-chunk.from,null,markedType]);break;}startChunk++;}if(startChunk==numChunks){dispatcher.post('messages',[[['Wrong text offset','error']]]);return;}currentChunk=startChunk;while(currentChunk<numChunks){var chunk=data.chunks[currentChunk];if(to<=chunk.to){chunk.markedTextEnd.push([textNo,false,to-chunk.from]);break;}currentChunk++;}if(currentChunk==numChunks){dispatcher.post('messages',[[['Wrong text offset','error']]]);var chunk=data.chunks[data.chunks.length-1];chunk.markedTextEnd.push([textNo,false,chunk.text.length]);return;}});// markedText
dispatcher.post('dataReady',[data]);};var resetData=function resetData(){setData(sourceData);renderData();};var translate=function translate(element,x,y){$(element.group).attr('transform','translate('+x+', '+y+')');element.translation={x:x,y:y};};var showMtime=function showMtime(){if(data.mtime){// we're getting seconds and need milliseconds
//$('#document_ctime').text("Created: " + Annotator.formatTime(1000 * data.ctime)).css("display", "inline");
$('#document_mtime').text("Last modified: "+Util.formatTimeAgo(1000*data.mtime)).css("display","inline");}else{//$('#document_ctime').css("display", "none");
$('#document_mtime').css("display","none");}};var addHeaderAndDefs=function addHeaderAndDefs(){var commentName=(coll+'/'+doc).replace('--','-\\-');$svg.append('<!-- document: '+commentName+' -->');var defs=svg.defs();var $blurFilter=$('<filter id="Gaussian_Blur"><feGaussianBlur in="SourceGraphic" stdDeviation="2" /></filter>');svg.add(defs,$blurFilter);return defs;};var getTextMeasurements=function getTextMeasurements(textsHash,options,callback){// make some text elements, find out the dimensions
var textMeasureGroup=svg.group(options);// changed from $.each because of #264 ('length' can appear)
for(var text in textsHash){if(textsHash.hasOwnProperty(text)){svg.text(textMeasureGroup,0,0,text);}}// measuring goes on here
var widths={};$(textMeasureGroup).find('text').each(function(svgTextNo,svgText){var text=$(svgText).text();widths[text]=this.getComputedTextLength();if(callback){$.each(textsHash[text],function(text,object){callback(object,svgText);});}});var bbox=textMeasureGroup.getBBox();svg.remove(textMeasureGroup);return new Measurements(widths,bbox.height,bbox.y);};var getTextAndSpanTextMeasurements=function getTextAndSpanTextMeasurements(){// get the span text sizes
var chunkTexts={};// set of span texts
$.each(data.chunks,function(chunkNo,chunk){chunk.row=undefined;// reset
if(!(chunk.text in chunkTexts))chunkTexts[chunk.text]=[];var chunkText=chunkTexts[chunk.text];// here we also need all the spans that are contained in
// chunks with this text, because we need to know the position
// of the span text within the respective chunk text
chunkText.push.apply(chunkText,chunk.fragments);// and also the markedText boundaries
chunkText.push.apply(chunkText,chunk.markedTextStart);chunkText.push.apply(chunkText,chunk.markedTextEnd);});var textSizes=getTextMeasurements(chunkTexts,undefined,function(fragment,text){if(fragment instanceof Fragment){// it's a fragment!
// measure the fragment text position in pixels
var firstChar=fragment.from-fragment.chunk.from;if(firstChar<0){firstChar=0;dispatcher.post('messages',[[['<strong>WARNING</strong>'+'<br/> '+'The fragment ['+fragment.from+', '+fragment.to+'] ('+fragment.text+') is not '+'contained in its designated chunk ['+fragment.chunk.from+', '+fragment.chunk.to+'] most likely '+'due to the fragment starting or ending with a space, please '+'verify the sanity of your data since we are unable to '+'visualise this fragment correctly and will drop leading '+'space characters','warning',15]]]);}var startPos=text.getStartPositionOfChar(firstChar).x;var lastChar=fragment.to-fragment.chunk.from-1;var endPos=lastChar<0?startPos:text.getEndPositionOfChar(lastChar).x;fragment.curly={from:startPos,to:endPos};}else{// it's markedText [id, start?, char#, offset]
if(fragment[2]<0)fragment[2]=0;if(!fragment[2]){// start
fragment[3]=text.getStartPositionOfChar(fragment[2]).x;}else{fragment[3]=text.getEndPositionOfChar(fragment[2]-1).x+1;}}});// get the fragment annotation text sizes
var fragmentTexts={};var noSpans=true;$.each(data.spans,function(spanNo,span){$.each(span.fragments,function(fragmentNo,fragment){fragmentTexts[fragment.glyphedLabelText]=true;noSpans=false;});});if(noSpans)fragmentTexts.$=true;// dummy so we can at least get the height
var fragmentSizes=getTextMeasurements(fragmentTexts,{'class':'span'});return{texts:textSizes,fragments:fragmentSizes};};var addArcTextMeasurements=function addArcTextMeasurements(sizes){// get the arc annotation text sizes (for all labels)
var arcTexts={};$.each(data.arcs,function(arcNo,arc){var labels=Util.getArcLabels(spanTypes,data.spans[arc.origin].type,arc.type,relationTypesHash);if(!labels.length)labels=[arc.type];$.each(labels,function(labelNo,label){arcTexts[label]=true;});});var arcSizes=getTextMeasurements(arcTexts,{'class':'arcs'});sizes.arcs=arcSizes;};var adjustTowerAnnotationSizes=function adjustTowerAnnotationSizes(){// find biggest annotation in each tower
$.each(data.towers,function(towerNo,tower){var maxWidth=0;$.each(tower,function(fragmentNo,fragment){var width=data.sizes.fragments.widths[fragment.glyphedLabelText];if(width>maxWidth)maxWidth=width;});// tower
$.each(tower,function(fragmentNo,fragment){fragment.width=maxWidth;});// tower
});// data.towers
};var makeArrow=function makeArrow(defs,spec){var parsedSpec=spec.split(',');var type=parsedSpec[0];if(type=='none')return;var width=5;var height=5;var color="black";if($.isNumeric(parsedSpec[1])&&parsedSpec[2]){if($.isNumeric(parsedSpec[2])&&parsedSpec[3]){// 3 args, 2 numeric: assume width, height, color
width=parsedSpec[1];height=parsedSpec[2];color=parsedSpec[3]||'black';}else{// 2 args, 1 numeric: assume width/height, color
width=height=parsedSpec[1];color=parsedSpec[2]||'black';}}else{// other: assume color only
width=height=5;color=parsedSpec[1]||'black';}// hash needs to be replaced as IDs don't permit it.
var arrowId='arrow_'+spec.replace(/#/g,'').replace(/,/g,'_');var arrow;if(type=='triangle'){arrow=svg.marker(defs,arrowId,width,height/2,width,height,'auto',{markerUnits:'strokeWidth','fill':color});svg.polyline(arrow,[[0,0],[width,height/2],[0,height],[width/12,height/2]]);}return arrowId;};var drawing=false;var redraw=false;var renderDataReal=function renderDataReal(sourceData){Util.profileEnd('before render');Util.profileStart('render');Util.profileStart('init');if(!sourceData&&!data){dispatcher.post('doneRendering',[coll,doc,args]);return;}$svgDiv.show();if(sourceData&&sourceData.collection&&(sourceData.document!==doc||sourceData.collection!==coll)||drawing){redraw=true;dispatcher.post('doneRendering',[coll,doc,args]);return;}redraw=false;drawing=true;if(sourceData)setData(sourceData);showMtime();// clear the SVG
svg.clear(true);if(!data||data.length==0)return;// establish the width according to the enclosing element
canvasWidth=that.forceWidth||$svgDiv.width();var defs=addHeaderAndDefs();var backgroundGroup=svg.group({'class':'background'});var glowGroup=svg.group({'class':'glow'});highlightGroup=svg.group({'class':'highlight'});var textGroup=svg.group({'class':'text'});Util.profileEnd('init');Util.profileStart('measures');var sizes=getTextAndSpanTextMeasurements();data.sizes=sizes;adjustTowerAnnotationSizes();var maxTextWidth=0;for(var text in sizes.texts.widths){if(sizes.texts.widths.hasOwnProperty(text)){var width=sizes.texts.widths[text];if(width>maxTextWidth)maxTextWidth=width;}}Util.profileEnd('measures');Util.profileStart('chunks');var currentX=Configuration.visual.margin.x+sentNumMargin+rowPadding;var rows=[];var fragmentHeights=[];var sentenceToggle=0;var sentenceNumber=0;var row=new Row(svg);row.sentence=++sentenceNumber;row.backgroundIndex=sentenceToggle;row.index=0;var rowIndex=0;var twoBarWidths;// HACK to avoid measuring space's width
var openTextHighlights={};var textMarkedRows=[];addArcTextMeasurements(sizes);// reserve places for spans
var floors=[];var reservations=[];// reservations[chunk][floor] = [[from, to, headroom]...]
for(var i=0;i<=data.lastFragmentIndex;i++){reservation[i]={};}var inf=1.0/0.0;$.each(data.spanDrawOrderPermutation,function(spanIdNo,spanId){var span=data.spans[spanId];var f1=span.fragments[0];var f2=span.fragments[span.fragments.length-1];var x1=(f1.curly.from+f1.curly.to-f1.width)/2-Configuration.visual.margin.x;var i1=f1.chunk.index;var x2=(f2.curly.from+f2.curly.to+f2.width)/2+Configuration.visual.margin.x;var i2=f2.chunk.index;// Start from the ground level, going up floor by floor.
// If no more floors, make a new available one.
// If a floor is available and there is no carpet, mark it as carpet.
// If a floor is available and there is carpet and height
//   difference is at least fragment height + curly, OK.
// If a floor is not available, forget about carpet.
// --
// When OK, calculate exact ceiling.
// If there isn't one, make a new floor, copy reservations
//   from floor below (with decreased ceiling)
// Make the reservation from the carpet to just below the
//   current floor.
//
// TODO drawCurly and height could be prettified to only check
// actual positions of curlies
var carpet=0;var outside=true;var thisCurlyHeight=span.drawCurly?Configuration.visual.curlyHeight:0;var height=sizes.fragments.height+thisCurlyHeight+Configuration.visual.boxSpacing+2*Configuration.visual.margin.y-3;$.each(floors,function(floorNo,floor){var floorAvailable=true;for(var i=i1;i<=i2;i++){if(!(reservations[i]&&reservations[i][floor]))continue;var from=i==i1?x1:-inf;var to=i==i2?x2:inf;$.each(reservations[i][floor],function(resNo,res){if(res[0]<to&&from<res[1]){floorAvailable=false;return false;}});}if(floorAvailable){if(carpet===null){carpet=floor;}else if(height+carpet<=floor){// found our floor!
outside=false;return false;}}else{carpet=null;}});var reslen=reservations.length;var makeNewFloorIfNeeded=function makeNewFloorIfNeeded(floor){var floorNo=$.inArray(floor,floors);if(floorNo==-1){floors.push(floor);floors.sort(Util.cmp);floorNo=$.inArray(floor,floors);if(floorNo!=0){// copy reservations from the floor below
var parquet=floors[floorNo-1];for(var i=0;i<=reslen;i++){if(reservations[i]){if(!reservations[i][parquet]){reservations[i][parquet]=[];}var footroom=floor-parquet;$.each(reservations[i][parquet],function(resNo,res){if(res[2]>footroom){if(!reservations[i][floor]){reservations[i][floor]=[];}reservations[i][floor].push([res[0],res[1],res[2]-footroom]);}});}}}}return floorNo;};var ceiling=carpet+height;var ceilingNo=makeNewFloorIfNeeded(ceiling);var carpetNo=makeNewFloorIfNeeded(carpet);// make the reservation
var floor,floorNo;for(floorNo=carpetNo;(floor=floors[floorNo])!==undefined&&floor<ceiling;floorNo++){var headroom=ceiling-floor;for(var i=i1;i<=i2;i++){var from=i==i1?x1:0;var to=i==i2?x2:inf;if(!reservations[i])reservations[i]={};if(!reservations[i][floor])reservations[i][floor]=[];reservations[i][floor].push([from,to,headroom]);// XXX maybe add fragment; probably unnecessary
}}span.floor=carpet+thisCurlyHeight;});$.each(data.chunks,function(chunkNo,chunk){reservations=new Array();chunk.group=svg.group(row.group);chunk.highlightGroup=svg.group(chunk.group);var y=0;var minArcDist;var hasLeftArcs,hasRightArcs,hasInternalArcs;var hasAnnotations;var chunkFrom=Infinity;var chunkTo=0;var chunkHeight=0;var spacing=0;var spacingChunkId=null;var spacingRowBreak=0;$.each(chunk.fragments,function(fragmentNo,fragment){var span=fragment.span;var spanDesc=spanTypes[span.type];var bgColor=spanDesc&&spanDesc.bgColor||spanTypes.SPAN_DEFAULT&&spanTypes.SPAN_DEFAULT.bgColor||'#ffffff';var fgColor=spanDesc&&spanDesc.fgColor||spanTypes.SPAN_DEFAULT&&spanTypes.SPAN_DEFAULT.fgColor||'#000000';var borderColor=spanDesc&&spanDesc.borderColor||spanTypes.SPAN_DEFAULT&&spanTypes.SPAN_DEFAULT.borderColor||'#000000';// special case: if the border 'color' value is 'darken',
// then just darken the BG color a bit for the border.
if(borderColor=='darken'){borderColor=Util.adjustColorLightness(bgColor,-0.6);}fragment.group=svg.group(chunk.group,{'class':'span'});var fragmentHeight=0;if(!y)y=-sizes.texts.height;var x=(fragment.curly.from+fragment.curly.to)/2;// XXX is it maybe sizes.texts?
var yy=y+sizes.fragments.y;var hh=sizes.fragments.height;var ww=fragment.width;var xx=x-ww/2;// text margin fine-tuning
yy+=boxTextMargin.y;hh-=2*boxTextMargin.y;xx+=boxTextMargin.x;ww-=2*boxTextMargin.x;var rectClass='span_'+(span.cue||span.type)+' span_default';// TODO XXX first part unneeded I think; remove
// attach e.g. "False_positive" into the type
if(span.comment&&span.comment.type){rectClass+=' '+span.comment.type;}var bx=xx-Configuration.visual.margin.x-boxTextMargin.x;var by=yy-Configuration.visual.margin.y;var bw=ww+2*Configuration.visual.margin.x;var bh=hh+2*Configuration.visual.margin.y;if(roundCoordinates){x=(x|0)+0.5;bx=(bx|0)+0.5;}var shadowRect;var markedRect;if(span.marked){markedRect=svg.rect(chunk.highlightGroup,bx-markedSpanSize,by-markedSpanSize,bw+2*markedSpanSize,bh+2*markedSpanSize,{// filter: 'url(#Gaussian_Blur)',
'class':"shadow_EditHighlight",rx:markedSpanSize,ry:markedSpanSize});svg.other(markedRect,'animate',{'data-type':span.marked,attributeName:'fill',values:span.marked=='match'?highlightMatchSequence:highlightSpanSequence,dur:highlightDuration,repeatCount:'indefinite',begin:'indefinite'});chunkFrom=Math.min(bx-markedSpanSize,chunkFrom);chunkTo=Math.max(bx+bw+markedSpanSize,chunkTo);fragmentHeight=Math.max(bh+2*markedSpanSize,fragmentHeight);}// .match() removes unconfigured shadows, which were
// always showing up as black.
// TODO: don't hard-code configured shadowclasses.
if(span.shadowClass&&span.shadowClass.match('True_positive|False_positive|False_negative|AnnotationError|AnnotationWarning|AnnotatorNotes|Normalized|AnnotationIncomplete|AnnotationUnconfirmed|rectEditHighlight|EditHighlight_arc|MissingAnnotation|ChangedAnnotation ')){shadowRect=svg.rect(fragment.group,bx-rectShadowSize,by-rectShadowSize,bw+2*rectShadowSize,bh+2*rectShadowSize,{'class':'shadow_'+span.shadowClass,filter:'url(#Gaussian_Blur)',rx:rectShadowRounding,ry:rectShadowRounding});chunkFrom=Math.min(bx-rectShadowSize,chunkFrom);chunkTo=Math.max(bx+bw+rectShadowSize,chunkTo);fragmentHeight=Math.max(bh+2*rectShadowSize,fragmentHeight);}fragment.rect=svg.rect(fragment.group,bx,by,bw,bh,{'class':rectClass,fill:bgColor,stroke:borderColor,rx:Configuration.visual.margin.x,ry:Configuration.visual.margin.y,'data-span-id':span.id,'data-fragment-id':fragment.id,'strokeDashArray':span.attributeMerge.dashArray});// TODO XXX: quick nasty hack to allow normalizations
// to be marked visually; do something cleaner!
if(span.normalized){$(fragment.rect).addClass(span.normalized);}fragment.right=bx+bw;// TODO put it somewhere nicer?
if(!(span.shadowClass||span.marked)){chunkFrom=Math.min(bx,chunkFrom);chunkTo=Math.max(bx+bw,chunkTo);fragmentHeight=Math.max(bh,fragmentHeight);}fragment.rectBox={x:bx,y:by-span.floor,width:bw,height:bh};fragment.height=span.floor+hh+3*Configuration.visual.margin.y+Configuration.visual.curlyHeight+Configuration.visual.arcSpacing;var spacedTowerId=fragment.towerId*2;if(!fragmentHeights[spacedTowerId]||fragmentHeights[spacedTowerId]<fragment.height){fragmentHeights[spacedTowerId]=fragment.height;}$(fragment.rect).attr('y',yy-Configuration.visual.margin.y-span.floor);if(shadowRect){$(shadowRect).attr('y',yy-rectShadowSize-Configuration.visual.margin.y-span.floor);}if(markedRect){$(markedRect).attr('y',yy-markedSpanSize-Configuration.visual.margin.y-span.floor);}if(span.attributeMerge.box==="crossed"){svg.path(fragment.group,svg.createPath().move(xx,yy-Configuration.visual.margin.y-span.floor).line(xx+fragment.width,yy+hh+Configuration.visual.margin.y-span.floor),{'class':'boxcross'});svg.path(fragment.group,svg.createPath().move(xx+fragment.width,yy-Configuration.visual.margin.y-span.floor).line(xx,yy+hh+Configuration.visual.margin.y-span.floor),{'class':'boxcross'});}var fragmentText=svg.text(fragment.group,x,y-span.floor,data.spanAnnTexts[fragment.glyphedLabelText],{fill:fgColor});// Make curlies to show the fragment
if(fragment.drawCurly){var curlyColor='grey';if(coloredCurlies){var spanDesc=spanTypes[span.type];var bgColor=spanDesc&&spanDesc.bgColor||spanTypes.SPAN_DEFAULT&&spanTypes.SPAN_DEFAULT.fgColor||'#000000';curlyColor=Util.adjustColorLightness(bgColor,-0.6);}var bottom=yy+hh+Configuration.visual.margin.y-span.floor+1;svg.path(fragment.group,svg.createPath().move(fragment.curly.from,bottom+Configuration.visual.curlyHeight).curveC(fragment.curly.from,bottom,x,bottom+Configuration.visual.curlyHeight,x,bottom).curveC(x,bottom+Configuration.visual.curlyHeight,fragment.curly.to,bottom,fragment.curly.to,bottom+Configuration.visual.curlyHeight),{'class':'curly','stroke':curlyColor});chunkFrom=Math.min(fragment.curly.from,chunkFrom);chunkTo=Math.max(fragment.curly.to,chunkTo);fragmentHeight=Math.max(Configuration.visual.curlyHeight,fragmentHeight);}if(fragment==span.headFragment){// find the gap to fit the backwards arcs, but only on
// head fragment - other fragments don't have arcs
$.each(span.incoming,function(arcId,arc){var leftSpan=data.spans[arc.origin];var origin=leftSpan.headFragment.chunk;var border;if(chunk.index==origin.index){hasInternalArcs=true;}if(origin.row){var labels=Util.getArcLabels(spanTypes,leftSpan.type,arc.type,relationTypesHash);if(!labels.length)labels=[arc.type];if(origin.row.index==rowIndex){// same row, but before this
border=origin.translation.x+leftSpan.fragments[leftSpan.fragments.length-1].right;}else{border=Configuration.visual.margin.x+sentNumMargin+rowPadding;}var labelNo=Configuration.abbrevsOn?labels.length-1:0;var smallestLabelWidth=sizes.arcs.widths[labels[labelNo]]+2*minArcSlant;var gap=currentX+bx-border;var arcSpacing=smallestLabelWidth-gap;if(!hasLeftArcs||spacing<arcSpacing){spacing=arcSpacing;spacingChunkId=origin.index+1;}arcSpacing=smallestLabelWidth-bx;if(!hasLeftArcs||spacingRowBreak<arcSpacing){spacingRowBreak=arcSpacing;}hasLeftArcs=true;}else{hasRightArcs=true;}});$.each(span.outgoing,function(arcId,arc){var leftSpan=data.spans[arc.target];var target=leftSpan.headFragment.chunk;var border;if(target.row){var labels=Util.getArcLabels(spanTypes,span.type,arc.type,relationTypesHash);if(!labels.length)labels=[arc.type];if(target.row.index==rowIndex){// same row, but before this
border=target.translation.x+leftSpan.fragments[leftSpan.fragments.length-1].right;}else{border=Configuration.visual.margin.x+sentNumMargin+rowPadding;}var labelNo=Configuration.abbrevsOn?labels.length-1:0;var smallestLabelWidth=sizes.arcs.widths[labels[labelNo]]+2*minArcSlant;var gap=currentX+bx-border;var arcSpacing=smallestLabelWidth-gap;if(!hasLeftArcs||spacing<arcSpacing){spacing=arcSpacing;spacingChunkId=target.index+1;}arcSpacing=smallestLabelWidth-bx;if(!hasLeftArcs||spacingRowBreak<arcSpacing){spacingRowBreak=arcSpacing;}hasLeftArcs=true;}else{hasRightArcs=true;}});}fragmentHeight+=span.floor||Configuration.visual.curlyHeight;if(fragmentHeight>chunkHeight)chunkHeight=fragmentHeight;hasAnnotations=true;});// fragments
// positioning of the chunk
chunk.right=chunkTo;var textWidth=sizes.texts.widths[chunk.text];chunkHeight+=sizes.texts.height;var boxX=-Math.min(chunkFrom,0);var boxWidth=Math.max(textWidth,chunkTo)-Math.min(0,chunkFrom);// if (hasLeftArcs) {
// TODO change this with smallestLeftArc
// var spacing = arcHorizontalSpacing - (currentX - lastArcBorder);
// arc too small?
if(spacing>0)currentX+=spacing;// }
var rightBorderForArcs=hasRightArcs?arcHorizontalSpacing:hasInternalArcs?arcSlant:0;var lastX=currentX;var lastRow=row;if(chunk.sentence){while(sentenceNumber<chunk.sentence){sentenceNumber++;row.arcs=svg.group(row.group,{'class':'arcs'});rows.push(row);row=new Row(svg);sentenceToggle=1-sentenceToggle;row.backgroundIndex=sentenceToggle;row.index=++rowIndex;}sentenceToggle=1-sentenceToggle;}if(chunk.sentence||currentX+boxWidth+rightBorderForArcs>=canvasWidth-2*Configuration.visual.margin.x){// the chunk does not fit
row.arcs=svg.group(row.group,{'class':'arcs'});// TODO: related to issue #571
// replace arcHorizontalSpacing with a calculated value
currentX=Configuration.visual.margin.x+sentNumMargin+rowPadding+(hasLeftArcs?arcHorizontalSpacing:hasInternalArcs?arcSlant:0);if(hasLeftArcs){var adjustedCurTextWidth=sizes.texts.widths[chunk.text]+arcHorizontalSpacing;if(adjustedCurTextWidth>maxTextWidth){maxTextWidth=adjustedCurTextWidth;}}if(spacingRowBreak>0){currentX+=spacingRowBreak;spacing=0;// do not center intervening elements
}// new row
rows.push(row);svg.remove(chunk.group);row=new Row(svg);row.backgroundIndex=sentenceToggle;row.index=++rowIndex;svg.add(row.group,chunk.group);chunk.group=row.group.lastElementChild;$(chunk.group).children("g[class='span']").each(function(index,element){chunk.fragments[index].group=element;});$(chunk.group).find("rect[data-span-id]").each(function(index,element){chunk.fragments[index].rect=element;});}// break the text highlights when the row breaks
if(row.index!==lastRow.index){$.each(openTextHighlights,function(textId,textDesc){if(textDesc[3]!=lastX){var newDesc=[lastRow,textDesc[3],lastX+boxX,textDesc[4]];textMarkedRows.push(newDesc);}textDesc[3]=currentX;});}// open text highlights
$.each(chunk.markedTextStart,function(textNo,textDesc){textDesc[3]+=currentX+boxX;openTextHighlights[textDesc[0]]=textDesc;});// close text highlights
$.each(chunk.markedTextEnd,function(textNo,textDesc){textDesc[3]+=currentX+boxX;var startDesc=openTextHighlights[textDesc[0]];delete openTextHighlights[textDesc[0]];markedRow=[row,startDesc[3],textDesc[3],startDesc[4]];textMarkedRows.push(markedRow);});// XXX check this - is it used? should it be lastRow?
if(hasAnnotations)row.hasAnnotations=true;if(chunk.sentence){row.sentence=++sentenceNumber;}if(spacing>0){// if we added a gap, center the intervening elements
spacing/=2;var firstChunkInRow=row.chunks[row.chunks.length-1];if(spacingChunkId<firstChunkInRow.index){spacingChunkId=firstChunkInRow.index+1;}for(var chunkIndex=spacingChunkId;chunkIndex<chunk.index;chunkIndex++){var movedChunk=data.chunks[chunkIndex];translate(movedChunk,movedChunk.translation.x+spacing,0);movedChunk.textX+=spacing;}}row.chunks.push(chunk);chunk.row=row;translate(chunk,currentX+boxX,0);chunk.textX=currentX+boxX;var spaceWidth=0;var spaceLen=chunk.nextSpace&&chunk.nextSpace.length||0;for(var i=0;i<spaceLen;i++){spaceWidth+=spaceWidths[chunk.nextSpace[i]]||0;}currentX+=spaceWidth+boxWidth;});// chunks
// finish the last row
row.arcs=svg.group(row.group,{'class':'arcs'});rows.push(row);Util.profileEnd('chunks');Util.profileStart('arcsPrep');var arrows={};var arrow=makeArrow(defs,'none');if(arrow)arrows['none']=arrow;var len=fragmentHeights.length;for(var i=0;i<len;i++){if(!fragmentHeights[i]||fragmentHeights[i]<Configuration.visual.arcStartHeight){fragmentHeights[i]=Configuration.visual.arcStartHeight;}}// find out how high the arcs have to go
$.each(data.arcs,function(arcNo,arc){arc.jumpHeight=0;var fromFragment=data.spans[arc.origin].headFragment;var toFragment=data.spans[arc.target].headFragment;if(fromFragment.towerId>toFragment.towerId){var tmp=fromFragment;fromFragment=toFragment;toFragment=tmp;}var from,to;if(fromFragment.chunk.index==toFragment.chunk.index){from=fromFragment.towerId;to=toFragment.towerId;}else{from=fromFragment.towerId+1;to=toFragment.towerId-1;}for(var i=from;i<=to;i++){if(arc.jumpHeight<fragmentHeights[i*2])arc.jumpHeight=fragmentHeights[i*2];}});// sort the arcs
data.arcs.sort(function(a,b){// first write those that have less to jump over
var tmp=a.jumpHeight-b.jumpHeight;if(tmp)return tmp<0?-1:1;// if equal, then those that span less distance
tmp=a.dist-b.dist;if(tmp)return tmp<0?-1:1;// if equal, then those where heights of the targets are smaller
tmp=data.spans[a.origin].headFragment.height+data.spans[a.target].headFragment.height-data.spans[b.origin].headFragment.height-data.spans[b.target].headFragment.height;if(tmp)return tmp<0?-1:1;// if equal, then those with the lower origin
tmp=data.spans[a.origin].headFragment.height-data.spans[b.origin].headFragment.height;if(tmp)return tmp<0?-1:1;// if equal, they're just equal.
return 0;});// draw the drag arc marker
var arrowhead=svg.marker(defs,'drag_arrow',5,2.5,5,5,'auto',{markerUnits:'strokeWidth','class':'drag_fill'});svg.polyline(arrowhead,[[0,0],[5,2.5],[0,5],[0.2,2.5]]);Util.profileEnd('arcsPrep');Util.profileStart('arcs');// add the arcs
$.each(data.arcs,function(arcNo,arc){// separate out possible numeric suffix from type
var noNumArcType;var splitArcType;if(arc.type){splitArcType=arc.type.match(/^(.*?)(\d*)$/);noNumArcType=splitArcType[1];}var originSpan=data.spans[arc.origin];var targetSpan=data.spans[arc.target];var leftToRight=originSpan.headFragment.towerId<targetSpan.headFragment.towerId;var left,right;if(leftToRight){left=originSpan.headFragment;right=targetSpan.headFragment;}else{left=targetSpan.headFragment;right=originSpan.headFragment;}var spanDesc=spanTypes[originSpan.type];// TODO: might make more sense to reformat this as dict instead
// of searching through the list every type
var arcDesc;if(spanDesc&&spanDesc.arcs){$.each(spanDesc.arcs,function(arcDescNo,arcDescIter){if(arcDescIter.type==arc.type){arcDesc=arcDescIter;}});}// fall back on unnumbered type if not found in full
if(!arcDesc&&noNumArcType&&noNumArcType!=arc.type&&spanDesc&&spanDesc.arcs){$.each(spanDesc.arcs,function(arcDescNo,arcDescIter){if(arcDescIter.type==noNumArcType){arcDesc=arcDescIter;}});}// fall back on relation types in case we still don't have
// an arc description, with final fallback to unnumbered relation
if(!arcDesc){arcDesc=$.extend({},relationTypesHash[arc.type]||relationTypesHash[noNumArcType]);}var color=arcDesc&&arcDesc.color||spanTypes.ARC_DEFAULT&&spanTypes.ARC_DEFAULT.color||'#000000';var symmetric=arcDesc&&arcDesc.properties&&arcDesc.properties.symmetric;var dashArray=arcDesc&&arcDesc.dashArray;var arrowHead=(arcDesc&&arcDesc.arrowHead||spanTypes.ARC_DEFAULT&&spanTypes.ARC_DEFAULT.arrowHead||'triangle,5')+','+color;var labelArrowHead=(arcDesc&&arcDesc.labelArrow||spanTypes.ARC_DEFAULT&&spanTypes.ARC_DEFAULT.labelArrow||'triangle,5')+','+color;var leftBox=rowBBox(left);var rightBox=rowBBox(right);var leftRow=left.chunk.row.index;var rightRow=right.chunk.row.index;if(!arrows[arrowHead]){var arrow=makeArrow(defs,arrowHead);if(arrow)arrows[arrowHead]=arrow;}if(!arrows[labelArrowHead]){var arrow=makeArrow(defs,labelArrowHead);if(arrow)arrows[labelArrowHead]=arrow;}// find the next height
var height=0;var fromIndex2,toIndex2;if(left.chunk.index==right.chunk.index){fromIndex2=left.towerId*2;toIndex2=right.towerId*2;}else{fromIndex2=left.towerId*2+1;toIndex2=right.towerId*2-1;}for(var i=fromIndex2;i<=toIndex2;i++){if(fragmentHeights[i]>height)height=fragmentHeights[i];}height+=Configuration.visual.arcSpacing;var leftSlantBound,rightSlantBound;for(var i=fromIndex2;i<=toIndex2;i++){if(fragmentHeights[i]<height)fragmentHeights[i]=height;}// Adjust the height to align with pixels when rendered
// TODO: on at least Chrome, this doesn't make a difference:
// the lines come out pixel-width even without it. Check.
height+=0.5;var chunkReverse=false;var ufoCatcher=originSpan.headFragment.chunk.index==targetSpan.headFragment.chunk.index;if(ufoCatcher){chunkReverse=leftBox.x+leftBox.width/2<rightBox.x+rightBox.width/2;}var ufoCatcherMod=ufoCatcher?chunkReverse?-0.5:0.5:1;for(var rowIndex=leftRow;rowIndex<=rightRow;rowIndex++){var row=rows[rowIndex];row.hasAnnotations=true;var arcGroup=svg.group(row.arcs,{'data-from':arc.origin,'data-to':arc.target});var from,to;if(rowIndex==leftRow){from=leftBox.x+(chunkReverse?0:leftBox.width);}else{from=sentNumMargin;}if(rowIndex==rightRow){to=rightBox.x+(chunkReverse?rightBox.width:0);}else{to=canvasWidth-2*Configuration.visual.margin.y;}var originType=data.spans[arc.origin].type;var arcLabels=Util.getArcLabels(spanTypes,originType,arc.type,relationTypesHash);var labelText=Util.arcDisplayForm(spanTypes,originType,arc.type,relationTypesHash);// if (Configuration.abbrevsOn && !ufoCatcher && arcLabels) {
if(Configuration.abbrevsOn&&arcLabels){var labelIdx=1;// first abbreviation
// strictly speaking 2*arcSlant would be needed to allow for
// the full-width arcs to fit, but judged unabbreviated text
// to be more important than the space for arcs.
var maxLength=to-from-arcSlant;while(sizes.arcs.widths[labelText]>maxLength&&arcLabels[labelIdx]){labelText=arcLabels[labelIdx];labelIdx++;}}var shadowGroup;if(arc.shadowClass||arc.marked){shadowGroup=svg.group(arcGroup);}var options={'fill':color,'data-arc-role':arc.type,'data-arc-origin':arc.origin,'data-arc-target':arc.target,// TODO: confirm this is unused and remove.
//'data-arc-id': arc.id,
'data-arc-ed':arc.eventDescId};// construct SVG text, showing possible trailing index
// numbers (as in e.g. "Theme2") as subscripts
var svgText;if(!splitArcType[2]){// no subscript, simple string suffices
svgText=labelText;}else{// Need to parse out possible numeric suffixes to avoid
// duplicating number in label and its subscript
var splitLabelText=labelText.match(/^(.*?)(\d*)$/);var noNumLabelText=splitLabelText[1];svgText=svg.createText();// TODO: to address issue #453, attaching options also
// to spans, not only primary text. Make sure there
// are no problems with this.
svgText.span(noNumLabelText,options);var subscriptSettings={'dy':'0.3em','font-size':'80%'};// alternate possibility
//                 var subscriptSettings = {
//                   'baseline-shift': 'sub',
//                   'font-size': '80%'
//                 };
$.extend(subscriptSettings,options);svgText.span(splitArcType[2],subscriptSettings);}// guess at the correct baseline shift to get vertical centering.
// (CSS dominant-baseline can't be used as not all SVG rendereds support it.)
var baseline_shift=sizes.arcs.height/4;var text=svg.text(arcGroup,(from+to)/2,-height+baseline_shift,svgText,options);var width=sizes.arcs.widths[labelText];var textBox={x:(from+to-width)/2,width:width,y:-height-sizes.arcs.height/2,height:sizes.arcs.height};if(arc.marked){var markedRect=svg.rect(shadowGroup,textBox.x-markedArcSize,textBox.y-markedArcSize,textBox.width+2*markedArcSize,textBox.height+2*markedArcSize,{// filter: 'url(#Gaussian_Blur)',
'class':"shadow_EditHighlight",rx:markedArcSize,ry:markedArcSize});svg.other(markedRect,'animate',{'data-type':arc.marked,attributeName:'fill',values:arc.marked=='match'?highlightMatchSequence:highlightArcSequence,dur:highlightDuration,repeatCount:'indefinite',begin:'indefinite'});}if(arc.shadowClass){svg.rect(shadowGroup,textBox.x-arcLabelShadowSize,textBox.y-arcLabelShadowSize,textBox.width+2*arcLabelShadowSize,textBox.height+2*arcLabelShadowSize,{'class':'shadow_'+arc.shadowClass,filter:'url(#Gaussian_Blur)',rx:arcLabelShadowRounding,ry:arcLabelShadowRounding});}var textStart=textBox.x;var textEnd=textBox.x+textBox.width;// adjust by margin for arc drawing
textStart-=Configuration.visual.arcTextMargin;textEnd+=Configuration.visual.arcTextMargin;if(from>to){var tmp=textStart;textStart=textEnd;textEnd=tmp;}var path;if(roundCoordinates){// don't ask
height=(height|0)+0.5;}if(height>row.maxArcHeight)row.maxArcHeight=height;var myArrowHead=arcDesc&&arcDesc.arrowHead||spanTypes.ARC_DEFAULT&&spanTypes.ARC_DEFAULT.arrowHead;var arrowName=(leftToRight?symmetric&&myArrowHead||'none':myArrowHead||'triangle,5')+','+color;var arrowType=arrows[arrowName];var arrowDecl=arrowType&&'url(#'+arrowType+')';var arrowAtLabelAdjust=0;var labelArrowDecl=null;var myLabelArrowHead=arcDesc&&arcDesc.labelArrow||spanTypes.ARC_DEFAULT&&spanTypes.ARC_DEFAULT.labelArrow;if(myLabelArrowHead){var labelArrowName=(leftToRight?symmetric&&myLabelArrowHead||'none':myLabelArrowHead||'triangle,5')+','+color;var labelArrowSplit=labelArrowName.split(',');arrowAtLabelAdjust=labelArrowSplit[0]!='none'&&parseInt(labelArrowSplit[1],10)||0;var labelArrowType=arrows[labelArrowName];var labelArrowDecl=labelArrowType&&'url(#'+labelArrowType+')';if(ufoCatcher)arrowAtLabelAdjust=-arrowAtLabelAdjust;}var arrowStart=textStart-arrowAtLabelAdjust;path=svg.createPath().move(arrowStart,-height);if(rowIndex==leftRow){var cornerx=from+ufoCatcherMod*arcSlant;// for normal cases, should not be past textStart even if narrow
if(!ufoCatcher&&cornerx>arrowStart-1){cornerx=arrowStart-1;}if(smoothArcCurves){var controlx=ufoCatcher?cornerx+2*ufoCatcherMod*reverseArcControlx:smoothArcSteepness*from+(1-smoothArcSteepness)*cornerx;var endy=leftBox.y+(leftToRight||arc.equiv?leftBox.height/2:Configuration.visual.margin.y);// no curving for short lines covering short vertical
// distances, the arrowheads can go off (#925)
if(Math.abs(-height-endy)<2&&Math.abs(cornerx-from)<5){endy=-height;}line=path.line(cornerx,-height).curveQ(controlx,-height,from,endy);}else{path.line(cornerx,-height).line(from,leftBox.y+(leftToRight||arc.equiv?leftBox.height/2:Configuration.visual.margin.y));}}else{path.line(from,-height);}svg.path(arcGroup,path,{markerEnd:arrowDecl,markerStart:labelArrowDecl,style:'stroke: '+color,'strokeDashArray':dashArray});if(arc.marked){svg.path(shadowGroup,path,{'class':'shadow_EditHighlight_arc',strokeWidth:markedArcStroke,'strokeDashArray':dashArray});svg.other(markedRect,'animate',{'data-type':arc.marked,attributeName:'fill',values:arc.marked=='match'?highlightMatchSequence:highlightArcSequence,dur:highlightDuration,repeatCount:'indefinite',begin:'indefinite'});}if(arc.shadowClass){svg.path(shadowGroup,path,{'class':'shadow_'+arc.shadowClass,strokeWidth:shadowStroke,'strokeDashArray':dashArray});}var myArrowHead=arcDesc&&arcDesc.arrowHead||spanTypes.ARC_DEFAULT&&spanTypes.ARC_DEFAULT.arrowHead;var arrowName=(leftToRight?myArrowHead||'triangle,5':symmetric&&myArrowHead||'none')+','+color;var arrowType=arrows[arrowName];var arrowDecl=arrowType&&'url(#'+arrowType+')';var arrowAtLabelAdjust=0;var labelArrowDecl=null;var myLabelArrowHead=arcDesc&&arcDesc.labelArrow||spanTypes.ARC_DEFAULT&&spanTypes.ARC_DEFAULT.labelArrow;if(myLabelArrowHead){var labelArrowName=(leftToRight?myLabelArrowHead||'triangle,5':symmetric&&myLabelArrowHead||'none')+','+color;var labelArrowSplit=labelArrowName.split(',');arrowAtLabelAdjust=labelArrowSplit[0]!='none'&&parseInt(labelArrowSplit[1],10)||0;var labelArrowType=arrows[labelArrowName];var labelArrowDecl=labelArrowType&&'url(#'+labelArrowType+')';if(ufoCatcher)arrowAtLabelAdjust=-arrowAtLabelAdjust;}var arrowEnd=textEnd+arrowAtLabelAdjust;path=svg.createPath().move(arrowEnd,-height);if(rowIndex==rightRow){var cornerx=to-ufoCatcherMod*arcSlant;// TODO: duplicates above in part, make funcs
// for normal cases, should not be past textEnd even if narrow
if(!ufoCatcher&&cornerx<arrowEnd+1){cornerx=arrowEnd+1;}if(smoothArcCurves){var controlx=ufoCatcher?cornerx-2*ufoCatcherMod*reverseArcControlx:smoothArcSteepness*to+(1-smoothArcSteepness)*cornerx;var endy=rightBox.y+(leftToRight&&!arc.equiv?Configuration.visual.margin.y:rightBox.height/2);// no curving for short lines covering short vertical
// distances, the arrowheads can go off (#925)
if(Math.abs(-height-endy)<2&&Math.abs(cornerx-to)<5){endy=-height;}path.line(cornerx,-height).curveQ(controlx,-height,to,endy);}else{path.line(cornerx,-height).line(to,rightBox.y+(leftToRight&&!arc.equiv?Configuration.visual.margin.y:rightBox.height/2));}}else{path.line(to,-height);}svg.path(arcGroup,path,{markerEnd:arrowDecl,markerStart:labelArrowDecl,style:'stroke: '+color,'strokeDashArray':dashArray});if(arc.marked){svg.path(shadowGroup,path,{'class':'shadow_EditHighlight_arc',strokeWidth:markedArcStroke,'strokeDashArray':dashArray});}if(shadowGroup){svg.path(shadowGroup,path,{'class':'shadow_'+arc.shadowClass,strokeWidth:shadowStroke,'strokeDashArray':dashArray});}}// arc rows
});// arcs
Util.profileEnd('arcs');Util.profileStart('fragmentConnectors');$.each(data.spans,function(spanNo,span){var numConnectors=span.fragments.length-1;for(var connectorNo=0;connectorNo<numConnectors;connectorNo++){var left=span.fragments[connectorNo];var right=span.fragments[connectorNo+1];var leftBox=rowBBox(left);var rightBox=rowBBox(right);var leftRow=left.chunk.row.index;var rightRow=right.chunk.row.index;for(var rowIndex=leftRow;rowIndex<=rightRow;rowIndex++){var row=rows[rowIndex];row.hasAnnotations=true;if(rowIndex==leftRow){from=leftBox.x+leftBox.width;}else{from=sentNumMargin;}if(rowIndex==rightRow){to=rightBox.x;}else{to=canvasWidth-2*Configuration.visual.margin.y;}var height=leftBox.y+leftBox.height-Configuration.visual.margin.y;if(roundCoordinates){// don't ask
height=(height|0)+0.5;}var path=svg.createPath().move(from,height).line(to,height);svg.path(row.arcs,path,{style:'stroke: '+fragmentConnectorColor,'strokeDashArray':fragmentConnectorDashArray});}// rowIndex
}// connectorNo
});// spans
Util.profileEnd('fragmentConnectors');Util.profileStart('rows');// position the rows
var y=Configuration.visual.margin.y;var sentNumGroup=svg.group({'class':'sentnum'});var currentSent;$.each(rows,function(rowId,row){$.each(row.chunks,function(chunkId,chunk){$.each(chunk.fragments,function(fragmentId,fragment){if(row.maxSpanHeight<fragment.height)row.maxSpanHeight=fragment.height;});});if(row.sentence){currentSent=row.sentence;}// SLOW (#724) and replaced with calculations:
//
// var rowBox = row.group.getBBox();
// // Make it work on IE
// rowBox = { x: rowBox.x, y: rowBox.y, height: rowBox.height, width: rowBox.width };
// // Make it work on Firefox and Opera
// if (rowBox.height == -Infinity) {
//   rowBox = { x: 0, y: 0, height: 0, width: 0 };
// }
// XXX TODO HACK: find out where 5 and 1.5 come from!
// This is the fix for #724, but the numbers are guessed.
var rowBoxHeight=Math.max(row.maxArcHeight+5,row.maxSpanHeight+1.5);// XXX TODO HACK: why 5, 1.5?
if(row.hasAnnotations){// rowBox.height = -rowBox.y + rowSpacing;
rowBoxHeight+=rowSpacing+1.5;// XXX TODO HACK: why 1.5?
}else{rowBoxHeight-=5;// XXX TODO HACK: why -5?
}rowBoxHeight+=rowPadding;var bgClass;if(data.markedSent[currentSent]){// specifically highlighted
bgClass='backgroundHighlight';}else if(Configuration.textBackgrounds=="striped"){// give every other sentence a different bg class
bgClass='background'+row.backgroundIndex;}else{// plain "standard" bg
bgClass='background0';}svg.rect(backgroundGroup,0,y+sizes.texts.y+sizes.texts.height,canvasWidth,rowBoxHeight+sizes.texts.height+1,{'class':bgClass});y+=rowBoxHeight;y+=sizes.texts.height;row.textY=y-rowPadding;if(row.sentence){var sentence_hash=new URLHash(coll,doc,{focus:[['sent',row.sentence]]});var link=svg.link(sentNumGroup,sentence_hash.getHash());var text=svg.text(link,sentNumMargin-Configuration.visual.margin.x,y-rowPadding,''+row.sentence,{'data-sent':row.sentence});var sentComment=data.sentComment[row.sentence];if(sentComment){var box=text.getBBox();svg.remove(text);// TODO: using rectShadowSize, but this shadow should
// probably have its own setting for shadow size
shadowRect=svg.rect(sentNumGroup,box.x-rectShadowSize,box.y-rectShadowSize,box.width+2*rectShadowSize,box.height+2*rectShadowSize,{'class':'shadow_'+sentComment.type,filter:'url(#Gaussian_Blur)',rx:rectShadowRounding,ry:rectShadowRounding,'data-sent':row.sentence});var text=svg.text(sentNumGroup,sentNumMargin-Configuration.visual.margin.x,y-rowPadding,''+row.sentence,{'data-sent':row.sentence});}}var rowY=y-rowPadding;if(roundCoordinates){rowY=rowY|0;}translate(row,0,rowY);y+=Configuration.visual.margin.y;});y+=Configuration.visual.margin.y;Util.profileEnd('rows');Util.profileStart('chunkFinish');// chunk index sort functions for overlapping fragment drawing
// algorithm; first for left-to-right pass, sorting primarily
// by start offset, second for right-to-left pass by end
// offset. Secondary sort by fragment length in both cases.
var currentChunk;var lrChunkComp=function lrChunkComp(a,b){var ac=currentChunk.fragments[a];var bc=currentChunk.fragments[b];var startDiff=Util.cmp(ac.from,bc.from);return startDiff!=0?startDiff:Util.cmp(bc.to-bc.from,ac.to-ac.from);};var rlChunkComp=function rlChunkComp(a,b){var ac=currentChunk.fragments[a];var bc=currentChunk.fragments[b];var endDiff=Util.cmp(bc.to,ac.to);return endDiff!=0?endDiff:Util.cmp(bc.to-bc.from,ac.to-ac.from);};var sentenceText=null;$.each(data.chunks,function(chunkNo,chunk){// context for sort
currentChunk=chunk;// text rendering
if(chunk.sentence){if(sentenceText){// svg.text(textGroup, sentenceText); // avoids jQuerySVG bug
svg.text(textGroup,0,0,sentenceText);}sentenceText=null;}if(!sentenceText){sentenceText=svg.createText();}var nextChunk=data.chunks[chunkNo+1];var nextSpace=nextChunk?nextChunk.space:'';sentenceText.span(/*chunk.space +*/chunk.text+nextSpace,{x:chunk.textX,y:chunk.row.textY,'data-chunk-id':chunk.index});// chunk backgrounds
if(chunk.fragments.length){var orderedIdx=[];for(var i=chunk.fragments.length-1;i>=0;i--){orderedIdx.push(i);}// Mark entity nesting height/depth (number of
// nested/nesting entities). To account for crossing
// brackets in a (mostly) reasonable way, determine
// depth/height separately in a left-to-right traversal
// and a right-to-left traversal.
orderedIdx.sort(lrChunkComp);var openFragments=[];for(var i=0;i<orderedIdx.length;i++){var current=chunk.fragments[orderedIdx[i]];current.nestingHeightLR=0;current.nestingDepthLR=0;var stillOpen=[];for(var o=0;o<openFragments.length;o++){if(openFragments[o].to>current.from){stillOpen.push(openFragments[o]);openFragments[o].nestingHeightLR++;}}openFragments=stillOpen;current.nestingDepthLR=openFragments.length;openFragments.push(current);}// re-sort for right-to-left traversal by end position
orderedIdx.sort(rlChunkComp);openFragments=[];for(var i=0;i<orderedIdx.length;i++){var current=chunk.fragments[orderedIdx[i]];current.nestingHeightRL=0;current.nestingDepthRL=0;var stillOpen=[];for(var o=0;o<openFragments.length;o++){if(openFragments[o].from<current.to){stillOpen.push(openFragments[o]);openFragments[o].nestingHeightRL++;}}openFragments=stillOpen;current.nestingDepthRL=openFragments.length;openFragments.push(current);}// the effective depth and height are the max of those
// for the left-to-right and right-to-left traversals.
for(var i=0;i<orderedIdx.length;i++){var c=chunk.fragments[orderedIdx[i]];c.nestingHeight=c.nestingHeightLR>c.nestingHeightRL?c.nestingHeightLR:c.nestingHeightRL;c.nestingDepth=c.nestingDepthLR>c.nestingDepthRL?c.nestingDepthLR:c.nestingDepthRL;}// Re-order by nesting height and draw in order
orderedIdx.sort(function(a,b){return Util.cmp(chunk.fragments[b].nestingHeight,chunk.fragments[a].nestingHeight);});for(var i=0;i<chunk.fragments.length;i++){var fragment=chunk.fragments[orderedIdx[i]];var spanDesc=spanTypes[fragment.span.type];var bgColor=spanDesc&&spanDesc.bgColor||spanTypes.SPAN_DEFAULT&&spanTypes.SPAN_DEFAULT.bgColor||'#ffffff';// Tweak for nesting depth/height. Recognize just three
// levels for now: normal, nested, and nesting, where
// nested+nesting yields normal. (Currently testing
// minor tweak: don't shrink for depth 1 as the nesting
// highlight will grow anyway [check nestingDepth > 1])
var shrink=0;if(fragment.nestingDepth>1&&fragment.nestingHeight==0){shrink=1;}else if(fragment.nestingDepth==0&&fragment.nestingHeight>0){shrink=-1;}var yShrink=shrink*nestingAdjustYStepSize;var xShrink=shrink*nestingAdjustXStepSize;// bit lighter
var lightBgColor=Util.adjustColorLightness(bgColor,0.8);// tweak for Y start offset (and corresponding height
// reduction): text rarely hits font max height, so this
// tends to look better
var yStartTweak=1;// store to have same mouseover highlight without recalc
fragment.highlightPos={x:chunk.textX+fragment.curly.from+xShrink,y:chunk.row.textY+sizes.texts.y+yShrink+yStartTweak,w:fragment.curly.to-fragment.curly.from-2*xShrink,h:sizes.texts.height-2*yShrink-yStartTweak};svg.rect(highlightGroup,fragment.highlightPos.x,fragment.highlightPos.y,fragment.highlightPos.w,fragment.highlightPos.h,{fill:lightBgColor,//opacity:1,
rx:highlightRounding.x,ry:highlightRounding.y});}}});if(sentenceText){// svg.text(textGroup, sentenceText); // avoids jQuerySVG bug
svg.text(textGroup,0,0,sentenceText);}// draw the markedText
$.each(textMarkedRows,function(textRowNo,textRowDesc){// row, from, to
var textHighlight=svg.rect(highlightGroup,textRowDesc[1]-2,textRowDesc[0].textY-sizes.fragments.height,textRowDesc[2]-textRowDesc[1]+4,sizes.fragments.height+4,{fill:'yellow'// TODO: put into css file, as default - turn into class
});// NOTE: changing highlightTextSequence here will give
// different-colored highlights
// TODO: entirely different settings for non-animations?
var markedType=textRowDesc[3];svg.other(textHighlight,'animate',{'data-type':markedType,attributeName:'fill',values:markedType=='match'?highlightMatchSequence:highlightTextSequence,dur:highlightDuration,repeatCount:'indefinite',begin:'indefinite'});});Util.profileEnd('chunkFinish');Util.profileStart('finish');svg.path(sentNumGroup,svg.createPath().move(sentNumMargin,0).line(sentNumMargin,y));// resize the SVG
var width=maxTextWidth+sentNumMargin+2*Configuration.visual.margin.x+1;if(width>canvasWidth)canvasWidth=width;$svg.width(canvasWidth);$svg.height(y);$svgDiv.height(y);Util.profileEnd('finish');Util.profileEnd('render');Util.profileReport();drawing=false;if(redraw){redraw=false;renderDataReal();}$svg.find('animate').each(function(){if(this.beginElement){// protect against non-SMIL browsers
this.beginElement();}});dispatcher.post('doneRendering',[coll,doc,args]);};var renderErrors={unableToReadTextFile:true,annotationFileNotFound:true,isDirectoryError:true};var renderData=function renderData(sourceData){Util.profileEnd('invoke getDocument');if(sourceData&&sourceData.exception){if(renderErrors[sourceData.exception]){dispatcher.post('renderError:'+sourceData.exception,[sourceData]);}else{dispatcher.post('unknownError',[sourceData.exception]);}}else{// Fill in default values that don't necessarily go over the protocol
if(sourceData){setSourceDataDefaults(sourceData);}dispatcher.post('startedRendering',[coll,doc,args]);dispatcher.post('spin');setTimeout(function(){try{renderDataReal(sourceData);}catch(e){// We are sure not to be drawing anymore, reset the state
drawing=false;// TODO: Hook printout into dispatch elsewhere?
console.warn('Rendering terminated due to:',e);dispatcher.post('renderError: Fatal',[sourceData,e]);}dispatcher.post('unspin');},0);}};var renderDocument=function renderDocument(){Util.profileStart('invoke getDocument');dispatcher.post('ajax',[{action:'getDocument',collection:coll,'document':doc},'renderData',{collection:coll,'document':doc}]);};var triggerRender=function triggerRender(){if(svg&&(isRenderRequested&&isCollectionLoaded||requestedData)&&Visualizer.areFontsLoaded){isRenderRequested=false;if(requestedData){Util.profileClear();Util.profileStart('before render');renderData(requestedData);}else if(doc.length){Util.profileClear();Util.profileStart('before render');renderDocument();}else{dispatcher.post(0,'renderError:noFileSpecified');}}};var requestRenderData=function requestRenderData(sourceData){requestedData=sourceData;triggerRender();};var collectionChanged=function collectionChanged(){isCollectionLoaded=false;};var gotCurrent=function gotCurrent(_coll,_doc,_args,reloadData){coll=_coll;doc=_doc;args=_args;if(reloadData){isRenderRequested=true;triggerRender();}};// event handlers
var highlight,highlightArcs,highlightSpans,commentId;var onMouseOver=function onMouseOver(evt){var target=$(evt.target);var id;if(id=target.attr('data-span-id')){commentId=id;var span=data.spans[id];dispatcher.post('displaySpanComment',[evt,target,id,span.type,span.attributeText,span.text,span.comment&&span.comment.text,span.comment&&span.comment.type,span.normalizations]);var spanDesc=spanTypes[span.type];var bgColor=spanDesc&&spanDesc.bgColor||spanTypes.SPAN_DEFAULT&&spanTypes.SPAN_DEFAULT.bgColor||'#ffffff';highlight=[];$.each(span.fragments,function(fragmentNo,fragment){highlight.push(svg.rect(highlightGroup,fragment.highlightPos.x,fragment.highlightPos.y,fragment.highlightPos.w,fragment.highlightPos.h,{'fill':bgColor,opacity:0.75,rx:highlightRounding.x,ry:highlightRounding.y}));});if(that.arcDragOrigin){target.parent().addClass('highlight');}else{highlightArcs=$svg.find('g[data-from="'+id+'"], g[data-to="'+id+'"]').addClass('highlight');var spans={};spans[id]=true;var spanIds=[];$.each(span.incoming,function(arcNo,arc){spans[arc.origin]=true;});$.each(span.outgoing,function(arcNo,arc){spans[arc.target]=true;});$.each(spans,function(spanId,dummy){spanIds.push('rect[data-span-id="'+spanId+'"]');});highlightSpans=$svg.find(spanIds.join(', ')).parent().addClass('highlight');}forceRedraw();}else if(!that.arcDragOrigin&&(id=target.attr('data-arc-role'))){var originSpanId=target.attr('data-arc-origin');var targetSpanId=target.attr('data-arc-target');var role=target.attr('data-arc-role');var symmetric=relationTypesHash&&relationTypesHash[role]&&relationTypesHash[role].properties&&relationTypesHash[role].properties.symmetric;// NOTE: no commentText, commentType for now
var arcEventDescId=target.attr('data-arc-ed');var commentText='';var commentType='';var arcId;if(arcEventDescId){var eventDesc=data.eventDescs[arcEventDescId];var comment=eventDesc.comment;if(comment){commentText=comment.text;commentType=comment.type;if(commentText==''&&commentType){// default to type if missing text
commentText=commentType;}}if(eventDesc.relation){// among arcs, only ones corresponding to relations have
// "independent" IDs
arcId=arcEventDescId;}}var originSpanType=data.spans[originSpanId].type||'';var targetSpanType=data.spans[targetSpanId].type||'';dispatcher.post('displayArcComment',[evt,target,symmetric,arcId,originSpanId,originSpanType,role,targetSpanId,targetSpanType,commentText,commentType]);highlightArcs=$svg.find('g[data-from="'+originSpanId+'"][data-to="'+targetSpanId+'"]').addClass('highlight');highlightSpans=$($svg).find('rect[data-span-id="'+originSpanId+'"], rect[data-span-id="'+targetSpanId+'"]').parent().addClass('highlight');}else if(id=target.attr('data-sent')){var comment=data.sentComment[id];if(comment){dispatcher.post('displaySentComment',[evt,target,comment.text,comment.type]);}}};var onMouseOut=function onMouseOut(evt){var target=$(evt.target);target.removeClass('badTarget');dispatcher.post('hideComment');if(highlight){$.each(highlight,function(){svg.remove(this);});highlight=undefined;}if(highlightSpans){highlightArcs.removeClass('highlight');highlightSpans.removeClass('highlight');highlightSpans=undefined;}forceRedraw();};var setAbbrevs=function setAbbrevs(_abbrevsOn){// TODO: this is a slightly weird place to tweak the configuration
Configuration.abbrevsOn=_abbrevsOn;dispatcher.post('configurationChanged');};var setTextBackgrounds=function setTextBackgrounds(_textBackgrounds){Configuration.textBackgrounds=_textBackgrounds;dispatcher.post('configurationChanged');};var setLayoutDensity=function setLayoutDensity(_density){//dispatcher.post('messages', [[['Setting layout density ' + _density, 'comment']]]);
// TODO: store standard settings instead of hard-coding
// them here (again)
if(_density<2){// dense
Configuration.visual.margin={x:1,y:0};Configuration.visual.boxSpacing=1;Configuration.visual.curlyHeight=1;Configuration.visual.arcSpacing=7;Configuration.visual.arcStartHeight=18;}else if(_density>2){// spacious
Configuration.visual.margin={x:2,y:1};Configuration.visual.boxSpacing=3;Configuration.visual.curlyHeight=6;Configuration.visual.arcSpacing=12;Configuration.visual.arcStartHeight=23;}else{// standard
Configuration.visual.margin={x:2,y:1};Configuration.visual.boxSpacing=1;Configuration.visual.curlyHeight=4;Configuration.visual.arcSpacing=9;Configuration.visual.arcStartHeight=19;}dispatcher.post('configurationChanged');};var setSvgWidth=function setSvgWidth(_width){$svgDiv.width(_width);if(Configuration.svgWidth!=_width){Configuration.svgWidth=_width;dispatcher.post('configurationChanged');}};$svgDiv=$($svgDiv).hide();// register event listeners
var registerHandlers=function registerHandlers(element,events){$.each(events,function(eventNo,eventName){element.bind(eventName,function(evt){dispatcher.post(eventName,[evt],'all');});});};registerHandlers($svgDiv,['mouseover','mouseout','mousemove','mouseup','mousedown','dragstart','dblclick','click']);registerHandlers($(document),['keydown','keypress','touchstart','touchend']);registerHandlers($(window),['resize']);// create the svg wrapper
$svgDiv.svg({onLoad:function onLoad(_svg){that.svg=svg=_svg;$svg=$(svg._svg);/* XXX HACK REMOVED - not efficient?

              // XXX HACK to allow off-DOM SVG element creation
              // we need to replace the jQuery SVG's _makeNode function
              // with a modified one.
              // Be aware of potential breakage upon jQuery SVG upgrade.
              svg._makeNode = function(parent, name, settings) {
                  // COMMENTED OUT: parent = parent || this._svg;
                  var node = this._svg.ownerDocument.createElementNS($.svg.svgNS, name);
                  for (var name in settings) {
                    var value = settings[name];
                    if (value != null && value != null &&
                        (typeof value != 'string' || value != '')) {
                      node.setAttribute($.svg._attrNames[name] || name, value);
                    }
                  }
                  // ADDED IN:
                  if (parent)
                    parent.appendChild(node);
                  return node;
                };
              */triggerRender();}});var loadSpanTypes=function loadSpanTypes(types){$.each(types,function(typeNo,type){if(type){spanTypes[type.type]=type;var children=type.children;if(children&&children.length){loadSpanTypes(children);}}});};var loadAttributeTypes=function loadAttributeTypes(response_types){var processed={};$.each(response_types,function(aTypeNo,aType){processed[aType.type]=aType;// count the values; if only one, it's a boolean attribute
var values=[];for(var i in aType.values){if(aType.values.hasOwnProperty(i)){values.push(i);}}if(values.length==1){aType.bool=values[0];}});return processed;};var loadRelationTypes=function loadRelationTypes(relation_types){$.each(relation_types,function(relTypeNo,relType){if(relType){relationTypesHash[relType.type]=relType;var children=relType.children;if(children&&children.length){loadRelationTypes(children);}}});};var collectionLoaded=function collectionLoaded(response){if(!response.exception){setCollectionDefaults(response);eventAttributeTypes=loadAttributeTypes(response.event_attribute_types);entityAttributeTypes=loadAttributeTypes(response.entity_attribute_types);spanTypes={};loadSpanTypes(response.entity_types);loadSpanTypes(response.event_types);loadSpanTypes(response.unconfigured_types);relationTypesHash={};loadRelationTypes(response.relation_types);loadRelationTypes(response.unconfigured_types);// TODO XXX: isn't the following completely redundant with
// loadRelationTypes?
$.each(response.relation_types,function(relTypeNo,relType){relationTypesHash[relType.type]=relType;});dispatcher.post('spanAndAttributeTypesLoaded',[spanTypes,entityAttributeTypes,eventAttributeTypes,relationTypesHash]);isCollectionLoaded=true;triggerRender();}else{// exception on collection load; allow visualizer_ui
// collectionLoaded to handle this
}};var isReloadOkay=function isReloadOkay(){// do not reload while the user is in the dialog
return!drawing;};// If we are yet to load our fonts, dispatch them
if(!Visualizer.areFontsLoaded){var webFontConfig={custom:{families:['Astloch','PT Sans Caption',//        'Ubuntu',
'Liberation Sans'],/* For some cases, in particular for embedding, we need to
              allow for fonts being hosted elsewhere */urls:webFontURLs!==undefined?webFontURLs:['static/fonts/Astloch-Bold.ttf','static/fonts/PT_Sans-Caption-Web-Regular.ttf',//
'static/fonts/Liberation_Sans-Regular.ttf']},active:proceedWithFonts,inactive:proceedWithFonts,fontactive:function fontactive(fontFamily,fontDescription){// Note: Enable for font debugging
//console.log("font active: ", fontFamily, fontDescription);
},fontloading:function fontloading(fontFamily,fontDescription){// Note: Enable for font debugging
//console.log("font loading:", fontFamily, fontDescription);
}};WebFont.load(webFontConfig);setTimeout(function(){if(!Visualizer.areFontsLoaded){console.error('Timeout in loading fonts');proceedWithFonts();}},fontLoadTimeout||5000);// default 5s
}dispatcher.on('collectionChanged',collectionChanged).on('collectionLoaded',collectionLoaded).on('renderData',renderData).on('triggerRender',triggerRender).on('requestRenderData',requestRenderData).on('isReloadOkay',isReloadOkay).on('resetData',resetData).on('abbrevs',setAbbrevs).on('textBackgrounds',setTextBackgrounds).on('layoutDensity',setLayoutDensity).on('svgWidth',setSvgWidth).on('current',gotCurrent).on('clearSVG',clearSVG).on('mouseover',onMouseOver).on('mouseout',onMouseOut);};Visualizer.areFontsLoaded=false;var proceedWithFonts=function proceedWithFonts(){Visualizer.areFontsLoaded=true;// Note: Enable for font debugging
//console.log("fonts done");
Dispatcher.post('triggerRender');};return Visualizer;}(jQuery,window);// BRAT STANDALONE LIBRARY BEGIN
// Browserify export
module.exports=Visualizer;// BRAT STANDALONE LIBRARY END
},{}],18:[function(require,module,exports){// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*-
// vim:set ft=javascript ts=2 sw=2 sts=2 cindent:
var VisualizerUI=function($,window,undefined){var VisualizerUI=function VisualizerUI(dispatcher,svg,showTooltip,overWriteModals){var that=this;var messagePostOutFadeDelay=1000;var messageDefaultFadeDelay=3000;var defaultFloatFormat='%.1f/right';var documentListing=null;// always documents of current collection
var selectorData=null;// can be search results when available
var searchActive=false;// whether search results received and in use
var loadedSearchData=null;var currentForm;var spanTypes=null;var relationTypesHash=null;// TODO: confirm unnecessary and remove
//       var attributeTypes = null;
var data=null;var mtime=null;var searchConfig=null;var coll,doc,args;var collScroll;var docScroll;var user=null;var annotationAvailable=false;var svgElement=$(svg._svg);var svgId=svgElement.parent().attr('id');var maxMessages=100;var currentDocumentSVGsaved=false;var fileBrowserClosedWithSubmit=false;// normalization: server-side DB by norm DB name
var normServerDbByNormDbName={};var matchFocus='';var matches='';/* START "no svg" message - related */var noSvgTimer=null;// this is necessary for centering
$('#no_svg_wrapper').css('display','table');// on initial load, hide the "no SVG" message
$('#no_svg_wrapper').hide();var hideNoDocMessage=function hideNoDocMessage(){clearTimeout(noSvgTimer);$('#no_svg_wrapper').hide(0);$('#source_files').show();};var showNoDocMessage=function showNoDocMessage(){clearTimeout(noSvgTimer);noSvgTimer=setTimeout(function(){$('#no_svg_wrapper').fadeIn(500);},2000);$('#source_files').hide();};/* END "no svg" message - related *//* START collection browser sorting - related */var lastGoodCollection='/';var sortOrder=[2,1];// column (0..), sort order (1, -1)
var collectionSortOrder;// holds previous sort while search is active
var docSortFunction=function docSortFunction(a,b){// parent at the top
if(a[2]==='..')return-1;if(b[2]==='..')return 1;// then other collections
var aIsColl=a[0]=="c";var bIsColl=b[0]=="c";if(aIsColl!==bIsColl)return aIsColl?-1:1;// desired column in the desired order
var col=sortOrder[0];var aa=a[col];var bb=b[col];if(selectorData.header[col-2][1]==='string-reverse'){aa=aa.split('').reverse().join('');bb=bb.split('').reverse().join('');}if(aa!=bb)return aa<bb?-sortOrder[1]:sortOrder[1];// prevent random shuffles on columns with duplicate values
// (alphabetical order of documents)
aa=a[2];bb=b[2];if(aa!=bb)return aa<bb?-1:1;return 0;};var makeSortChangeFunction=function makeSortChangeFunction(sort,th,thNo){$(th).click(function(){// TODO: avoid magic numbers in access to the selector
// data (column 0 is type, 1 is args, rest is data)
if(sort[0]===thNo+1)sort[1]=-sort[1];else{var type=selectorData.header[thNo-1][1];var ascending=type==="string";sort[0]=thNo+1;sort[1]=ascending?1:-1;}selectorData.items.sort(docSortFunction);docScroll=0;showFileBrowser();// resort
});};/* END collection browser sorting - related *//* START message display - related */var showPullupTrigger=function showPullupTrigger(){$('#pulluptrigger').show('puff');};var $messageContainer=$('#messages');var $messagepullup=$('#messagepullup');var pullupTimer=null;var displayMessages=function displayMessages(msgs){var initialMessageNum=$messagepullup.children().length;if(msgs===false){$messageContainer.children().each(function(msgElNo,msgEl){$(msgEl).remove();});}else{$.each(msgs,function(msgNo,msg){var element;var timer=null;try{element=$('<div class="'+msg[1]+'">'+msg[0]+'</div>');}catch(x){escaped=msg[0].replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");element=$('<div class="error"><b>[ERROR: could not display the following message normally due to malformed XML:]</b><br/>'+escaped+'</div>');}var pullupElement=element.clone();$messageContainer.append(element);$messagepullup.append(pullupElement.css('display','none'));slideToggle(pullupElement,true,true);var fader=function fader(){if($messagepullup.is(':visible')){element.remove();}else{element.hide('slow',function(){element.remove();});}};var delay=msg[2]===undefined?messageDefaultFadeDelay:msg[2]===-1?null:msg[2]*1000;if(delay===null){var button=$('<input type="button" value="OK"/>');element.prepend(button);button.click(function(evt){timer=setTimeout(fader,0);});}else{timer=setTimeout(fader,delay);element.mouseover(function(){clearTimeout(timer);element.show();}).mouseout(function(){timer=setTimeout(fader,messagePostOutFadeDelay);});}// setTimeout(fader, messageDefaultFadeDelay);
});// limited history - delete oldest
var $messages=$messagepullup.children();for(var i=0;i<$messages.length-maxMessages;i++){$($messages[i]).remove();}}// if there is change in the number of messages, may need to
// tweak trigger visibility
var messageNum=$messagepullup.children().length;if(messageNum!=initialMessageNum){if(messageNum==0){// all gone; nothing to trigger
$('#pulluptrigger').hide('slow');}else if(initialMessageNum==0){// first messages, show trigger at fade
setTimeout(showPullupTrigger,messageDefaultFadeDelay+250);}}};// hide pullup trigger by default, show on first message
$('#pulluptrigger').hide();$('#pulluptrigger').mouseenter(function(evt){$('#pulluptrigger').hide('puff');clearTimeout(pullupTimer);slideToggle($messagepullup.stop(),true,true,true);});$('#messagepullup').mouseleave(function(evt){setTimeout(showPullupTrigger,500);clearTimeout(pullupTimer);pullupTimer=setTimeout(function(){slideToggle($messagepullup.stop(),false,true,true);},500);});/* END message display - related *//* START comment popup - related */var adjustToCursor=function adjustToCursor(evt,element,offset,top,right){// get the real width, without wrapping
element.css({left:0,top:0});var screenHeight=$(window).height();var screenWidth=$(window).width();// FIXME why the hell is this 22 necessary?!?
var elementHeight=element.height()+22;var elementWidth=element.width()+22;var x,y;offset=offset||0;if(top){y=evt.clientY-elementHeight-offset;if(y<0)top=false;}if(!top){y=evt.clientY+offset;}if(right){x=evt.clientX+offset;if(x>=screenWidth-elementWidth)right=false;}if(!right){x=evt.clientX-elementWidth-offset;}if(y<0)y=0;if(x<0)x=0;element.css({top:y,left:x});};var commentPopup=$('#commentpopup');var commentDisplayed=false;var displayCommentTimer=null;var displayComment=function displayComment(evt,target,comment,commentText,commentType,immediately){var idtype;if(commentType){// label comment by type, with special case for default note type
var commentLabel;if(commentType=='AnnotatorNotes'){commentLabel='<b>Note:</b> ';}else{commentLabel='<b>'+Util.escapeHTML(commentType)+':</b> ';}comment+=commentLabel+Util.escapeHTMLwithNewlines(commentText);idtype='comment_'+commentType;}commentPopup[0].className=idtype;commentPopup.html(comment);if(showTooltip){adjustToCursor(evt,commentPopup,10,true,true);clearTimeout(displayCommentTimer);/* slight "tooltip" delay to allow highlights to be seen
           before the popup obstructs them. */displayCommentTimer=setTimeout(function(){commentPopup.stop(true,true).fadeIn();commentDisplayed=true;},immediately?0:500);}};// to avoid clobbering on delayed response
var commentPopupNormInfoSeqId=0;var normInfoSortFunction=function normInfoSortFunction(a,b){// images at the top
if(a[0].toLowerCase()=='<img>')return-1;if(b[0].toLowerCase()=='<img>')return 1;// otherwise stable
return Util.cmp(a[2],b[2]);};var displaySpanComment=function displaySpanComment(evt,target,spanId,spanType,mods,spanText,commentText,commentType,normalizations){var immediately=false;var comment='<div><span class="comment_type_id_wrapper">'+'<span class="comment_type">'+Util.escapeHTML(Util.spanDisplayForm(spanTypes,spanType))+'</span>'+' '+'<span class="comment_id">'+'ID:'+Util.escapeHTML(spanId)+'</span></span>';if(mods.length){comment+='<div>'+Util.escapeHTML(mods.join(', '))+'</div>';}comment+='</div>';comment+='<div class="comment_text">"'+Util.escapeHTML(spanText)+'"</div>';var validArcTypesForDrag=dispatcher.post('getValidArcTypesForDrag',[spanId,spanType]);if(validArcTypesForDrag&&validArcTypesForDrag[0]){if(validArcTypesForDrag[0].length){comment+='<div>'+validArcTypesForDrag[0].join(', ')+'</div>';}else{$('rect[data-span-id="'+spanId+'"]').addClass('badTarget');}immediately=true;}// process normalizations
var normsToQuery=[];$.each(normalizations,function(normNo,norm){var dbName=norm[0],dbKey=norm[1];comment+='<hr/>'+'<span class="comment_id">'+Util.escapeHTML(dbName)+':'+Util.escapeHTML(dbKey)+'</span>';if(dbName in normServerDbByNormDbName&&normServerDbByNormDbName[dbName]!='<NONE>'){// DB available, add drop-off point to HTML and store
// query parameters
commentPopupNormInfoSeqId++;comment+='<br/><div id="norm_info_drop_point_'+commentPopupNormInfoSeqId+'"/>';normsToQuery.push([dbName,dbKey,commentPopupNormInfoSeqId]);}else{// no DB, just attach "human-readable" text provided
// with the annotation, if any
if(norm[2]){comment+='<br/><span class="norm_info_value">'+Util.escapeHTML(norm[2])+'</span>';}}});// display initial comment HTML
if(showTooltip){displayComment(evt,target,comment,commentText,commentType,immediately);}// initiate AJAX calls for the normalization data to query
$.each(normsToQuery,function(normqNo,normq){// TODO: cache some number of most recent norm_get_data results
var dbName=normq[0],dbKey=normq[1],infoSeqId=normq[2];dispatcher.post('ajax',[{action:'normData',database:dbName,key:dbKey,collection:coll},function(response){if(response.exception){;// TODO: response to error
}else if(!response.value){;// TODO: response to missing key
}else{// extend comment popup with normalization data
norminfo='';// flatten outer (name, attr, info) array (idx for sort)
infos=[];var idx=0;for(var i=0;i<response.value.length;i++){for(var j=0;j<response.value[i].length;j++){var label=response.value[i][j][0];var value=response.value[i][j][1];infos.push([label,value,idx++]);}}// sort, prioritizing images (to get floats right)
infos=infos.sort(normInfoSortFunction);// generate HTML
for(var i=0;i<infos.length;i++){var label=infos[i][0];var value=infos[i][1];if(label&&value){// special treatment for some label values
if(label.toLowerCase()=='<img>'){// image
norminfo+='<img class="norm_info_img" src="'+value+'"/>';}else{// normal, as text
// max length restriction
if(value.length>300){value=value.substr(0,300)+' ...';}norminfo+='<span class="norm_info_label">'+Util.escapeHTML(label)+'</span>'+'<span class="norm_info_value">'+':'+Util.escapeHTML(value)+'</span>'+'<br/>';}}}var drop=$('#norm_info_drop_point_'+infoSeqId);if(drop){drop.html(norminfo);}else{console.log('norm info drop point not found!');//TODO XXX
}}}]);});};var onDocChanged=function onDocChanged(){commentPopup.hide();commentDisplayed=false;};var displayArcComment=function displayArcComment(evt,target,symmetric,arcId,originSpanId,originSpanType,role,targetSpanId,targetSpanType,commentText,commentType){var arcRole=target.attr('data-arc-role');// in arrowStr, &#8212 == mdash, &#8594 == Unicode right arrow
var arrowStr=symmetric?'&#8212;':'&#8594;';var arcDisplayForm=Util.arcDisplayForm(spanTypes,data.spans[originSpanId].type,arcRole,relationTypesHash);var comment="";comment+='<span class="comment_type_id_wrapper">'+'<span class="comment_type">'+Util.escapeHTML(Util.spanDisplayForm(spanTypes,originSpanType))+' '+arrowStr+' '+Util.escapeHTML(arcDisplayForm)+' '+arrowStr+' '+Util.escapeHTML(Util.spanDisplayForm(spanTypes,targetSpanType))+'</span>'+'<span class="comment_id">'+(arcId?'ID:'+arcId:Util.escapeHTML(originSpanId)+arrowStr+Util.escapeHTML(targetSpanId))+'</span>'+'</span>';comment+='<div class="comment_text">'+Util.escapeHTML('"'+data.spans[originSpanId].text+'"')+arrowStr+Util.escapeHTML('"'+data.spans[targetSpanId].text+'"')+'</div>';displayComment(evt,target,comment,commentText,commentType);};var displaySentComment=function displaySentComment(evt,target,commentText,commentType){displayComment(evt,target,'',commentText,commentType);};var hideComment=function hideComment(){clearTimeout(displayCommentTimer);if(commentDisplayed){commentPopup.stop(true,true).fadeOut(function(){commentDisplayed=false;});}};var onMouseMove=function onMouseMove(evt){if(commentDisplayed&&showTooltip){adjustToCursor(evt,commentPopup,10,true,true);}};/* END comment popup - related *//* START form management - related */initForm=function initForm(form,opts){opts=opts||{};var formId=form.attr('id');// alsoResize is special
var alsoResize=opts.alsoResize;delete opts.alsoResize;// Always add OK and Cancel
var buttons=opts.buttons||[];if(opts.no_ok){delete opts.no_ok;}else{buttons.push({id:formId+"-ok",text:"OK",click:function click(){form.submit();}});}if(opts.no_cancel){delete opts.no_cancel;}else{buttons.push({id:formId+"-cancel",text:"Cancel",click:function click(){form.dialog('close');}});}delete opts.buttons;opts=$.extend({autoOpen:false,closeOnEscape:true,buttons:buttons,modal:true},opts);form.dialog(opts);form.bind('dialogclose',function(){if(form==currentForm){currentForm=null;}});// HACK: jQuery UI's dialog does not support alsoResize
// nor does resizable support a jQuery object of several
// elements
// See: http://bugs.jqueryui.com/ticket/4666
if(alsoResize){form.parent().resizable('option','alsoResize','#'+form.attr('id')+', '+alsoResize);}};var showForm=function showForm(form){currentForm=form;if(!overWriteModals){// as suggested in http://stackoverflow.com/questions/2657076/jquery-ui-dialog-fixed-positioning
form.parent().css({position:"fixed"});form.dialog('open');slideToggle($('#pulldown').stop(),false);}return form;};var hideForm=function hideForm(){if(!currentForm)return;// currentForm.fadeOut(function() { currentForm = null; });
currentForm.dialog('close');currentForm=null;};/* END form management - related *//* START collection browser - related */var selectElementInTable=function selectElementInTable(table,docname,mf){table=$(table);table.find('tr').removeClass('selected');var sel='tr';var $element;if(docname){sel+='[data-doc="'+docname+'"]';if(mf){sel+='[data-mf="'+Util.paramArray(mf)+'"]';}var $element=table.find(sel).first();$element.addClass('selected');}matchFocus=$element&&$element.attr('data-mf');matches=$element&&$element.attr('data-match');};var chooseDocument=function chooseDocument(evt){var $element=$(evt.target).closest('tr');$('#document_select tr').removeClass('selected');$('#document_input').val($element.attr('data-doc'));$element.addClass('selected');matchFocus=$element.attr('data-mf');matches=$element.attr('data-match');};var chooseDocumentAndSubmit=function chooseDocumentAndSubmit(evt){chooseDocument(evt);fileBrowserSubmit(evt);};var fileBrowser=$('#collection_browser');initForm(fileBrowser,{alsoResize:'#document_select',close:function close(evt){if(!doc){// no document; set and show the relevant message, and
// clear the "blind" unless waiting for a collection
if(fileBrowserClosedWithSubmit){$('#no_document_message').hide();$('#loading_message').show();}else{$('#loading_message').hide();$('#no_document_message').show();$('#waiter').dialog('close');}showNoDocMessage();}else if(!fileBrowserClosedWithSubmit&&!searchActive){dispatcher.post('setArguments',[{},true]);}},width:500});/* XXX removed per #900
      // insert the Save link
      var $fileBrowserButtonset = fileBrowser.
          parent().find('.ui-dialog-buttonpane .ui-dialog-buttonset').prepend(' ');
      $('<a href="ajax.cgi?action=downloadSearchFile" id="save_search">Save</a>').
          prependTo($fileBrowserButtonset).button().css('display', 'none');
      */var docInputHandler=function docInputHandler(evt){selectElementInTable('#document_select',$(this).val());};$('#document_input').keyup(docInputHandler);var fileBrowserSubmit=function fileBrowserSubmit(evt){var _coll,_doc,_args,found;var input=$('#document_input').val().replace(/\/?\s+$/,'').replace(/^\s+/,'');if(!input.length)return false;if(input.substr(0,2)==='..'){// ..
var pos=coll.substr(0,coll.length-1).lastIndexOf('/');if(pos===-1){dispatcher.post('messages',[[['At the root','error',2]]]);$('#document_input').focus().select();return false;}else{_coll=coll.substr(0,pos+1);_doc='';}}else if(found=input.match(/^(\/?)((?:[^\/]*\/)*)([^\/?]*)$/)){var abs=found[1];var collname=found[2].substr(0,found[2].length-1);var docname=found[3];if(abs){_coll=abs+collname;if(_coll.length<2)coll+='/';_doc=docname;}else{if(collname)collname+='/';_coll=coll+collname;_doc=docname;}}else{dispatcher.post('messages',[[['Invalid document name format','error',2]]]);$('#document_input').focus().select();}docScroll=$('#document_select')[0].scrollTop;fileBrowser.find('#document_select tbody').empty();if(coll!=_coll||doc!=_doc||Util.paramArray(args.matchfocus)!=matchFocus){// something changed
// set to allow keeping "blind" down during reload
fileBrowserClosedWithSubmit=true;// ... and change BG message to a more appropriate one
// trigger clear and changes if something other than the
// current thing is chosen, but only blank screen before
// render if the document changed (prevent "flicker" on
// e.g. picking search results)
if(coll!=_coll||doc!=_doc){dispatcher.post('clearSVG');}dispatcher.post('allowReloadByURL');var newArgs=[];if(matchFocus)newArgs.push('matchfocus='+matchFocus);if(matches)newArgs.push('match='+matches);dispatcher.post('setCollection',[_coll,_doc,Util.deparam(newArgs.join('&'))]);}else{// hide even on select current thing
hideForm();}return false;};fileBrowser.submit(fileBrowserSubmit).bind('reset',hideForm);var fileBrowserWaiting=false;var showFileBrowser=function showFileBrowser(){// keep tabs on how the browser is closed; we need to keep the
// "blind" up when retrieving a collection, but not when canceling
// without selection (would hang the UI)
// BRAT STANDALONE LIBRARY BEGIN
/*
        fileBrowserClosedWithSubmit = false;

        // no point in showing this while the browser is shown
        hideNoDocMessage();

        if (currentForm == tutorialForm) {
          fileBrowserWaiting = true;
          return;
        }
        fileBrowserWaiting = false;

        // hide "no document" message when file browser shown
        // TODO: can't make this work; I can't detect when it gets hidden.
        // hideNoDocMessage();

        if (!(selectorData && showForm(fileBrowser))) return false;

        var html = ['<tr><th/>'];
        var tbody;
        $.each(selectorData.header, function(headNo, head) {
          html.push('<th>' + head[0] + '</th>');
        });
        html.push('</tr>');
        $('#document_select thead').html(html.join(''));

        html = [];
        // NOTE: we seem to have some excessive sorting going on;
        // disabling this as a test. If everything works, just remove
        // the following commented-out line (and this comment):
        //selectorData.items.sort(docSortFunction);
        $.each(selectorData.items, function(docNo, doc) {
          var isColl = doc[0] == "c"; // "collection"
          // second column is optional annotation-specific pointer,
          // used (at least) for search results
          var annp = doc[1] ? ('?' + Util.escapeHTML(Util.param(doc[1]))) : '';
          var name = Util.escapeHTML(doc[2]);
          var collFile = isColl ? 'collection' : 'file';
          //var collFileImg = isColl ? 'ic_list_folder.png' : 'ic_list_drafts.png';
          //var collFileImg = isColl ? 'Fugue-folder-horizontal-open.png' : 'Fugue-document.png';
          var collFileImg = isColl ? 'Fugue-shadowless-folder-horizontal-open.png' : 'Fugue-shadowless-document.png';
          var collSuffix = isColl ? '/' : '';
          if (doc[1]) {
            var matchfocus = doc[1].matchfocus || [];
            var mfstr = ' data-mf="' + Util.paramArray(matchfocus) + '"';
            var match = doc[1].match || [];
            var matchstr = ' data-match="' + Util.paramArray(match) + '"';
          } else {
            var matchstr = '';
            var mfstr = '';
          }
          html.push('<tr class="' + collFile + '" data-doc="'
            + name + collSuffix + '"' + matchstr + mfstr + '>');
          html.push('<th><img src="static/img/' + collFileImg + '" alt="' + collFile + '"/></th>');
          html.push('<th>' + name + collSuffix + '</th>');
          var len = selectorData.header.length - 1;
          for (var i = 0; i < len; i++) {
            var type = selectorData.header[i + 1][1];
            var datum = doc[i + 3];
            // format rest according to "data type" specified in header
            var formatted = null;
            var cssClass = null;
            if (!type) {
              console.error('Missing document list data type');
              formatted = datum;
            } else if (datum === undefined) {
              formatted = '';
            } else if (type === 'string') {
              formatted = Util.escapeHTML(datum);
            } else if (type === 'string-right' || type === 'string-reverse') {
              formatted = Util.escapeHTML(datum);
              cssClass = 'rightalign';
            } else if (type === 'string-center') {
              formatted = Util.escapeHTML(datum);
              cssClass = 'centeralign';
            } else if (type === 'time') {
              formatted = Util.formatTimeAgo(datum * 1000);
            } else if (type === 'float') {
              type = defaultFloatFormat;
              cssClass = 'rightalign';
            } else if (type === 'int') {
              formatted = '' + datum;
              cssClass = 'rightalign';
            }
            if (formatted === null) {
              var m = type.match(/^(.*?)(?:\/(right))?$/);
              cssClass = m[2] ? 'rightalign' : null;
              formatted = $.sprintf(m[1], datum);
            }
            html.push('<td' + (cssClass ? ' class="' + cssClass + '"' : '') + '>' +
                formatted + '</td>');
          }
          html.push('</tr>');
        });
        html = html.join('');
        tbody = $('#document_select tbody').html(html);
        $('#document_select')[0].scrollTop = docScroll;
        tbody.find('tr').
            click(chooseDocument).
            dblclick(chooseDocumentAndSubmit);

        $('#document_select thead tr *').each(function(thNo, th) {
            makeSortChangeFunction(sortOrder, th, thNo);
        });

        $('#collection_input').val(selectorData.collection);
        $('#document_input').val(doc);

        $('#readme').val(selectorData.description || '');
        if (selectorData.description && 
            (selectorData.description.match(/\n/) ||
             selectorData.description.length > 50)) {
          // multi-line or long description; show "more" button and fill
          // dialog text
          $('#more_readme_button').button(); // TODO: more reasonable place
          $('#more_readme_button').show();
          // only display text up to the first newline in the short info*///var split_readme_text = selectorData.description.match(/^[^\n]*/);
/*$('#readme').val(split_readme_text[0]);
          $('#more_info_readme').text(selectorData.description);
        } else {
          // empty or short, single-line description; no need for more
          $('#more_readme_button').hide();
          $('#more_info_readme').text('');
        }

        selectElementInTable($('#document_select'), doc, args.matchfocus);
        setTimeout(function() {
          $('#document_input').focus().select();
        }, 0);

*/// BRAT STANDALONE LIBRARY END
};// end showFileBrowser()
$('#collection_browser_button').click(function(evt){dispatcher.post('clearSearch');});var currentSelectorPosition=function currentSelectorPosition(){var pos;$.each(selectorData.items,function(docNo,docRow){if(docRow[2]==doc){// args may have changed, so lacking a perfect match return
// last matching document as best guess
pos=docNo;// check whether 'focus' agrees; the rest of the args are
// irrelevant for determining position.
var collectionArgs=docRow[1]||{};if(Util.isEqual(collectionArgs.matchfocus,args.matchfocus)){pos=docNo;return false;}}});return pos;};/* END collection browser - related *//* START search - related */var addSpanTypesToSelect=function addSpanTypesToSelect($select,types,included){if(!included)included={};if(!included['']){included['']=true;$select.html('<option value="">- Any -</option>');}$.each(types,function(typeNo,type){if(type!==null){if(!included[type.name]){included[type.name]=true;var $option=$('<option value="'+Util.escapeQuotes(type.type)+'"/>').text(type.name);$select.append($option);if(type.children){addSpanTypesToSelect($select,type.children,included);}}}});};var rememberNormDb=function rememberNormDb(response){// the visualizer needs to remember aspects of the norm setup
// so that it can avoid making queries for unconfigured or
// missing normalization DBs.
var norm_resources=response.normalization_config||[];$.each(norm_resources,function(normNo,norm){var normName=norm[0];var serverDb=norm[3];normServerDbByNormDbName[normName]=serverDb;});};var setupSearchTypes=function setupSearchTypes(response){addSpanTypesToSelect($('#search_form_entity_type'),response.entity_types);addSpanTypesToSelect($('#search_form_event_type'),response.event_types);addSpanTypesToSelect($('#search_form_relation_type'),response.relation_types);// nice-looking selects and upload fields
$('#search_form select').addClass('ui-widget ui-state-default ui-button-text');$('#search_form_load_file').addClass('ui-widget ui-state-default ui-button-text');};// when event role changes, event types do as well
var searchEventRoles=[];var searchEventRoleChanged=function searchEventRoleChanged(evt){var $type=$(this).parent().next().children('select');var type=$type.val();var role=$(this).val();var origin=$('#search_form_event_type').val();var eventType=spanTypes[origin];var arcTypes=eventType&&eventType.arcs||[];var arcType=null;$type.html('<option value="">- Any -</option>');$.each(arcTypes,function(arcNo,arcDesc){if(arcDesc.type==role){arcType=arcDesc;return false;}});var targets=arcType&&arcType.targets||[];$.each(targets,function(targetNo,target){var spanType=spanTypes[target];var spanName=spanType.name||spanType.labels[0]||target;var option='<option value="'+Util.escapeQuotes(target)+'">'+Util.escapeHTML(spanName)+'</option>';$type.append(option);});// return the type to the same value, if possible
if(type){$type.val(type);};};$('#search_form_event_roles .search_event_role select').live('change',searchEventRoleChanged);// adding new role rows
var addEmptySearchEventRole=function addEmptySearchEventRole(){var $roles=$('#search_form_event_roles');var rowNo=$roles.children().length;var $role=$('<select class="fullwidth"/>');$role.append('<option value="">- Any -</option>');$.each(searchEventRoles,function(arcTypePairNo,arcTypePair){var option='<option value="'+Util.escapeQuotes(arcTypePair[0])+'">'+Util.escapeHTML(arcTypePair[1])+'</option>';$role.append(option);});var $type=$('<select class="fullwidth"/>');var $text=$('<input class="fullwidth"/>');var button=$('<input type="button"/>');var rowButton=$('<td/>').append(button);if(rowNo){rowButton.addClass('search_event_role_del');button.val("\u2013");// n-dash
}else{rowButton.addClass('search_event_role_add');button.val('+');}var $tr=$('<tr/>').append($('<td class="search_event_role"/>').append($role)).append($('<td class="search_event_type"/>').append($type)).append($('<td class="search_event_text"/>').append($text)).append(rowButton);$roles.append($tr);$role.trigger('change');// style selector
$role.addClass('ui-widget ui-state-default ui-button-text');$type.addClass('ui-widget ui-state-default ui-button-text');// style button
button.button();button.addClass('small-buttons ui-button-text').removeClass('ui-button');};// deleting role rows
var delSearchEventRole=function delSearchEventRole(evt){$row=$(this).closest('tr');$row.remove();};$('#search_form_event_roles .search_event_role_add input').live('click',addEmptySearchEventRole);$('#search_form_event_roles .search_event_role_del input').live('click',delSearchEventRole);// When event type changes, the event roles do as well
// Also, put in one empty role row
$('#search_form_event_type').change(function(evt){var $roles=$('#search_form_event_roles').empty();searchEventRoles=[];var eventType=spanTypes[$(this).val()];var arcTypes=eventType&&eventType.arcs||[];$.each(arcTypes,function(arcTypeNo,arcType){var arcTypeName=arcType.labels&&arcType.labels[0]||arcType.type;searchEventRoles.push([arcType.type,arcTypeName]);});addEmptySearchEventRole();});// when relation changes, change choices of arg1 type
$('#search_form_relation_type').change(function(evt){var relTypeType=$(this).val();var $arg1=$('#search_form_relation_arg1_type').html('<option value="">- Any -</option>');var $arg2=$('#search_form_relation_arg2_type').empty();$.each(spanTypes,function(spanTypeType,spanType){if(spanType.arcs){$.each(spanType.arcs,function(arcTypeNo,arcType){if(arcType.type===relTypeType){var spanName=spanType.name;var option='<option value="'+Util.escapeQuotes(spanTypeType)+'">'+Util.escapeHTML(spanName)+'</option>';$arg1.append(option);}});}});$('#search_form_relation_arg1_type').change();// style the selects
$arg1.addClass('ui-widget ui-state-default ui-button-text');$arg2.addClass('ui-widget ui-state-default ui-button-text');});// when arg1 type changes, change choices of arg2 type
$('#search_form_relation_arg1_type').change(function(evt){var $arg2=$('#search_form_relation_arg2_type').html('<option value="">- Any -</option>');var relType=$('#search_form_relation_type').val();var arg1Type=spanTypes[$(this).val()];var arcTypes=arg1Type&&arg1Type.arcs||[];var arcType=null;$.each(arcTypes,function(arcNo,arcDesc){if(arcDesc.type==relType){arcType=arcDesc;return false;}});if(arcType&&arcType.targets){$.each(arcType.targets,function(spanTypeNo,spanTypeType){var spanName=Util.spanDisplayForm(spanTypes,spanTypeType);var option='<option value="'+Util.escapeQuotes(spanTypeType)+'">'+Util.escapeHTML(spanName)+'</option>';$arg2.append(option);});}});$('#search_form_note_category').change(function(evt){var category=$(this).val();var $type=$('#search_form_note_type');if($.inArray(category,['entity','event','relation'])!=-1){$type.html($('#search_form_'+category+'_type').html()).val('');$('#search_form_note_type_row:not(:visible)').show('highlight');}else{$type.html('');$('#search_form_note_type_row:visible').hide('highlight');}});// context length setting should only be visible if
// concordancing is on
// TODO: @amadanmath: help, my jQuery is horrible
if($('#concordancing_on').is(':checked')){$('#context_size_div').show("highlight");}else{$('#context_size_div').hide("highlight");}$('#concordancing input[type="radio"]').change(function(){if($('#concordancing_on').is(':checked')){$('#context_size_div').show("highlight");}else{$('#context_size_div').hide("highlight");}});$('#search_options div.advancedOptions').hide("highlight");// set up advanced search options; only visible is clicked
var advancedSearchOptionsVisible=false;$('#advanced_search_option_toggle').click(function(evt){if(advancedSearchOptionsVisible){$('#search_options div.advancedOptions').hide("highlight");$('#advanced_search_option_toggle').text("Show advanced");}else{$('#search_options div.advancedOptions').show("highlight");$('#advanced_search_option_toggle').text("Hide advanced");}advancedSearchOptionsVisible=!advancedSearchOptionsVisible;// block default
return false;});var activeSearchTab=function activeSearchTab(){// activeTab: 0 = Text, 1 = Entity, 2 = Event, 3 = Relation, 4 = Notes, 5 = Load
var activeTab=$('#search_tabs').tabs('option','selected');return['searchText','searchEntity','searchEvent','searchRelation','searchNote','searchLoad'][activeTab];};var onSearchTabSelect=function onSearchTabSelect(){var action=activeSearchTab();switch(action){case'searchText':$('#search_form_text_text').focus().select();break;case'searchEntity':$('#search_form_entity_text').focus().select();break;case'searchEvent':$('#search_form_event_trigger').focus().select();break;case'searchRelation':$('#search_form_relation_type').focus().select();break;case'searchNote':$('#search_form_note_text').focus().select();break;case'searchLoad':$('#search_form_load_file').focus().select();break;}};// set up jQuery UI elements in search form
$('#search_tabs').tabs({show:onSearchTabSelect});$('#search_form').find('.radio_group').buttonset();var applySearchResults=function applySearchResults(response){if(!searchActive){collectionSortOrder=sortOrder;}dispatcher.post('searchResultsReceived',[response]);searchActive=true;updateSearchButtons();};var searchForm=$('#search_form');var searchFormSubmit=function searchFormSubmit(evt){// hack around empty document; "" would be interpreted as
// missing argument by server dispatcher (issue #513)
// TODO: do this properly, avoiding magic strings
var action=activeSearchTab();var docArg=doc?doc:"/NO-DOCUMENT/";var opts={action:action,collection:coll,document:docArg// TODO the search form got complex :)
};switch(action){case'searchText':opts.text=$('#search_form_text_text').val();if(!opts.text.length){dispatcher.post('messages',[[['Please fill in the text to search for!','comment']]]);return false;}break;case'searchEntity':opts.type=$('#search_form_entity_type').val()||'';opts.text=$('#search_form_entity_text').val();break;case'searchEvent':opts.type=$('#search_form_event_type').val()||'';opts.trigger=$('#search_form_event_trigger').val();var eargs=[];$('#search_form_event_roles tr').each(function(){var earg={};earg.role=$(this).find('.search_event_role select').val()||'';earg.type=$(this).find('.search_event_type select').val()||'';earg.text=$(this).find('.search_event_text input').val();eargs.push(earg);});opts.args=$.toJSON(eargs);break;case'searchRelation':opts.type=$('#search_form_relation_type').val()||'';opts.arg1=$('#search_form_relation_arg1_text').val();opts.arg1type=$('#search_form_relation_arg1_type').val()||'';opts.arg2=$('#search_form_relation_arg2_text').val();opts.arg2type=$('#search_form_relation_arg2_type').val()||'';break;case'searchNote':opts.category=$('#search_form_note_category').val()||'';opts.type=$('#search_form_note_type').val()||'';opts.text=$('#search_form_note_text').val()||'';break;case'searchLoad':applySearchResults(loadedSearchData);return false;}// fill in scope of search ("document" / "collection")
var searchScope=$('#search_scope input:checked').val();opts.scope=searchScope;// adjust specific action to invoke by scope
if(searchScope=="document"){opts.action=opts.action+"InDocument";}else{opts.action=opts.action+"InCollection";}// fill in concordancing options
opts.concordancing=$('#concordancing_on').is(':checked');opts.context_length=$('#context_length').val();// fill in text match options
opts.text_match=$('#text_match input:checked').val();opts.match_case=$('#match_case_on').is(':checked');dispatcher.post('hideForm');dispatcher.post('ajax',[opts,function(response){if(response&&response.items&&response.items.length==0){// TODO: might consider having this message come from the
// server instead
dispatcher.post('messages',[[['No matches to search.','comment']]]);dispatcher.post('clearSearch',[true]);}else{applySearchResults(response);}}]);return false;};$('#search_form_load_file').change(function(evt){var $file=$('#search_form_load_file');var file=$file[0].files[0];var reader=new FileReader();reader.onerror=function(evt){dispatcher.post('messages',[[['The file could not be read.','error']]]);};reader.onloadend=function(evt){try{loadedSearchData=JSON.parse(evt.target.result);// TODO XXX check for validity of contents, not just whether
// it's valid JSON or not; throw something if not
}catch(x){dispatcher.post('messages',[[['The file contains invalid data.','error']]]);return;}};reader.readAsText(file);});searchForm.submit(searchFormSubmit);initForm(searchForm,{width:500,// alsoResize: '#search_tabs',
resizable:false,open:function open(evt){keymap={};}});$('#search_form_clear').attr('title','Clear the search and resume normal collection browsing');var showSearchForm=function showSearchForm(){// this.checked = searchActive; // TODO: dup? unnecessary? remove if yes.
updateSearchButtons();$('#search_form_event_type').change();$('#search_form_relation_type').change();dispatcher.post('showForm',[searchForm]);onSearchTabSelect();};$('#search_button').click(showSearchForm);var clearSearchResults=function clearSearchResults(){// clear UI, don't show collection browser
dispatcher.post('clearSearch',[true]);// TODO: this was the only way I found to reset search. It
// trigger an unnecessary round-trip to the server, though,
// so there should be a better way ...
dispatcher.post('setArguments',[{},true]);};$('#clear_search_button').click(clearSearchResults);var updateSearchButtons=function updateSearchButtons(){$searchButton=$('#search_button');$searchButton[0].checked=searchActive;$searchButton.button('refresh');$clearSearchButton=$('#clear_search_button');if(searchActive){// TODO: this is a bit poor form, using jQuery UI classes
// directly -- are these names guaranteed to be stable?
$('#search_button_label').removeClass('ui-corner-all');$('#search_button_label').addClass('ui-corner-left');$clearSearchButton.show();}else{$('#search_button_label').removeClass('ui-corner-left');$('#search_button_label').addClass('ui-corner-all');$clearSearchButton.hide();}};/* END search - related *//* START data dialog - related */var dataForm=$('#data_form');var dataFormSubmit=function dataFormSubmit(evt){dispatcher.post('hideForm');return false;};dataForm.submit(dataFormSubmit);initForm(dataForm,{width:500,resizable:false,no_cancel:true,open:function open(evt){keymap={};// aspects of the data form relating to the current document should
// only be shown when a document is selected.
if(!doc){$('#document_export').hide();$('#document_visualization').hide();}else{$('#document_export').show();$('#document_visualization').show();// the SVG button can only be accessed through the data form,
// so we'll spare unnecessary saves by only saving here
saveSVG();}}});$('#data_button').click(function(){dispatcher.post('showForm',[dataForm]);});// make nice-looking buttons for checkboxes and buttons
$('#data_form').find('input[type="checkbox"]').button();$('#data_form').find('input[type="button"]').button();// resize invalidates stored visualization (SVG etc.); add a
// button to regen
$('#stored_file_regenerate').button().hide();$('#stored_file_regenerate').click(function(evt){$('#stored_file_regenerate').hide();saveSVG();});/* END data dialog - related *//* START options dialog - related */var optionsForm=$('#options_form');var optionsFormSubmit=function optionsFormSubmit(evt){dispatcher.post('hideForm');return false;};optionsForm.submit(optionsFormSubmit);initForm(optionsForm,{width:550,resizable:false,no_cancel:true,open:function open(evt){keymap={};}});$('#options_button').click(function(){dispatcher.post('showForm',[optionsForm]);});// make nice-looking buttons for checkboxes and radios
$('#options_form').find('input[type="checkbox"]').button();$('#options_form').find('.radio_group').buttonset();$('#rapid_model').addClass('ui-widget ui-state-default ui-button-text');var fillDisambiguatorOptions=function fillDisambiguatorOptions(disambiguators){$('#annotation_speed3').button(disambiguators.length?'enable':'disable');//XXX: We need to disable rapid in the conf too if it is not available
var $rapid_mode=$('#rapid_model').html('');$.each(disambiguators,function(modelNo,model){var $option=$('<option/>').attr('value',model[2]).text(model[2]);$rapid_mode.append($option);});};/* END options dialog - related *//* START "more collection information" dialog - related */var moreInfoDialog=$('#more_information_dialog');var moreInfoDialogSubmit=function moreInfoDialogSubmit(evt){dispatcher.post('hideForm');return false;};moreInfoDialog.submit(moreInfoDialogSubmit);initForm(moreInfoDialog,{width:500,no_cancel:true,open:function open(evt){keymap={};},alsoResize:'#more_info_readme'});$('#more_readme_button').click(function(){dispatcher.post('showForm',[moreInfoDialog]);});/* END "more collection information" dialog - related */var onKeyDown=function onKeyDown(evt){var code=evt.which;if(code===$.ui.keyCode.ESCAPE){dispatcher.post('messages',[false]);return;}if(currentForm){if(code===$.ui.keyCode.ENTER){// don't trigger submit in textareas to allow multiline text
// entry
// NOTE: spec seems to require this to be upper-case,
// but at least chrome 8.0.552.215 returns lowercased
var nodeType=evt.target.type?evt.target.type.toLowerCase():'';if(evt.target.nodeName&&evt.target.nodeName.toLowerCase()=='input'&&(nodeType=='text'||nodeType=='password')){currentForm.trigger('submit');return false;}}else if(evt.ctrlKey&&(code=='F'.charCodeAt(0)||code=='G'.charCodeAt(0))){// prevent Ctrl-F/Ctrl-G in forms
evt.preventDefault();return false;}return;}if(code===$.ui.keyCode.TAB){showFileBrowser();return false;}else if(code==$.ui.keyCode.LEFT){return moveInFileBrowser(-1);}else if(code===$.ui.keyCode.RIGHT){return moveInFileBrowser(+1);}else if(evt.shiftKey&&code===$.ui.keyCode.UP){autoPaging(true);}else if(evt.shiftKey&&code===$.ui.keyCode.DOWN){autoPaging(false);}else if(evt.ctrlKey&&code=='F'.charCodeAt(0)){evt.preventDefault();showSearchForm();}else if(searchActive&&evt.ctrlKey&&code=='G'.charCodeAt(0)){evt.preventDefault();return moveInFileBrowser(+1);}else if(searchActive&&evt.ctrlKey&&code=='K'.charCodeAt(0)){evt.preventDefault();clearSearchResults();}};var moveInFileBrowser=function moveInFileBrowser(dir){var pos=currentSelectorPosition();var newPos=pos+dir;if(newPos>=0&&newPos<selectorData.items.length&&selectorData.items[newPos][0]!="c"){// not at the start, and the previous is not a collection (dir)
dispatcher.post('allowReloadByURL');dispatcher.post('setDocument',[selectorData.items[newPos][2],selectorData.items[newPos][1]]);}return false;};/* Automatically proceed from document to document */var autoPagingTimeout=null;var autoPaging=function autoPaging(on){clearTimeout(autoPagingTimeout);if(on){autoPagingTimeout=setInterval(function(){moveInFileBrowser(+1);},2000);}};var resizeFunction=function resizeFunction(evt){dispatcher.post('renderData');};var resizerTimeout=null;var onResize=function onResize(evt){if(evt.target===window){clearTimeout(resizerTimeout);resizerTimeout=setTimeout(resizeFunction,100);// TODO is 100ms okay?
}};var collectionLoaded=function collectionLoaded(response){if(response.exception){if(response.exception=='annotationCollectionNotFound'||response.exception=='collectionNotAccessible'){// revert to last good
dispatcher.post('setCollection',[lastGoodCollection]);}else{dispatcher.post('messages',[[['Unknown error: '+response.exception,'error']]]);dispatcher.post('setCollection',['/']);}}else{lastGoodCollection=response.collection;fillDisambiguatorOptions(response.disambiguator_config);selectorData=response;documentListing=response;// 'backup'
searchConfig=response.search_config;selectorData.items.sort(docSortFunction);setupSearchTypes(response);// scroller at the top
docScroll=0;}};var searchResultsReceived=function searchResultsReceived(response){if(response.exception){;// TODO: reasonable reaction
}else{selectorData=response;sortOrder=[2,1];// reset
// NOTE: don't sort, allowing order in which
// responses are given to be used as default
//selectorData.items.sort(docSortFunction);
if(response.action.match(/Collection$/)){showFileBrowser();}else{var item=response.items[0];dispatcher.post('setDocument',[item[2],item[1]]);}$('#save_search').css('display','inline-block');}};var clearSearch=function clearSearch(dontShowFileBrowser){dispatcher.post('hideForm');// back off to document collection
if(searchActive){$('#save_search').css('display','none');selectorData=documentListing;sortOrder=collectionSortOrder;selectorData.items.sort(docSortFunction);searchActive=false;updateSearchButtons();}if(!dontShowFileBrowser){showFileBrowser();}};var saveSVGTimer=null;var saveSVG=function saveSVG(){if(currentDocumentSVGsaved){// no need to store again
return false;}clearTimeout(saveSVGTimer);$('#stored_file_regenerate').hide();$('#stored_file_spinner').show();saveSVGTimer=dispatcher.post(1,'ajax',[{action:'storeSVG',svg:$('#svg').html(),collection:coll,document:doc},'savedSVG']);};var onDoneRendering=function onDoneRendering(coll,doc,args){if(args&&!args.edited){var svgtop=$('svg').offset().top;var $inFocus=$('#svg animate[data-type="focus"]:first').parent();if($inFocus.length){$('html,body').animate({scrollTop:$inFocus.offset().top-svgtop-window.innerHeight/2},{duration:'slow',easing:'swing'});}}dispatcher.post('allowReloadByURL');if(!currentForm){$('#waiter').dialog('close');}};var onStartedRendering=function onStartedRendering(){hideForm();if(!currentForm){$('#waiter').dialog('open');}};var savedSVGreceived=function savedSVGreceived(response){$('#stored_file_spinner').hide();if(response&&response.exception=='corruptSVG'){dispatcher.post('messages',[[['Cannot save SVG: corrupt','error']]]);return;}var $downloadStored=$('#download_stored').empty().show();$.each(response.stored,function(storedNo,stored){var params={'action':'retrieveStored','document':doc,'suffix':stored.suffix,// TODO: Extract the protocol version into somewhere global
'protocol':1};var $downloadLink=$('<a id="download_'+stored.name+'"'+' target="'+stored.name+'"'+'>'+stored.name+'</a>');$downloadLink.attr('href','ajax.cgi?'+$.param(params));$downloadLink.button();if(storedNo)$downloadStored.append(' ');$downloadStored.append($downloadLink);});currentDocumentSVGsaved=true;};var invalidateSavedSVG=function invalidateSavedSVG(){// assuming that invalidation of the SVG invalidates all stored
// static visualizations, as others are derived from the SVG
$('#download_stored').hide();// have a way to regenerate if dialog open when data invalidated
$('#stored_file_regenerate').show();currentDocumentSVGsaved=false;};var onNewSourceData=function onNewSourceData(sourceData){if(!sourceData)return;var $sourceFiles=$('#source_files').empty();/* Add download links for all available extensions */$.each(sourceData.source_files,function(extNo,ext){var $link=$('<a target="brat_search"/>').text(ext).attr('href','ajax.cgi?action=downloadFile&collection='+encodeURIComponent(coll)+'&document='+encodeURIComponent(doc)+'&extension='+encodeURIComponent(ext)+// TODO: Extract the protocol version into somewhere global
'&protocol='+1);$link.button();if(extNo)$sourceFiles.append(' ');$sourceFiles.append($link);});/* Add a download link for the whole collection */invalidateSavedSVG();mtime=sourceData.mtime;if(mtime){// we're getting seconds and need milliseconds
//$('#document_ctime').text("Created: " + Annotator.formatTime(1000 * sourceData.ctime)).css("display", "inline");
$('#document_mtime').text("Last modified: "+Util.formatTimeAgo(1000*mtime)).show();}else{//$('#document_ctime').css("display", "none");
$('#document_mtime').hide();}};//BRAT STANDALONE LIBRARY BEGIN
//We do no use notion of documents
/**/var gotCurrent=function gotCurrent(_coll,_doc,_args){var oldColl=coll;coll=_coll;doc=_doc;args=_args;// if we have a specific document, hide the "no document" message
if(_doc){hideNoDocMessage();}// if we have a collection change, update "collection download" and
// "side-by-side comparison" buttons
if(oldColl!=coll){var $sourceCollection=$('#source_collection').empty();var $collectionDownloadLink=$('<a target="brat_search"/>').text('Download tar.gz').attr('href','ajax.cgi?action=downloadCollection&collection='+encodeURIComponent(coll)// TODO: Extract the protocol version into somewhere global
+'&protocol='+1);$sourceCollection.append($collectionDownloadLink);$collectionDownloadLink.button();$cmpButton=$('#side-by-side_cmp').empty();var $cmpLink=$('<a target="_blank"/>').text('Comparison mode').attr('href','diff.xhtml?diff='+encodeURIComponent(coll));$cmpButton.append($cmpLink);$cmpLink.button();}//BRAT STANDALONE LIBRARY BEGIN
/*
        $docName = $('#document_name input').val(coll + doc);
        var docName = $docName[0];
        // TODO do this on resize, as well
        // scroll the document name to the right, so the name is visible
        // (even if the collection name isn't, fully)
        docName.scrollLeft = docName.scrollWidth;

        $('#document_mtime').hide();
        *///BRAT STANDALONE LIBRARY END
invalidateSavedSVG();};/**///BRAT STANDALONE LIBRARY END
var slideToggle=function slideToggle(el,show,autoHeight,bottom){var el=$(el);var visible=el.is(":visible");var height;if(show===undefined)show=!visible;// @amadanmath: commenting this out appears to remove the annoying
// misfeature where it's possible to stop the menu halfway by
// mousing out and back in during closing. Please check that
// this doesn't introduce other trouble and remove these lines.
//         if (show === visible) return false;
if(!autoHeight){height=el.data("cachedHeight");}else{el.height('auto');}if(!height){height=el.show().height();el.data('cachedHeight',height);if(!visible)el.hide().css({height:0});}if(show){el.show().animate({height:height},{duration:150,complete:function complete(){if(autoHeight){el.height('auto');}},step:bottom?function(now,fx){fx.elem.scrollTop=fx.elem.scrollHeight;}:undefined});}else{el.animate({height:0},{duration:300,complete:function complete(){el.hide();}});}};var menuTimer=null;$('#header').mouseenter(function(evt){clearTimeout(menuTimer);slideToggle($('#pulldown').stop(),true);}).mouseleave(function(evt){clearTimeout(menuTimer);menuTimer=setTimeout(function(){slideToggle($('#pulldown').stop(),false);},500);});$('#label_abbreviations input').click(function(evt){var val=this.value;val=val==='on';if(val){dispatcher.post('messages',[[['Abbreviations are now on','comment']]]);}else{dispatcher.post('messages',[[['Abbreviations are now off','comment']]]);}dispatcher.post('abbrevs',[val]);// TODO: XXX: for some insane reason, doing the following call
// synchronously breaks the checkbox (#456). If you ever figure
// out why, it would make more sense to call
//    dispatcher.post('resetData');
// without the asynch.
dispatcher.post(1,'resetData');});$('#text_backgrounds input').click(function(evt){var val=this.value;dispatcher.post('textBackgrounds',[val]);// TODO: XXX: see comment above for why this is asynchronous
dispatcher.post(1,'resetData');});$('#layout_density input').click(function(evt){var val=this.value;dispatcher.post('layoutDensity',[val]);// TODO: XXX: see comment above for why this is asynchronous
dispatcher.post(1,'resetData');return false;});$('#svg_width_unit input').click(function(evt){var width_unit=this.value;var width_value=$('#svg_width_value')[0].value;var val=width_value+width_unit;dispatcher.post('svgWidth',[val]);// TODO: XXX: see comment above for why this is asynchronous
dispatcher.post(1,'resetData');return false;});$('#annotation_speed input').click(function(evt){var val=this.value;dispatcher.post('annotationSpeed',[val]);return false;});$('#pulldown').find('input').button();var headerHeight=$('#mainHeader').height();$('#svg').css('margin-top',headerHeight+10);aboutDialog=$('#about');aboutDialog.dialog({autoOpen:false,closeOnEscape:true,resizable:false,modal:true,open:function open(){aboutDialog.find('*').blur();},beforeClose:function beforeClose(){currentForm=null;}});$('#mainlogo').click(function(){showForm(aboutDialog);});// TODO: copy from annotator_ui; DRY it up
var adjustFormToCursor=function adjustFormToCursor(evt,element){var screenHeight=$(window).height()-8;// TODO HACK - no idea why -8 is needed
var screenWidth=$(window).width()-8;var elementHeight=element.height();var elementWidth=element.width();var y=Math.min(evt.clientY,screenHeight-elementHeight);var x=Math.min(evt.clientX,screenWidth-elementWidth);element.css({top:y,left:x});};var viewspanForm=$('#viewspan_form');var onSingleClick=function onSingleClick(evt){var target=$(evt.target);var id;if(id=target.attr('data-span-id')){var span=data.spans[id];dispatcher.post('sglclick',[span]);}};var onDblClick=function onDblClick(evt){if(user&&annotationAvailable)return;var target=$(evt.target);var id;if(id=target.attr('data-span-id')){window.getSelection().removeAllRanges();var span=data.spans[id];var urlHash=URLHash.parse(window.location.hash);urlHash.setArgument('focus',[[span.id]]);$('#viewspan_highlight_link').show().attr('href',urlHash.getHash());$('#viewspan_selected').text(span.text);var encodedText=encodeURIComponent(span.text);$.each(searchConfig,function(searchNo,search){$('#viewspan_'+search[0]).attr('href',search[1].replace('%s',encodedText));});// annotator comments
$('#viewspan_notes').val(span.annotatorNotes||'');dispatcher.post('showForm',[viewspanForm]);$('#viewspan_form-ok').focus();adjustFormToCursor(evt,viewspanForm.parent());}};viewspanForm.submit(function(evt){dispatcher.post('hideForm');return false;});var authForm=$('#auth_form');initForm(authForm,{resizable:false});var authFormSubmit=function authFormSubmit(evt){dispatcher.post('hideForm');var _user=$('#auth_user').val();var password=$('#auth_pass').val();dispatcher.post('ajax',[{action:'login',user:_user,password:password},function(response){if(response.exception){dispatcher.post('showForm',[authForm]);$('#auth_user').select().focus();}else{user=_user;$('#auth_button').val('Logout '+user);$('#auth_user').val('');$('#auth_pass').val('');$('.login').show();dispatcher.post('user',[user]);}}]);return false;};$('#auth_button').click(function(evt){if(user){dispatcher.post('ajax',[{action:'logout'},function(response){user=null;$('#auth_button').val('Login');$('.login').hide();dispatcher.post('user',[null]);}]);}else{dispatcher.post('showForm',[authForm]);}});authForm.submit(authFormSubmit);var tutorialForm=$('#tutorial');if(!$.browser.webkit){// Inject the browser warning
$('#browserwarning').css('display','block');}initForm(tutorialForm,{width:800,height:600,no_cancel:true,no_ok:true,buttons:[{id:"tutorial-ok",text:"OK",click:function click(){tutorialForm.dialog('close');}}],close:function close(){if(fileBrowserWaiting){showFileBrowser();}}});var init=function init(){dispatcher.post('initForm',[viewspanForm,{width:760,no_cancel:true}]);dispatcher.post('ajax',[{action:'whoami'},function(response){var auth_button=$('#auth_button');if(response.user){user=response.user;dispatcher.post('messages',[[['Welcome back, user "'+user+'"','comment']]]);auth_button.val('Logout '+user);dispatcher.post('user',[user]);$('.login').show();}else{user=null;auth_button.val('Login');dispatcher.post('user',[null]);$('.login').hide();// don't show tutorial if there's a specific document (annoyance)
if(!doc){dispatcher.post('showForm',[tutorialForm]);$('#tutorial-ok').focus();}}},{keep:true}]);dispatcher.post('ajax',[{action:'loadConf'},function(response){if(response.config!=undefined){// TODO: check for exceptions
try{Configuration=JSON.parse(response.config);}catch(x){// XXX Bad config
Configuration={};dispatcher.post('messages',[[['Corrupted configuration; resetting.','error']]]);configurationChanged();}// TODO: make whole-object assignment work
// @amadanmath: help! This code is horrible
// Configuration.svgWidth = storedConf.svgWidth;
dispatcher.post('svgWidth',[Configuration.svgWidth]);// Configuration.abbrevsOn = storedConf.abbrevsOn == "true";
// Configuration.textBackgrounds = storedConf.textBackgrounds;
// Configuration.rapidModeOn = storedConf.rapidModeOn == "true";
// Configuration.confirmModeOn = storedConf.confirmModeOn == "true";
// Configuration.autorefreshOn = storedConf.autorefreshOn == "true";
if(Configuration.autorefreshOn){checkForDocumentChanges();}// Configuration.visual.margin.x = parseInt(storedConf.visual.margin.x);
// Configuration.visual.margin.y = parseInt(storedConf.visual.margin.y);
// Configuration.visual.boxSpacing = parseInt(storedConf.visual.boxSpacing);
// Configuration.visual.curlyHeight = parseInt(storedConf.visual.curlyHeight);
// Configuration.visual.arcSpacing = parseInt(storedConf.visual.arcSpacing);
// Configuration.visual.arcStartHeight = parseInt(storedConf.visual.arcStartHeight);
}dispatcher.post('configurationUpdated');}]);};var noFileSpecified=function noFileSpecified(){// not (only) an error, so no messaging
dispatcher.post('clearSVG');showFileBrowser();};var showUnableToReadTextFile=function showUnableToReadTextFile(){dispatcher.post('messages',[[['Unable to read the text file.','error']]]);dispatcher.post('clearSVG');showFileBrowser();};var showAnnotationFileNotFound=function showAnnotationFileNotFound(){dispatcher.post('messages',[[['Annotation file not found.','error']]]);dispatcher.post('clearSVG');showFileBrowser();};var showUnknownError=function showUnknownError(exception){dispatcher.post('messages',[[['Unknown error: '+exception,'error']]]);dispatcher.post('clearSVG');showFileBrowser();};var reloadDirectoryWithSlash=function reloadDirectoryWithSlash(sourceData){var collection=sourceData.collection+sourceData.document+'/';dispatcher.post('setCollection',[collection,'',sourceData.arguments]);};// TODO: confirm attributeTypes unnecessary and remove
//       var spanAndAttributeTypesLoaded = function(_spanTypes, _attributeTypes) {
//         spanTypes = _spanTypes;
//         attributeTypes = _attributeTypes;
//       };
// TODO: spanAndAttributeTypesLoaded is obviously not descriptive of
// the full function. Rename reasonably.
var spanAndAttributeTypesLoaded=function spanAndAttributeTypesLoaded(_spanTypes,_entityAttributeTypes,_eventAttributeTypes,_relationTypesHash){spanTypes=_spanTypes;relationTypesHash=_relationTypesHash;};var annotationIsAvailable=function annotationIsAvailable(){annotationAvailable=true;};// hide anything requiring login, just in case
$('.login').hide();// XXX TODO a lot
var touchStart;var onTouchStart=function onTouchStart(evt){// evt.preventDefault();
evt=evt.originalEvent;if(evt.touches.length==1){// single touch; start tracking to see if we're doing
// left/right
touchStart=$.extend({},evt.touches[0]);// clone
}else if(evt.touches.length==4){// 4 finger tap: file browser
showFileBrowser();return false;}};var onTouchEnd=function onTouchEnd(evt){// evt.preventDefault();
evt=evt.originalEvent;$.each(evt.changedTouches,function(touchEndNo,touchEnd){if(touchStart.identifier==touchEnd.identifier){var dx=touchEnd.screenX-touchStart.screenX;var dy=touchEnd.screenY-touchStart.screenY;var adx=Math.abs(dx);var ady=Math.abs(dy);if(adx>200&&ady<adx/2){// it's left/right!
return moveInFileBrowser(dx<0?-1:+1);}}});};var documentChangesTimer=null;var maxDocumentChangesTimeout=32*1000;var documentChangesTimeout=1*1000;var checkForDocumentChanges=function checkForDocumentChanges(){if(coll&&doc&&dispatcher.post('isReloadOkay',[],'all')){opts={'action':'getDocumentTimestamp','collection':coll,'document':doc};dispatcher.post('ajax',[opts,function(response){if(data){if(mtime!=response.mtime){dispatcher.post('current',[coll,doc,args,true]);documentChangesTimeout=1*1000;}else{documentChangesTimeout*=2;if(documentChangesTimeout>=maxDocumentChangesTimeout)documentChangesTimeout=maxDocumentChangesTimeout;}}}]);}else{documentChangesTimeout=1*1000;}documentChangesTimer=setTimeout(checkForDocumentChanges,documentChangesTimeout);};if(Configuration.autorefreshOn){checkForDocumentChanges();}$('#autorefresh_mode').click(function(evt){var val=this.checked;if(val){Configuration.autorefreshOn=true;checkForDocumentChanges();dispatcher.post('messages',[[['Autorefresh mode is now on','comment']]]);}else{Configuration.autorefreshOn=false;clearTimeout(documentChangesTimer);dispatcher.post('messages',[[['Autorefresh mode is now off','comment']]]);}dispatcher.post('configurationChanged');});var isReloadOkay=function isReloadOkay(){// do not reload while the user is in the dialog
return currentForm==null;};var configurationChanged=function configurationChanged(){// just assume that any config change makes stored
// visualizations invalid. This is a bit excessive (not all
// options affect visualization) but mostly harmless.
invalidateSavedSVG();// save configuration changed by user action
dispatcher.post('ajax',[{action:'saveConf',config:JSON.stringify(Configuration)},null]);};//BRAT STANDALONE LIBRARY BEGIN
//Config must be managed outside the component
/*
      var updateConfigurationUI = function() {
        // update UI to reflect non-user config changes (e.g. load)
        
        // Annotation mode
        if (Configuration.confirmModeOn) {
          $('#annotation_speed1')[0].checked = true;
        } else if (Configuration.rapidModeOn) {
          $('#annotation_speed3')[0].checked = true;
        } else {
          $('#annotation_speed2')[0].checked = true;
        }
        $('#annotation_speed input').button('refresh');

        // Label abbrevs
        $('#label_abbreviations_on')[0].checked  = Configuration.abbrevsOn;
        $('#label_abbreviations_off')[0].checked = !Configuration.abbrevsOn; 
        $('#label_abbreviations input').button('refresh');

        // Text backgrounds        
        $('#text_backgrounds input[value="'+Configuration.textBackgrounds+'"]')[0].checked = true;
        $('#text_backgrounds input').button('refresh');

        // SVG width
        var splitSvgWidth = Configuration.svgWidth.match(/^(.*?)(px|\%)$/);
        if (!splitSvgWidth) {
          // TODO: reset to sensible value?
          dispatcher.post('messages', [[['Error parsing SVG width "'+Configuration.svgWidth+'"', 'error', 2]]]);
        } else {
          $('#svg_width_value')[0].value = splitSvgWidth[1];
          $('#svg_width_unit input[value="'+splitSvgWidth[2]+'"]')[0].checked = true;
          $('#svg_width_unit input').button('refresh');
        }

        // Autorefresh
        $('#autorefresh_mode')[0].checked = Configuration.autorefreshOn;
        $('#autorefresh_mode').button('refresh');
      }*/$('#prev').button().click(function(){return moveInFileBrowser(-1);});$('#next').button().click(function(){return moveInFileBrowser(+1);});$('#footer').show();var rememberData=function rememberData(_data){if(_data&&!_data.exception){data=_data;}};var onScreamingHalt=function onScreamingHalt(){$('#waiter').dialog('close');$('#pulldown, #navbuttons, #spinner').remove();dispatcher.post('hideForm');};dispatcher.on('init',init).on('dataReady',rememberData).on('annotationIsAvailable',annotationIsAvailable).on('messages',displayMessages).on('displaySpanComment',displaySpanComment).on('displayArcComment',displayArcComment).on('displaySentComment',displaySentComment).on('docChanged',onDocChanged).on('hideComment',hideComment).on('showForm',showForm).on('hideForm',hideForm).on('initForm',initForm).on('collectionLoaded',rememberNormDb).on('collectionLoaded',collectionLoaded).on('spanAndAttributeTypesLoaded',spanAndAttributeTypesLoaded).on('isReloadOkay',isReloadOkay).on('current',gotCurrent).on('doneRendering',onDoneRendering).on('startedRendering',onStartedRendering).on('newSourceData',onNewSourceData).on('savedSVG',savedSVGreceived).on('renderError:noFileSpecified',noFileSpecified).on('renderError:annotationFileNotFound',showAnnotationFileNotFound).on('renderError:unableToReadTextFile',showUnableToReadTextFile).on('renderError:isDirectoryError',reloadDirectoryWithSlash).on('unknownError',showUnknownError).on('keydown',onKeyDown).on('mousemove',onMouseMove).on('dblclick',onDblClick).on('click',onSingleClick).on('touchstart',onTouchStart).on('touchend',onTouchEnd).on('resize',onResize).on('searchResultsReceived',searchResultsReceived).on('clearSearch',clearSearch).on('clearSVG',showNoDocMessage).on('screamingHalt',onScreamingHalt).//on('configurationUpdated', updateConfigurationUI).
on('configurationChanged',configurationChanged);};return VisualizerUI;}(jQuery,window);// BRAT STANDALONE LIBRARY BEGIN
// Browserify export
module.exports=VisualizerUI;// BRAT STANDALONE LIBRARY END
},{}],19:[function(require,module,exports){window.$=require('./client/lib/node-jquery-1.7.1');//require('jquery-node-browserify'); // @1.7.2 ++
LONG_ANNOTATION_CONST="LongAnnotation";window.BratFrontendEditor=function(element,collData,docData,options){var _newOptions;if(!(element instanceof Element)){throw new Error('element should be an instance of Element');}collData=collData||{};docData=docData||{};options=options||{};//DEFAULT OPTIONS
newOptions=(_newOptions={activateEdition:true,overWriteModals:false,showTooltip:false,assetsPath:"static/",maxFragmentLength:40},_defineProperty(_newOptions,"showTooltip",true),_defineProperty(_newOptions,"overWriteModals",false),_defineProperty(_newOptions,"webFontURLs",['fonts/Astloch-Bold.ttf','fonts/PT_Sans-Caption-Web-Regular.ttf','fonts/Liberation_Sans-Regular.ttf']),_defineProperty(_newOptions,"fontLoadTimeout",5000),_defineProperty(_newOptions,"ajax",'local'),_newOptions);// If option defined, over-write newOptions
for(var opt in options){if(options.hasOwnProperty(opt)){newOptions[opt]=options[opt];}}this.element=element;this.collData=collData;this.docData=docData;this.options=newOptions;this.init();};BratFrontendEditor.prototype={constructor:BratFrontendEditor,init:function init(){var self=this;var html=require('./brat.html');self.element.innerHTML=html;self.setHtmlImgSrc();window.jQuery=$;(function($){// require('./index.css'); //TODO: If possible, include css in min.js (browserify-css)
require('./client/lib/jquery-ui.min');require('./client/lib/jquery.svg.min');require('./client/lib/jquery.svgdom.min');require('jquery-bbq');require('./client/lib/jquery.sprintf');require('./client/lib/jquery.json.min');//TODO Fix this error
window.WebFont=require('./client/lib/webfont.js').WebFont;//Uncaught TypeError: Cannot set property 'WebFont' of undefined
//brat global helpers
var Config=require('./client/src/configuration');window.Configuration=new Config();window.Util=require('./client/src/util');// brat modules
window.Dispatcher=require('./client/src/dispatcher');window.URLHash=require('./client/src/url_hash');//TODO Figure out
window.LocalAjax=require('./client/src/local_ajax');window.Ajax=require('./client/src/ajax.js');window.Visualizer=require('./client/src/visualizer');window.VisualizerUI=require('./client/src/visualizer_ui');window.AnnotatorUI=require('./client/src/annotator_ui');window.Spinner=require('./client/src/spinner');$(document).ready(function(){self.dispatcher=new Dispatcher();switch(self.options.ajax){case'local':self.ajax=new LocalAjax(self.dispatcher,self.options.maxFragmentLength);break;case'normal':self.ajax=new Ajax(self.dispatcher);break;case'external':break;default:self.ajax=new LocalAjax(self.dispatcher,self.options.maxFragmentLength);break;}var absoluteWebFontsURLS=[self.options.assetsPath+self.options.webFontURLs[0],self.options.assetsPath+self.options.webFontURLs[1],self.options.assetsPath+self.options.webFontURLs[2]];self.visualizer=new Visualizer(self.element,self.dispatcher,'svg',absoluteWebFontsURLS,self.options.fontLoadTimeout);self.svg=self.visualizer.svg;if(self.options.activateEdition===true){self.visualizerUI=new VisualizerUI(self.dispatcher,self.svg,self.options.showTooltip,self.options.overWriteModals);self.annotatorUI=new AnnotatorUI(self.dispatcher,self.svg);// self.spinner = new Spinner(self.dispatcher, '#spinner');
}self.dispatcher.post('init');if(self.options.maxFragmentLength>0){self.addLongAnnotationEntityAttribute();}self.docData.collection=null;self.dispatcher.post('collectionLoaded',[self.collData]);self.dispatcher.post('requestRenderData',[self.docData]);self.dispatcher.post('current',[self.collData,self.docData,{}]);});})($);},addLongAnnotationEntityAttribute:function addLongAnnotationEntityAttribute(){// Special symbol for splitted long annotations
this.collData.entity_attribute_types.push({"name":LONG_ANNOTATION_CONST,"type":LONG_ANNOTATION_CONST,"values":{LONG_ANNOTATION_CONST:{"glyph":"↹"}}});this.collData.entity_types.forEach(function(type){type.attributes.push(LONG_ANNOTATION_CONST);});},setHtmlImgSrc:function setHtmlImgSrc(){var spinners=this.element.getElementsByClassName("brat-spinner");var magnifiers=this.element.getElementsByClassName("brat-fugue-shadowless-magnifier");var externals=this.element.getElementsByClassName("brat-fugue-shadowless-external");if(spinners&&spinners.length){spinners[0].src=this.options.assetsPath+'img/spinner.gif';}if(magnifiers&&magnifiers.length){magnifiers[0].src=this.options.assetsPath+'img/Fugue-shadowless-magnifier.png';}if(externals&&externals.length){externals[0].src=this.options.assetsPath+'img/Fugue-shadowless-external.png';}}};},{"./brat.html":1,"./client/lib/jquery-ui.min":2,"./client/lib/jquery.json.min":3,"./client/lib/jquery.sprintf":4,"./client/lib/jquery.svg.min":5,"./client/lib/jquery.svgdom.min":6,"./client/lib/node-jquery-1.7.1":7,"./client/lib/webfont.js":8,"./client/src/ajax.js":9,"./client/src/annotator_ui":10,"./client/src/configuration":11,"./client/src/dispatcher":12,"./client/src/local_ajax":13,"./client/src/spinner":14,"./client/src/url_hash":15,"./client/src/util":16,"./client/src/visualizer":17,"./client/src/visualizer_ui":18,"jquery-bbq":20}],20:[function(require,module,exports){/*!
 * jQuery BBQ: Back Button & Query Library - v1.3pre - 8/26/2010
 * http://benalman.com/projects/jquery-bbq-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */// Script: jQuery BBQ: Back Button & Query Library
//
// *Version: 1.3pre, Last updated: 8/26/2010*
//
// Project Home - http://benalman.com/projects/jquery-bbq-plugin/
// GitHub       - http://github.com/cowboy/jquery-bbq/
// Source       - http://github.com/cowboy/jquery-bbq/raw/master/jquery.ba-bbq.js
// (Minified)   - http://github.com/cowboy/jquery-bbq/raw/master/jquery.ba-bbq.min.js (2.2kb gzipped)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
//
// Basic AJAX     - http://benalman.com/code/projects/jquery-bbq/examples/fragment-basic/
// Advanced AJAX  - http://benalman.com/code/projects/jquery-bbq/examples/fragment-advanced/
// jQuery UI Tabs - http://benalman.com/code/projects/jquery-bbq/examples/fragment-jquery-ui-tabs/
// Deparam        - http://benalman.com/code/projects/jquery-bbq/examples/deparam/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
//                   Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
// Unit Tests      - http://benalman.com/code/projects/jquery-bbq/unit/
//
// About: Release History
//
// 1.3pre - (8/26/2010) Integrated <jQuery hashchange event> v1.3, which adds
//         document.title and document.domain support in IE6/7, BlackBerry
//         support, better Iframe hiding for accessibility reasons, and the new
//         <jQuery.fn.hashchange> "shortcut" method. Added the
//         <jQuery.param.sorted> method which reduces the possibility of
//         extraneous hashchange event triggering. Added the
//         <jQuery.param.fragment.ajaxCrawlable> method which can be used to
//         enable Google "AJAX Crawlable mode."
// 1.2.1 - (2/17/2010) Actually fixed the stale window.location Safari bug from
//         <jQuery hashchange event> in BBQ, which was the main reason for the
//         previous release!
// 1.2   - (2/16/2010) Integrated <jQuery hashchange event> v1.2, which fixes a
//         Safari bug, the event can now be bound before DOM ready, and IE6/7
//         page should no longer scroll when the event is first bound. Also
//         added the <jQuery.param.fragment.noEscape> method, and reworked the
//         <hashchange event (BBQ)> internal "add" method to be compatible with
//         changes made to the jQuery 1.4.2 special events API.
// 1.1.1 - (1/22/2010) Integrated <jQuery hashchange event> v1.1, which fixes an
//         obscure IE8 EmulateIE7 meta tag compatibility mode bug.
// 1.1   - (1/9/2010) Broke out the jQuery BBQ event.special <hashchange event>
//         functionality into a separate plugin for users who want just the
//         basic event & back button support, without all the extra awesomeness
//         that BBQ provides. This plugin will be included as part of jQuery BBQ,
//         but also be available separately. See <jQuery hashchange event>
//         plugin for more information. Also added the <jQuery.bbq.removeState>
//         method and added additional <jQuery.deparam> examples.
// 1.0.3 - (12/2/2009) Fixed an issue in IE 6 where location.search and
//         location.hash would report incorrectly if the hash contained the ?
//         character. Also <jQuery.param.querystring> and <jQuery.param.fragment>
//         will no longer parse params out of a URL that doesn't contain ? or #,
//         respectively.
// 1.0.2 - (10/10/2009) Fixed an issue in IE 6/7 where the hidden IFRAME caused
//         a "This page contains both secure and nonsecure items." warning when
//         used on an https:// page.
// 1.0.1 - (10/7/2009) Fixed an issue in IE 8. Since both "IE7" and "IE8
//         Compatibility View" modes erroneously report that the browser
//         supports the native window.onhashchange event, a slightly more
//         robust test needed to be added.
// 1.0   - (10/2/2009) Initial release
(function($,window){console.info('yes!');'$:nomunge';// Used by YUI compressor.
// Some convenient shortcuts.
var undefined,aps=Array.prototype.slice,decode=decodeURIComponent,// Method / object references.
jq_param=$.param,jq_param_sorted,jq_param_fragment,jq_deparam,jq_deparam_fragment,jq_bbq=$.bbq=$.bbq||{},jq_bbq_pushState,jq_bbq_getState,jq_elemUrlAttr,special=$.event.special,// Reused strings.
str_hashchange='hashchange',str_querystring='querystring',str_fragment='fragment',str_elemUrlAttr='elemUrlAttr',str_href='href',str_src='src',// Reused RegExp.
re_params_querystring=/^.*\?|#.*$/g,re_params_fragment,re_fragment,re_no_escape,ajax_crawlable,fragment_prefix,// Used by jQuery.elemUrlAttr.
elemUrlAttr_cache={};// A few commonly used bits, broken out to help reduce minified file size.
function is_string(arg){return typeof arg==='string';};// Why write the same function twice? Let's curry! Mmmm, curry..
function curry(func){var args=aps.call(arguments,1);return function(){return func.apply(this,args.concat(aps.call(arguments)));};};// Get location.hash (or what you'd expect location.hash to be) sans any
// leading #. Thanks for making this necessary, Firefox!
function get_fragment(url){return url.replace(re_fragment,'$2');};// Get location.search (or what you'd expect location.search to be) sans any
// leading #. Thanks for making this necessary, IE6!
function get_querystring(url){return url.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/,'$1');};// Section: Param (to string)
//
// Method: jQuery.param.querystring
//
// Retrieve the query string from a URL or if no arguments are passed, the
// current window.location.href.
//
// Usage:
//
// > jQuery.param.querystring( [ url ] );
//
// Arguments:
//
//  url - (String) A URL containing query string params to be parsed. If url
//    is not passed, the current window.location.href is used.
//
// Returns:
//
//  (String) The parsed query string, with any leading "?" removed.
//
// Method: jQuery.param.querystring (build url)
//
// Merge a URL, with or without pre-existing query string params, plus any
// object, params string or URL containing query string params into a new URL.
//
// Usage:
//
// > jQuery.param.querystring( url, params [, merge_mode ] );
//
// Arguments:
//
//  url - (String) A valid URL for params to be merged into. This URL may
//    contain a query string and/or fragment (hash).
//  params - (String) A params string or URL containing query string params to
//    be merged into url.
//  params - (Object) A params object to be merged into url.
//  merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not
//    specified, and is as-follows:
//
//    * 0: params in the params argument will override any query string
//         params in url.
//    * 1: any query string params in url will override params in the params
//         argument.
//    * 2: params argument will completely replace any query string in url.
//
// Returns:
//
//  (String) A URL with a urlencoded query string in the format '?a=b&c=d&e=f'.
// Method: jQuery.param.fragment
//
// Retrieve the fragment (hash) from a URL or if no arguments are passed, the
// current window.location.href.
//
// Usage:
//
// > jQuery.param.fragment( [ url ] );
//
// Arguments:
//
//  url - (String) A URL containing fragment (hash) params to be parsed. If
//    url is not passed, the current window.location.href is used.
//
// Returns:
//
//  (String) The parsed fragment (hash) string, with any leading "#" removed.
// Method: jQuery.param.fragment (build url)
//
// Merge a URL, with or without pre-existing fragment (hash) params, plus any
// object, params string or URL containing fragment (hash) params into a new
// URL.
//
// Usage:
//
// > jQuery.param.fragment( url, params [, merge_mode ] );
//
// Arguments:
//
//  url - (String) A valid URL for params to be merged into. This URL may
//    contain a query string and/or fragment (hash).
//  params - (String) A params string or URL containing fragment (hash) params
//    to be merged into url.
//  params - (Object) A params object to be merged into url.
//  merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not
//    specified, and is as-follows:
//
//    * 0: params in the params argument will override any fragment (hash)
//         params in url.
//    * 1: any fragment (hash) params in url will override params in the
//         params argument.
//    * 2: params argument will completely replace any query string in url.
//
// Returns:
//
//  (String) A URL with a urlencoded fragment (hash) in the format '#a=b&c=d&e=f'.
function jq_param_sub(is_fragment,get_func,url,params,merge_mode){var result,qs,matches,url_params,hash;if(params!==undefined){// Build URL by merging params into url string.
// matches[1] = url part that precedes params, not including trailing ?/#
// matches[2] = params, not including leading ?/#
// matches[3] = if in 'querystring' mode, hash including leading #, otherwise ''
matches=url.match(is_fragment?re_fragment:/^([^#?]*)\??([^#]*)(#?.*)/);// Get the hash if in 'querystring' mode, and it exists.
hash=matches[3]||'';if(merge_mode===2&&is_string(params)){// If merge_mode is 2 and params is a string, merge the fragment / query
// string into the URL wholesale, without converting it into an object.
qs=params.replace(is_fragment?re_params_fragment:re_params_querystring,'');}else{// Convert relevant params in url to object.
url_params=jq_deparam(matches[2]);params=is_string(params)// Convert passed params string into object.
?jq_deparam[is_fragment?str_fragment:str_querystring](params)// Passed params object.
:params;qs=merge_mode===2?params// passed params replace url params
:merge_mode===1?$.extend({},params,url_params)// url params override passed params
:$.extend({},url_params,params);// passed params override url params
// Convert params object into a sorted params string.
qs=jq_param_sorted(qs);// Unescape characters specified via $.param.noEscape. Since only hash-
// history users have requested this feature, it's only enabled for
// fragment-related params strings.
if(is_fragment){qs=qs.replace(re_no_escape,decode);}}// Build URL from the base url, querystring and hash. In 'querystring'
// mode, ? is only added if a query string exists. In 'fragment' mode, #
// is always added.
result=matches[1]+(is_fragment?fragment_prefix:qs||!matches[1]?'?':'')+qs+hash;}else{// If URL was passed in, parse params from URL string, otherwise parse
// params from window.location.href.
result=get_func(url!==undefined?url:location.href);}return result;};jq_param[str_querystring]=curry(jq_param_sub,0,get_querystring);jq_param[str_fragment]=jq_param_fragment=curry(jq_param_sub,1,get_fragment);// Method: jQuery.param.sorted
//
// Returns a params string equivalent to that returned by the internal
// jQuery.param method, but sorted, which makes it suitable for use as a
// cache key.
//
// For example, in most browsers jQuery.param({z:1,a:2}) returns "z=1&a=2"
// and jQuery.param({a:2,z:1}) returns "a=2&z=1". Even though both the
// objects being serialized and the resulting params strings are equivalent,
// if these params strings were set into the location.hash fragment
// sequentially, the hashchange event would be triggered unnecessarily, since
// the strings are different (even though the data described by them is the
// same). By sorting the params string, unecessary hashchange event triggering
// can be avoided.
//
// Usage:
//
// > jQuery.param.sorted( obj [, traditional ] );
//
// Arguments:
//
//  obj - (Object) An object to be serialized.
//  traditional - (Boolean) Params deep/shallow serialization mode. See the
//    documentation at http://api.jquery.com/jQuery.param/ for more detail.
//
// Returns:
//
//  (String) A sorted params string.
jq_param.sorted=jq_param_sorted=function jq_param_sorted(a,traditional){var arr=[],obj={};$.each(jq_param(a,traditional).split('&'),function(i,v){var key=v.replace(/(?:%5B|=).*$/,''),key_obj=obj[key];if(!key_obj){key_obj=obj[key]=[];arr.push(key);}key_obj.push(v);});return $.map(arr.sort(),function(v){return obj[v];}).join('&');};// Method: jQuery.param.fragment.noEscape
//
// Specify characters that will be left unescaped when fragments are created
// or merged using <jQuery.param.fragment>, or when the fragment is modified
// using <jQuery.bbq.pushState>. This option only applies to serialized data
// object fragments, and not set-as-string fragments. Does not affect the
// query string. Defaults to ",/" (comma, forward slash).
//
// Note that this is considered a purely aesthetic option, and will help to
// create URLs that "look pretty" in the address bar or bookmarks, without
// affecting functionality in any way. That being said, be careful to not
// unescape characters that are used as delimiters or serve a special
// purpose, such as the "#?&=+" (octothorpe, question mark, ampersand,
// equals, plus) characters.
//
// Usage:
//
// > jQuery.param.fragment.noEscape( [ chars ] );
//
// Arguments:
//
//  chars - (String) The characters to not escape in the fragment. If
//    unspecified, defaults to empty string (escape all characters).
//
// Returns:
//
//  Nothing.
jq_param_fragment.noEscape=function(chars){chars=chars||'';var arr=$.map(chars.split(''),encodeURIComponent);re_no_escape=new RegExp(arr.join('|'),'g');};// A sensible default. These are the characters people seem to complain about
// "uglifying up the URL" the most.
jq_param_fragment.noEscape(',/');// Method: jQuery.param.fragment.ajaxCrawlable
//
// TODO: DESCRIBE
//
// Usage:
//
// > jQuery.param.fragment.ajaxCrawlable( [ state ] );
//
// Arguments:
//
//  state - (Boolean) TODO: DESCRIBE
//
// Returns:
//
//  (Boolean) The current ajaxCrawlable state.
jq_param_fragment.ajaxCrawlable=function(state){if(state!==undefined){if(state){re_params_fragment=/^.*(?:#!|#)/;re_fragment=/^([^#]*)(?:#!|#)?(.*)$/;fragment_prefix='#!';}else{re_params_fragment=/^.*#/;re_fragment=/^([^#]*)#?(.*)$/;fragment_prefix='#';}ajax_crawlable=!!state;}return ajax_crawlable;};jq_param_fragment.ajaxCrawlable(0);// Section: Deparam (from string)
//
// Method: jQuery.deparam
//
// Deserialize a params string into an object, optionally coercing numbers,
// booleans, null and undefined values; this method is the counterpart to the
// internal jQuery.param method.
//
// Usage:
//
// > jQuery.deparam( params [, coerce ] );
//
// Arguments:
//
//  params - (String) A params string to be parsed.
//  coerce - (Boolean) If true, coerces any numbers or true, false, null, and
//    undefined to their actual value. Defaults to false if omitted.
//
// Returns:
//
//  (Object) An object representing the deserialized params string.
$.deparam=jq_deparam=function jq_deparam(params,coerce){var obj={},coerce_types={'true':!0,'false':!1,'null':null};// Iterate over all name=value pairs.
$.each(params.replace(/\+/g,' ').split('&'),function(j,v){var param=v.split('='),key=decode(param[0]),val,cur=obj,i=0,// If key is more complex than 'foo', like 'a[]' or 'a[b][c]', split it
// into its component parts.
keys=key.split(']['),keys_last=keys.length-1;// If the first keys part contains [ and the last ends with ], then []
// are correctly balanced.
if(/\[/.test(keys[0])&&/\]$/.test(keys[keys_last])){// Remove the trailing ] from the last keys part.
keys[keys_last]=keys[keys_last].replace(/\]$/,'');// Split first keys part into two parts on the [ and add them back onto
// the beginning of the keys array.
keys=keys.shift().split('[').concat(keys);keys_last=keys.length-1;}else{// Basic 'foo' style key.
keys_last=0;}// Are we dealing with a name=value pair, or just a name?
if(param.length===2){val=decode(param[1]);// Coerce values.
if(coerce){val=val&&!isNaN(val)?+val// number
:val==='undefined'?undefined// undefined
:coerce_types[val]!==undefined?coerce_types[val]// true, false, null
:val;// string
}if(keys_last){// Complex key, build deep object structure based on a few rules:
// * The 'cur' pointer starts at the object top-level.
// * [] = array push (n is set to array length), [n] = array if n is
//   numeric, otherwise object.
// * If at the last keys part, set the value.
// * For each keys part, if the current level is undefined create an
//   object or array based on the type of the next keys part.
// * Move the 'cur' pointer to the next level.
// * Rinse & repeat.
for(;i<=keys_last;i++){key=keys[i]===''?cur.length:keys[i];cur=cur[key]=i<keys_last?cur[key]||(keys[i+1]&&isNaN(keys[i+1])?{}:[]):val;}}else{// Simple key, even simpler rules, since only scalars and shallow
// arrays are allowed.
if($.isArray(obj[key])){// val is already an array, so push on the next value.
obj[key].push(val);}else if(obj[key]!==undefined){// val isn't an array, but since a second value has been specified,
// convert val into an array.
obj[key]=[obj[key],val];}else{// val is a scalar.
obj[key]=val;}}}else if(key){// No value was defined, so set something meaningful.
obj[key]=coerce?undefined:'';}});return obj;};// Method: jQuery.deparam.querystring
//
// Parse the query string from a URL or the current window.location.href,
// deserializing it into an object, optionally coercing numbers, booleans,
// null and undefined values.
//
// Usage:
//
// > jQuery.deparam.querystring( [ url ] [, coerce ] );
//
// Arguments:
//
//  url - (String) An optional params string or URL containing query string
//    params to be parsed. If url is omitted, the current
//    window.location.href is used.
//  coerce - (Boolean) If true, coerces any numbers or true, false, null, and
//    undefined to their actual value. Defaults to false if omitted.
//
// Returns:
//
//  (Object) An object representing the deserialized params string.
// Method: jQuery.deparam.fragment
//
// Parse the fragment (hash) from a URL or the current window.location.href,
// deserializing it into an object, optionally coercing numbers, booleans,
// null and undefined values.
//
// Usage:
//
// > jQuery.deparam.fragment( [ url ] [, coerce ] );
//
// Arguments:
//
//  url - (String) An optional params string or URL containing fragment (hash)
//    params to be parsed. If url is omitted, the current window.location.href
//    is used.
//  coerce - (Boolean) If true, coerces any numbers or true, false, null, and
//    undefined to their actual value. Defaults to false if omitted.
//
// Returns:
//
//  (Object) An object representing the deserialized params string.
function jq_deparam_sub(is_fragment,url_or_params,coerce){if(url_or_params===undefined||typeof url_or_params==='boolean'){// url_or_params not specified.
coerce=url_or_params;url_or_params=jq_param[is_fragment?str_fragment:str_querystring]();}else{url_or_params=is_string(url_or_params)?url_or_params.replace(is_fragment?re_params_fragment:re_params_querystring,''):url_or_params;}return jq_deparam(url_or_params,coerce);};jq_deparam[str_querystring]=curry(jq_deparam_sub,0);jq_deparam[str_fragment]=jq_deparam_fragment=curry(jq_deparam_sub,1);// Section: Element manipulation
//
// Method: jQuery.elemUrlAttr
//
// Get the internal "Default URL attribute per tag" list, or augment the list
// with additional tag-attribute pairs, in case the defaults are insufficient.
//
// In the <jQuery.fn.querystring> and <jQuery.fn.fragment> methods, this list
// is used to determine which attribute contains the URL to be modified, if
// an "attr" param is not specified.
//
// Default Tag-Attribute List:
//
//  a      - href
//  base   - href
//  iframe - src
//  img    - src
//  input  - src
//  form   - action
//  link   - href
//  script - src
//
// Usage:
//
// > jQuery.elemUrlAttr( [ tag_attr ] );
//
// Arguments:
//
//  tag_attr - (Object) An object containing a list of tag names and their
//    associated default attribute names in the format { tag: 'attr', ... } to
//    be merged into the internal tag-attribute list.
//
// Returns:
//
//  (Object) An object containing all stored tag-attribute values.
// Only define function and set defaults if function doesn't already exist, as
// the urlInternal plugin will provide this method as well.
$[str_elemUrlAttr]||($[str_elemUrlAttr]=function(obj){return $.extend(elemUrlAttr_cache,obj);})({a:str_href,base:str_href,iframe:str_src,img:str_src,input:str_src,form:'action',link:str_href,script:str_src});jq_elemUrlAttr=$[str_elemUrlAttr];// Method: jQuery.fn.querystring
//
// Update URL attribute in one or more elements, merging the current URL (with
// or without pre-existing query string params) plus any params object or
// string into a new URL, which is then set into that attribute. Like
// <jQuery.param.querystring (build url)>, but for all elements in a jQuery
// collection.
//
// Usage:
//
// > jQuery('selector').querystring( [ attr, ] params [, merge_mode ] );
//
// Arguments:
//
//  attr - (String) Optional name of an attribute that will contain a URL to
//    merge params or url into. See <jQuery.elemUrlAttr> for a list of default
//    attributes.
//  params - (Object) A params object to be merged into the URL attribute.
//  params - (String) A URL containing query string params, or params string
//    to be merged into the URL attribute.
//  merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not
//    specified, and is as-follows:
//
//    * 0: params in the params argument will override any params in attr URL.
//    * 1: any params in attr URL will override params in the params argument.
//    * 2: params argument will completely replace any query string in attr
//         URL.
//
// Returns:
//
//  (jQuery) The initial jQuery collection of elements, but with modified URL
//  attribute values.
// Method: jQuery.fn.fragment
//
// Update URL attribute in one or more elements, merging the current URL (with
// or without pre-existing fragment/hash params) plus any params object or
// string into a new URL, which is then set into that attribute. Like
// <jQuery.param.fragment (build url)>, but for all elements in a jQuery
// collection.
//
// Usage:
//
// > jQuery('selector').fragment( [ attr, ] params [, merge_mode ] );
//
// Arguments:
//
//  attr - (String) Optional name of an attribute that will contain a URL to
//    merge params into. See <jQuery.elemUrlAttr> for a list of default
//    attributes.
//  params - (Object) A params object to be merged into the URL attribute.
//  params - (String) A URL containing fragment (hash) params, or params
//    string to be merged into the URL attribute.
//  merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not
//    specified, and is as-follows:
//
//    * 0: params in the params argument will override any params in attr URL.
//    * 1: any params in attr URL will override params in the params argument.
//    * 2: params argument will completely replace any fragment (hash) in attr
//         URL.
//
// Returns:
//
//  (jQuery) The initial jQuery collection of elements, but with modified URL
//  attribute values.
function jq_fn_sub(mode,force_attr,params,merge_mode){if(!is_string(params)&&(typeof params==="undefined"?"undefined":_typeof(params))!=='object'){// force_attr not specified.
merge_mode=params;params=force_attr;force_attr=undefined;}return this.each(function(){var that=$(this),// Get attribute specified, or default specified via $.elemUrlAttr.
attr=force_attr||jq_elemUrlAttr()[(this.nodeName||'').toLowerCase()]||'',// Get URL value.
url=attr&&that.attr(attr)||'';// Update attribute with new URL.
that.attr(attr,jq_param[mode](url,params,merge_mode));});};$.fn[str_querystring]=curry(jq_fn_sub,str_querystring);$.fn[str_fragment]=curry(jq_fn_sub,str_fragment);// Section: History, hashchange event
//
// Method: jQuery.bbq.pushState
//
// Adds a 'state' into the browser history at the current position, setting
// location.hash and triggering any bound <hashchange event> callbacks
// (provided the new state is different than the previous state).
//
// If no arguments are passed, an empty state is created, which is just a
// shortcut for jQuery.bbq.pushState( {}, 2 ).
//
// Usage:
//
// > jQuery.bbq.pushState( [ params [, merge_mode ] ] );
//
// Arguments:
//
//  params - (String) A serialized params string or a hash string beginning
//    with # to merge into location.hash.
//  params - (Object) A params object to merge into location.hash.
//  merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not
//    specified (unless a hash string beginning with # is specified, in which
//    case merge behavior defaults to 2), and is as-follows:
//
//    * 0: params in the params argument will override any params in the
//         current state.
//    * 1: any params in the current state will override params in the params
//         argument.
//    * 2: params argument will completely replace current state.
//
// Returns:
//
//  Nothing.
//
// Additional Notes:
//
//  * Setting an empty state may cause the browser to scroll.
//  * Unlike the fragment and querystring methods, if a hash string beginning
//    with # is specified as the params agrument, merge_mode defaults to 2.
jq_bbq.pushState=jq_bbq_pushState=function jq_bbq_pushState(params,merge_mode){if(is_string(params)&&/^#/.test(params)&&merge_mode===undefined){// Params string begins with # and merge_mode not specified, so completely
// overwrite window.location.hash.
merge_mode=2;}var has_args=params!==undefined,// Merge params into window.location using $.param.fragment.
url=jq_param_fragment(location.href,has_args?params:{},has_args?merge_mode:2);// Set new window.location.href. Note that Safari 3 & Chrome barf on
// location.hash = '#' so the entire URL is set.
location.href=url;};// Method: jQuery.bbq.getState
//
// Retrieves the current 'state' from the browser history, parsing
// location.hash for a specific key or returning an object containing the
// entire state, optionally coercing numbers, booleans, null and undefined
// values.
//
// Usage:
//
// > jQuery.bbq.getState( [ key ] [, coerce ] );
//
// Arguments:
//
//  key - (String) An optional state key for which to return a value.
//  coerce - (Boolean) If true, coerces any numbers or true, false, null, and
//    undefined to their actual value. Defaults to false.
//
// Returns:
//
//  (Anything) If key is passed, returns the value corresponding with that key
//    in the location.hash 'state', or undefined. If not, an object
//    representing the entire 'state' is returned.
jq_bbq.getState=jq_bbq_getState=function jq_bbq_getState(key,coerce){return key===undefined||typeof key==='boolean'?jq_deparam_fragment(key)// 'key' really means 'coerce' here
:jq_deparam_fragment(coerce)[key];};// Method: jQuery.bbq.removeState
//
// Remove one or more keys from the current browser history 'state', creating
// a new state, setting location.hash and triggering any bound
// <hashchange event> callbacks (provided the new state is different than
// the previous state).
//
// If no arguments are passed, an empty state is created, which is just a
// shortcut for jQuery.bbq.pushState( {}, 2 ).
//
// Usage:
//
// > jQuery.bbq.removeState( [ key [, key ... ] ] );
//
// Arguments:
//
//  key - (String) One or more key values to remove from the current state,
//    passed as individual arguments.
//  key - (Array) A single array argument that contains a list of key values
//    to remove from the current state.
//
// Returns:
//
//  Nothing.
//
// Additional Notes:
//
//  * Setting an empty state may cause the browser to scroll.
jq_bbq.removeState=function(arr){var state={};// If one or more arguments is passed..
if(arr!==undefined){// Get the current state.
state=jq_bbq_getState();// For each passed key, delete the corresponding property from the current
// state.
$.each($.isArray(arr)?arr:arguments,function(i,v){delete state[v];});}// Set the state, completely overriding any existing state.
jq_bbq_pushState(state,2);};// Event: hashchange event (BBQ)
//
// Usage in jQuery 1.4 and newer:
//
// In jQuery 1.4 and newer, the event object passed into any hashchange event
// callback is augmented with a copy of the location.hash fragment at the time
// the event was triggered as its event.fragment property. In addition, the
// event.getState method operates on this property (instead of location.hash)
// which allows this fragment-as-a-state to be referenced later, even after
// window.location may have changed.
//
// Note that event.fragment and event.getState are not defined according to
// W3C (or any other) specification, but will still be available whether or
// not the hashchange event exists natively in the browser, because of the
// utility they provide.
//
// The event.fragment property contains the output of <jQuery.param.fragment>
// and the event.getState method is equivalent to the <jQuery.bbq.getState>
// method.
//
// > $(window).bind( 'hashchange', function( event ) {
// >   var hash_str = event.fragment,
// >     param_obj = event.getState(),
// >     param_val = event.getState( 'param_name' ),
// >     param_val_coerced = event.getState( 'param_name', true );
// >   ...
// > });
//
// Usage in jQuery 1.3.2:
//
// In jQuery 1.3.2, the event object cannot to be augmented as in jQuery 1.4+,
// so the fragment state isn't bound to the event object and must instead be
// parsed using the <jQuery.param.fragment> and <jQuery.bbq.getState> methods.
//
// > $(window).bind( 'hashchange', function( event ) {
// >   var hash_str = $.param.fragment(),
// >     param_obj = $.bbq.getState(),
// >     param_val = $.bbq.getState( 'param_name' ),
// >     param_val_coerced = $.bbq.getState( 'param_name', true );
// >   ...
// > });
//
// Additional Notes:
//
// * Due to changes in the special events API, jQuery BBQ v1.2 or newer is
//   required to enable the augmented event object in jQuery 1.4.2 and newer.
// * See <jQuery hashchange event> for more detailed information.
special[str_hashchange]=$.extend(special[str_hashchange],{// Augmenting the event object with the .fragment property and .getState
// method requires jQuery 1.4 or newer. Note: with 1.3.2, everything will
// work, but the event won't be augmented)
add:function add(handleObj){var old_handler;function new_handler(e){// e.fragment is set to the value of location.hash (with any leading #
// removed) at the time the event is triggered.
var hash=e[str_fragment]=jq_param_fragment();// e.getState() works just like $.bbq.getState(), but uses the
// e.fragment property stored on the event object.
e.getState=function(key,coerce){return key===undefined||typeof key==='boolean'?jq_deparam(hash,key)// 'key' really means 'coerce' here
:jq_deparam(hash,coerce)[key];};old_handler.apply(this,arguments);};// This may seem a little complicated, but it normalizes the special event
// .add method between jQuery 1.4/1.4.1 and 1.4.2+
if($.isFunction(handleObj)){// 1.4, 1.4.1
old_handler=handleObj;return new_handler;}else{// 1.4.2+
old_handler=handleObj.handler;handleObj.handler=new_handler;}}});})(jQuery,this);/*!
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */// Script: jQuery hashchange event
//
// *Version: 1.3, Last updated: 7/21/2010*
//
// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
// GitHub       - http://github.com/cowboy/jquery-hashchange/
// Source       - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
// (Minified)   - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
//
// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
// document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
//                   Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
// Unit Tests      - http://benalman.com/code/projects/jquery-hashchange/unit/
//
// About: Known issues
//
// While this jQuery hashchange event implementation is quite stable and
// robust, there are a few unfortunate browser bugs surrounding expected
// hashchange event-based behaviors, independent of any JavaScript
// window.onhashchange abstraction. See the following examples for more
// information:
//
// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
//
// Also note that should a browser natively support the window.onhashchange
// event, but not report that it does, the fallback polling loop will be used.
//
// About: Release History
//
// 1.3   - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
//         "removable" for mobile-only development. Added IE6/7 document.title
//         support. Attempted to make Iframe as hidden as possible by using
//         techniques from http://www.paciellogroup.com/blog/?p=604. Added
//         support for the "shortcut" format $(window).hashchange( fn ) and
//         $(window).hashchange() like jQuery provides for built-in events.
//         Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
//         lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
//         and <jQuery.fn.hashchange.src> properties plus document-domain.html
//         file to address access denied issues when setting document.domain in
//         IE6/7.
// 1.2   - (2/11/2010) Fixed a bug where coming back to a page using this plugin
//         from a page on another domain would cause an error in Safari 4. Also,
//         IE6/7 Iframe is now inserted after the body (this actually works),
//         which prevents the page from scrolling when the event is first bound.
//         Event can also now be bound before DOM ready, but it won't be usable
//         before then in IE6/7.
// 1.1   - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
//         where browser version is incorrectly reported as 8.0, despite
//         inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
// 1.0   - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
//         window.onhashchange functionality into a separate plugin for users
//         who want just the basic event & back button support, without all the
//         extra awesomeness that BBQ provides. This plugin will be included as
//         part of jQuery BBQ, but also be available separately.
(function($,window,undefined){'$:nomunge';// Used by YUI compressor.
// Reused string.
var str_hashchange='hashchange',// Method / object references.
doc=document,fake_onhashchange,special=$.event.special,// Does the browser support window.onhashchange? Note that IE8 running in
// IE7 compatibility mode reports true for 'onhashchange' in window, even
// though the event isn't supported, so also test document.documentMode.
doc_mode=doc.documentMode,supports_onhashchange='on'+str_hashchange in window&&(doc_mode===undefined||doc_mode>7);// Get location.hash (or what you'd expect location.hash to be) sans any
// leading #. Thanks for making this necessary, Firefox!
function get_fragment(url){url=url||location.href;return'#'+url.replace(/^[^#]*#?(.*)$/,'$1');};// Method: jQuery.fn.hashchange
//
// Bind a handler to the window.onhashchange event or trigger all bound
// window.onhashchange event handlers. This behavior is consistent with
// jQuery's built-in event handlers.
//
// Usage:
//
// > jQuery(window).hashchange( [ handler ] );
//
// Arguments:
//
//  handler - (Function) Optional handler to be bound to the hashchange
//    event. This is a "shortcut" for the more verbose form:
//    jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
//    all bound window.onhashchange event handlers will be triggered. This
//    is a shortcut for the more verbose
//    jQuery(window).trigger( 'hashchange' ). These forms are described in
//    the <hashchange event> section.
//
// Returns:
//
//  (jQuery) The initial jQuery collection of elements.
// Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
// $(elem).hashchange() for triggering, like jQuery does for built-in events.
$.fn[str_hashchange]=function(fn){return fn?this.bind(str_hashchange,fn):this.trigger(str_hashchange);};// Property: jQuery.fn.hashchange.delay
//
// The numeric interval (in milliseconds) at which the <hashchange event>
// polling loop executes. Defaults to 50.
// Property: jQuery.fn.hashchange.domain
//
// If you're setting document.domain in your JavaScript, and you want hash
// history to work in IE6/7, not only must this property be set, but you must
// also set document.domain BEFORE jQuery is loaded into the page. This
// property is only applicable if you are supporting IE6/7 (or IE8 operating
// in "IE7 compatibility" mode).
//
// In addition, the <jQuery.fn.hashchange.src> property must be set to the
// path of the included "document-domain.html" file, which can be renamed or
// modified if necessary (note that the document.domain specified must be the
// same in both your main JavaScript as well as in this file).
//
// Usage:
//
// jQuery.fn.hashchange.domain = document.domain;
// Property: jQuery.fn.hashchange.src
//
// If, for some reason, you need to specify an Iframe src file (for example,
// when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
// do so using this property. Note that when using this property, history
// won't be recorded in IE6/7 until the Iframe src file loads. This property
// is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
// compatibility" mode).
//
// Usage:
//
// jQuery.fn.hashchange.src = 'path/to/file.html';
$.fn[str_hashchange].delay=50;/*
  $.fn[ str_hashchange ].domain = null;
  $.fn[ str_hashchange ].src = null;
  */// Event: hashchange event
//
// Fired when location.hash changes. In browsers that support it, the native
// HTML5 window.onhashchange event is used, otherwise a polling loop is
// initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
// see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
// compatibility" mode), a hidden Iframe is created to allow the back button
// and hash-based history to work.
//
// Usage as described in <jQuery.fn.hashchange>:
//
// > // Bind an event handler.
// > jQuery(window).hashchange( function(e) {
// >   var hash = location.hash;
// >   ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).hashchange();
//
// A more verbose usage that allows for event namespacing:
//
// > // Bind an event handler.
// > jQuery(window).bind( 'hashchange', function(e) {
// >   var hash = location.hash;
// >   ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).trigger( 'hashchange' );
//
// Additional Notes:
//
// * The polling loop and Iframe are not created until at least one handler
//   is actually bound to the 'hashchange' event.
// * If you need the bound handler(s) to execute immediately, in cases where
//   a location.hash exists on page load, via bookmark or page refresh for
//   example, use jQuery(window).hashchange() or the more verbose
//   jQuery(window).trigger( 'hashchange' ).
// * The event can be bound before DOM ready, but since it won't be usable
//   before then in IE6/7 (due to the necessary Iframe), recommended usage is
//   to bind it inside a DOM ready handler.
// Override existing $.event.special.hashchange methods (allowing this plugin
// to be defined after jQuery BBQ in BBQ's source code).
special[str_hashchange]=$.extend(special[str_hashchange],{// Called only when the first 'hashchange' event is bound to window.
setup:function setup(){// If window.onhashchange is supported natively, there's nothing to do..
if(supports_onhashchange){return false;}// Otherwise, we need to create our own. And we don't want to call this
// until the user binds to the event, just in case they never do, since it
// will create a polling loop and possibly even a hidden Iframe.
$(fake_onhashchange.start);},// Called only when the last 'hashchange' event is unbound from window.
teardown:function teardown(){// If window.onhashchange is supported natively, there's nothing to do..
if(supports_onhashchange){return false;}// Otherwise, we need to stop ours (if possible).
$(fake_onhashchange.stop);}});// fake_onhashchange does all the work of triggering the window.onhashchange
// event for browsers that don't natively support it, including creating a
// polling loop to watch for hash changes and in IE 6/7 creating a hidden
// Iframe to enable back and forward.
fake_onhashchange=function(){var self={},timeout_id,// Remember the initial hash so it doesn't get triggered immediately.
last_hash=get_fragment(),fn_retval=function fn_retval(val){return val;},history_set=fn_retval,history_get=fn_retval;// Start the polling loop.
self.start=function(){timeout_id||poll();};// Stop the polling loop.
self.stop=function(){timeout_id&&clearTimeout(timeout_id);timeout_id=undefined;};// This polling loop checks every $.fn.hashchange.delay milliseconds to see
// if location.hash has changed, and triggers the 'hashchange' event on
// window when necessary.
function poll(){var hash=get_fragment(),history_hash=history_get(last_hash);if(hash!==last_hash){history_set(last_hash=hash,history_hash);$(window).trigger(str_hashchange);}else if(history_hash!==last_hash){location.href=location.href.replace(/#.*/,'')+history_hash;}timeout_id=setTimeout(poll,$.fn[str_hashchange].delay);};// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
/msie|trident/i.test(navigator.userAgent)&&!supports_onhashchange&&function(){// Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
// when running in "IE7 compatibility" mode.
var iframe,iframe_src;// When the event is bound and polling starts in IE 6/7, create a hidden
// Iframe for history handling.
self.start=function(){if(!iframe){iframe_src=$.fn[str_hashchange].src;iframe_src=iframe_src&&iframe_src+get_fragment();// Create hidden Iframe. Attempt to make Iframe as hidden as possible
// by using techniques from http://www.paciellogroup.com/blog/?p=604.
iframe=$('<iframe tabindex="-1" title="empty"/>').hide()// When Iframe has completely loaded, initialize the history and
// start polling.
.one('load',function(){iframe_src||history_set(get_fragment());poll();})// Load Iframe src if specified, otherwise nothing.
.attr('src',iframe_src||'javascript:0')// Append Iframe after the end of the body to prevent unnecessary
// initial page scrolling (yes, this works).
.insertAfter('body')[0].contentWindow;// Whenever `document.title` changes, update the Iframe's title to
// prettify the back/next history menu entries. Since IE sometimes
// errors with "Unspecified error" the very first time this is set
// (yes, very useful) wrap this with a try/catch block.
doc.onpropertychange=function(){try{if(event.propertyName==='title'){iframe.document.title=doc.title;}}catch(e){}};}};// Override the "stop" method since an IE6/7 Iframe was created. Even
// if there are no longer any bound event handlers, the polling loop
// is still necessary for back/next to work at all!
self.stop=fn_retval;// Get history by looking at the hidden Iframe's location.hash.
history_get=function history_get(){return get_fragment(iframe.location.href);};// Set a new history item by opening and then closing the Iframe
// document, *then* setting its location.hash. If document.domain has
// been set, update that as well.
history_set=function history_set(hash,history_hash){var iframe_doc=iframe.document,domain=$.fn[str_hashchange].domain;if(hash!==history_hash){// Update Iframe with any initial `document.title` that might be set.
iframe_doc.title=doc.title;// Opening the Iframe's document after it has been closed is what
// actually adds a history entry.
iframe_doc.open();// Set document.domain for the Iframe document as well, if necessary.
domain&&iframe_doc.write('<script>document.domain="'+domain+'"</script>');iframe_doc.close();// Update the Iframe's hash, for great justice.
iframe.location.hash=hash;}};}();// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return self;}();})(jQuery,this);},{}],21:[function(require,module,exports){// shim for using process in browser
var process=module.exports={};// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error('setTimeout has not been defined');}function defaultClearTimeout(){throw new Error('clearTimeout has not been defined');}(function(){try{if(typeof setTimeout==='function'){cachedSetTimeout=setTimeout;}else{cachedSetTimeout=defaultSetTimout;}}catch(e){cachedSetTimeout=defaultSetTimout;}try{if(typeof clearTimeout==='function'){cachedClearTimeout=clearTimeout;}else{cachedClearTimeout=defaultClearTimeout;}}catch(e){cachedClearTimeout=defaultClearTimeout;}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){//normal enviroments in sane situations
return setTimeout(fun,0);}// if setTimeout wasn't available but was latter defined
if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0);}try{// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun,0);}catch(e){try{// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null,fun,0);}catch(e){// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this,fun,0);}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){//normal enviroments in sane situations
return clearTimeout(marker);}// if clearTimeout wasn't available but was latter defined
if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker);}try{// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);}catch(e){try{// When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
return cachedClearTimeout.call(null,marker);}catch(e){// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this,marker);}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return;}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue);}else{queueIndex=-1;}if(queue.length){drainQueue();}}function drainQueue(){if(draining){return;}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run();}}queueIndex=-1;len=queue.length;}currentQueue=null;draining=false;runClearTimeout(timeout);}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i];}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue);}};// v8 likes predictible objects
function Item(fun,array){this.fun=fun;this.array=array;}Item.prototype.run=function(){this.fun.apply(null,this.array);};process.title='browser';process.browser=true;process.env={};process.argv=[];process.version='';// empty string to avoid regexp issues
process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.prependListener=noop;process.prependOnceListener=noop;process.listeners=function(name){return[];};process.binding=function(name){throw new Error('process.binding is not supported');};process.cwd=function(){return'/';};process.chdir=function(dir){throw new Error('process.chdir is not supported');};process.umask=function(){return 0;};},{}],22:[function(require,module,exports){if(typeof Object.create==='function'){// implementation from standard node.js 'util' module
module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}});};}else{// old school shim for old browsers
module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function TempCtor(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor();ctor.prototype.constructor=ctor;};}},{}],23:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&(typeof arg==="undefined"?"undefined":_typeof(arg))==='object'&&typeof arg.copy==='function'&&typeof arg.fill==='function'&&typeof arg.readUInt8==='function';};},{}],24:[function(require,module,exports){(function(process,global){(function(){// 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 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;};// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate=function(fn,msg){// Allow for deprecating things in the process of starting up.
if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments);};}if(process.noDeprecation===true){return fn;}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg);}else if(process.traceDeprecation){console.trace(msg);}else{console.error(msg);}warned=true;}return fn.apply(this,arguments);}return deprecated;};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||'';set=set.toUpperCase();if(!debugs[set]){if(new RegExp('\\b'+set+'\\b','i').test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error('%s %d: %s',set,pid,msg);};}else{debugs[set]=function(){};}}return debugs[set];};/**
 * 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"\x1B["+inspect.colors[style][0]+'m'+str+"\x1B["+inspect.colors[style][1]+'m';}else{return str;}}function stylizeNoColor(str,styleType){return str;}function arrayToHash(array){var hash={};array.forEach(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,ctx);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=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value);}// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if(isError(value)&&(keys.indexOf('message')>=0||keys.indexOf('description')>=0)){return formatError(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('');}}keys.forEach(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=Object.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(ctx.seen.indexOf(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=output.reduce(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 Array.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==="undefined"?"undefined":_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==="undefined"?"undefined":_typeof(arg))==='object'&&arg!==null;}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]'||e instanceof 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==="undefined"?"undefined":_typeof(arg))==='symbol'||// ES6 symbol
typeof arg==='undefined';}exports.isPrimitive=isPrimitive;exports.isBuffer=require('./support/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=require('inherits');exports._extend=function(origin,add){// Don't do anything if add isn't an object
if(!add||!isObject(add))return origin;var keys=Object.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);}}).call(this);}).call(this,require('_process'),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"./support/isBuffer":23,"_process":21,"inherits":22}],25:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"v1",{enumerable:true,get:function get(){return _v.default;}});Object.defineProperty(exports,"v3",{enumerable:true,get:function get(){return _v2.default;}});Object.defineProperty(exports,"v4",{enumerable:true,get:function get(){return _v3.default;}});Object.defineProperty(exports,"v5",{enumerable:true,get:function get(){return _v4.default;}});Object.defineProperty(exports,"NIL",{enumerable:true,get:function get(){return _nil.default;}});Object.defineProperty(exports,"version",{enumerable:true,get:function get(){return _version.default;}});Object.defineProperty(exports,"validate",{enumerable:true,get:function get(){return _validate.default;}});Object.defineProperty(exports,"stringify",{enumerable:true,get:function get(){return _stringify.default;}});Object.defineProperty(exports,"parse",{enumerable:true,get:function get(){return _parse.default;}});var _v=_interopRequireDefault(require("./v1.js"));var _v2=_interopRequireDefault(require("./v3.js"));var _v3=_interopRequireDefault(require("./v4.js"));var _v4=_interopRequireDefault(require("./v5.js"));var _nil=_interopRequireDefault(require("./nil.js"));var _version=_interopRequireDefault(require("./version.js"));var _validate=_interopRequireDefault(require("./validate.js"));var _stringify=_interopRequireDefault(require("./stringify.js"));var _parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./nil.js":27,"./parse.js":28,"./stringify.js":32,"./v1.js":33,"./v3.js":34,"./v4.js":36,"./v5.js":37,"./validate.js":38,"./version.js":39}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;/*
 * Browser-compatible JavaScript MD5
 *
 * Modification of JavaScript MD5
 * https://github.com/blueimp/JavaScript-MD5
 *
 * Copyright 2011, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * https://opensource.org/licenses/MIT
 *
 * Based on
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */function md5(bytes){if(typeof bytes==='string'){var msg=unescape(encodeURIComponent(bytes));// UTF8 escape
bytes=new Uint8Array(msg.length);for(var i=0;i<msg.length;++i){bytes[i]=msg.charCodeAt(i);}}return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes),bytes.length*8));}/*
 * Convert an array of little-endian words to an array of bytes
 */function md5ToHexEncodedArray(input){var output=[];var length32=input.length*32;var hexTab='0123456789abcdef';for(var i=0;i<length32;i+=8){var x=input[i>>5]>>>i%32&0xff;var hex=parseInt(hexTab.charAt(x>>>4&0x0f)+hexTab.charAt(x&0x0f),16);output.push(hex);}return output;}/**
 * Calculate output length with padding and bit length
 */function getOutputLength(inputLength8){return(inputLength8+64>>>9<<4)+14+1;}/*
 * Calculate the MD5 of an array of little-endian words, and a bit length.
 */function wordsToMd5(x,len){/* append padding */x[len>>5]|=0x80<<len%32;x[getOutputLength(len)-1]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i<x.length;i+=16){var olda=a;var oldb=b;var oldc=c;var oldd=d;a=md5ff(a,b,c,d,x[i],7,-680876936);d=md5ff(d,a,b,c,x[i+1],12,-389564586);c=md5ff(c,d,a,b,x[i+2],17,606105819);b=md5ff(b,c,d,a,x[i+3],22,-1044525330);a=md5ff(a,b,c,d,x[i+4],7,-176418897);d=md5ff(d,a,b,c,x[i+5],12,1200080426);c=md5ff(c,d,a,b,x[i+6],17,-1473231341);b=md5ff(b,c,d,a,x[i+7],22,-45705983);a=md5ff(a,b,c,d,x[i+8],7,1770035416);d=md5ff(d,a,b,c,x[i+9],12,-1958414417);c=md5ff(c,d,a,b,x[i+10],17,-42063);b=md5ff(b,c,d,a,x[i+11],22,-1990404162);a=md5ff(a,b,c,d,x[i+12],7,1804603682);d=md5ff(d,a,b,c,x[i+13],12,-40341101);c=md5ff(c,d,a,b,x[i+14],17,-1502002290);b=md5ff(b,c,d,a,x[i+15],22,1236535329);a=md5gg(a,b,c,d,x[i+1],5,-165796510);d=md5gg(d,a,b,c,x[i+6],9,-1069501632);c=md5gg(c,d,a,b,x[i+11],14,643717713);b=md5gg(b,c,d,a,x[i],20,-373897302);a=md5gg(a,b,c,d,x[i+5],5,-701558691);d=md5gg(d,a,b,c,x[i+10],9,38016083);c=md5gg(c,d,a,b,x[i+15],14,-660478335);b=md5gg(b,c,d,a,x[i+4],20,-405537848);a=md5gg(a,b,c,d,x[i+9],5,568446438);d=md5gg(d,a,b,c,x[i+14],9,-1019803690);c=md5gg(c,d,a,b,x[i+3],14,-187363961);b=md5gg(b,c,d,a,x[i+8],20,1163531501);a=md5gg(a,b,c,d,x[i+13],5,-1444681467);d=md5gg(d,a,b,c,x[i+2],9,-51403784);c=md5gg(c,d,a,b,x[i+7],14,1735328473);b=md5gg(b,c,d,a,x[i+12],20,-1926607734);a=md5hh(a,b,c,d,x[i+5],4,-378558);d=md5hh(d,a,b,c,x[i+8],11,-2022574463);c=md5hh(c,d,a,b,x[i+11],16,1839030562);b=md5hh(b,c,d,a,x[i+14],23,-35309556);a=md5hh(a,b,c,d,x[i+1],4,-1530992060);d=md5hh(d,a,b,c,x[i+4],11,1272893353);c=md5hh(c,d,a,b,x[i+7],16,-155497632);b=md5hh(b,c,d,a,x[i+10],23,-1094730640);a=md5hh(a,b,c,d,x[i+13],4,681279174);d=md5hh(d,a,b,c,x[i],11,-358537222);c=md5hh(c,d,a,b,x[i+3],16,-722521979);b=md5hh(b,c,d,a,x[i+6],23,76029189);a=md5hh(a,b,c,d,x[i+9],4,-640364487);d=md5hh(d,a,b,c,x[i+12],11,-421815835);c=md5hh(c,d,a,b,x[i+15],16,530742520);b=md5hh(b,c,d,a,x[i+2],23,-995338651);a=md5ii(a,b,c,d,x[i],6,-198630844);d=md5ii(d,a,b,c,x[i+7],10,1126891415);c=md5ii(c,d,a,b,x[i+14],15,-1416354905);b=md5ii(b,c,d,a,x[i+5],21,-57434055);a=md5ii(a,b,c,d,x[i+12],6,1700485571);d=md5ii(d,a,b,c,x[i+3],10,-1894986606);c=md5ii(c,d,a,b,x[i+10],15,-1051523);b=md5ii(b,c,d,a,x[i+1],21,-2054922799);a=md5ii(a,b,c,d,x[i+8],6,1873313359);d=md5ii(d,a,b,c,x[i+15],10,-30611744);c=md5ii(c,d,a,b,x[i+6],15,-1560198380);b=md5ii(b,c,d,a,x[i+13],21,1309151649);a=md5ii(a,b,c,d,x[i+4],6,-145523070);d=md5ii(d,a,b,c,x[i+11],10,-1120210379);c=md5ii(c,d,a,b,x[i+2],15,718787259);b=md5ii(b,c,d,a,x[i+9],21,-343485551);a=safeAdd(a,olda);b=safeAdd(b,oldb);c=safeAdd(c,oldc);d=safeAdd(d,oldd);}return[a,b,c,d];}/*
 * Convert an array bytes to an array of little-endian words
 * Characters >255 have their high-byte silently ignored.
 */function bytesToWords(input){if(input.length===0){return[];}var length8=input.length*8;var output=new Uint32Array(getOutputLength(length8));for(var i=0;i<length8;i+=8){output[i>>5]|=(input[i/8]&0xff)<<i%32;}return output;}/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */function safeAdd(x,y){var lsw=(x&0xffff)+(y&0xffff);var msw=(x>>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&0xffff;}/*
 * Bitwise rotate a 32-bit number to the left.
 */function bitRotateLeft(num,cnt){return num<<cnt|num>>>32-cnt;}/*
 * These functions implement the four basic operations the algorithm uses.
 */function md5cmn(q,a,b,x,s,t){return safeAdd(bitRotateLeft(safeAdd(safeAdd(a,q),safeAdd(x,t)),s),b);}function md5ff(a,b,c,d,x,s,t){return md5cmn(b&c|~b&d,a,b,x,s,t);}function md5gg(a,b,c,d,x,s,t){return md5cmn(b&d|c&~d,a,b,x,s,t);}function md5hh(a,b,c,d,x,s,t){return md5cmn(b^c^d,a,b,x,s,t);}function md5ii(a,b,c,d,x,s,t){return md5cmn(c^(b|~d),a,b,x,s,t);}var _default=md5;exports.default=_default;},{}],27:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _default='00000000-0000-0000-0000-000000000000';exports.default=_default;},{}],28:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _validate=_interopRequireDefault(require("./validate.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function parse(uuid){if(!(0,_validate.default)(uuid)){throw TypeError('Invalid UUID');}var v=void 0;var arr=new Uint8Array(16);// Parse ########-....-....-....-............
arr[0]=(v=parseInt(uuid.slice(0,8),16))>>>24;arr[1]=v>>>16&0xff;arr[2]=v>>>8&0xff;arr[3]=v&0xff;// Parse ........-####-....-....-............
arr[4]=(v=parseInt(uuid.slice(9,13),16))>>>8;arr[5]=v&0xff;// Parse ........-....-####-....-............
arr[6]=(v=parseInt(uuid.slice(14,18),16))>>>8;arr[7]=v&0xff;// Parse ........-....-....-####-............
arr[8]=(v=parseInt(uuid.slice(19,23),16))>>>8;arr[9]=v&0xff;// Parse ........-....-....-....-############
// (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
arr[10]=(v=parseInt(uuid.slice(24,36),16))/0x10000000000&0xff;arr[11]=v/0x100000000&0xff;arr[12]=v>>>24&0xff;arr[13]=v>>>16&0xff;arr[14]=v>>>8&0xff;arr[15]=v&0xff;return arr;}var _default=parse;exports.default=_default;},{"./validate.js":38}],29:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;exports.default=_default;},{}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=rng;// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).
var getRandomValues=void 0;var rnds8=new Uint8Array(16);function rng(){// lazy load so that environments that need to polyfill have a chance to do so
if(!getRandomValues){// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
// find the complete implementation of crypto (msCrypto) on IE11.
getRandomValues=typeof crypto!=='undefined'&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!=='undefined'&&typeof msCrypto.getRandomValues==='function'&&msCrypto.getRandomValues.bind(msCrypto);if(!getRandomValues){throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');}}return getRandomValues(rnds8);}},{}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;// Adapted from Chris Veness' SHA1 code at
// http://www.movable-type.co.uk/scripts/sha1.html
function f(s,x,y,z){switch(s){case 0:return x&y^~x&z;case 1:return x^y^z;case 2:return x&y^x&z^y&z;case 3:return x^y^z;}}function ROTL(x,n){return x<<n|x>>>32-n;}function sha1(bytes){var K=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6];var H=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0];if(typeof bytes==='string'){var msg=unescape(encodeURIComponent(bytes));// UTF8 escape
bytes=[];for(var i=0;i<msg.length;++i){bytes.push(msg.charCodeAt(i));}}else if(!Array.isArray(bytes)){// Convert Array-like to Array
bytes=Array.prototype.slice.call(bytes);}bytes.push(0x80);var l=bytes.length/4+2;var N=Math.ceil(l/16);var M=new Array(N);for(var _i=0;_i<N;++_i){var arr=new Uint32Array(16);for(var j=0;j<16;++j){arr[j]=bytes[_i*64+j*4]<<24|bytes[_i*64+j*4+1]<<16|bytes[_i*64+j*4+2]<<8|bytes[_i*64+j*4+3];}M[_i]=arr;}M[N-1][14]=(bytes.length-1)*8/Math.pow(2,32);M[N-1][14]=Math.floor(M[N-1][14]);M[N-1][15]=(bytes.length-1)*8&0xffffffff;for(var _i2=0;_i2<N;++_i2){var W=new Uint32Array(80);for(var _t=0;_t<16;++_t){W[_t]=M[_i2][_t];}for(var _t2=16;_t2<80;++_t2){W[_t2]=ROTL(W[_t2-3]^W[_t2-8]^W[_t2-14]^W[_t2-16],1);}var _a=H[0];var b=H[1];var c=H[2];var d=H[3];var e=H[4];for(var _t3=0;_t3<80;++_t3){var s=Math.floor(_t3/20);var T=ROTL(_a,5)+f(s,b,c,d)+e+K[s]+W[_t3]>>>0;e=d;d=c;c=ROTL(b,30)>>>0;b=_a;_a=T;}H[0]=H[0]+_a>>>0;H[1]=H[1]+b>>>0;H[2]=H[2]+c>>>0;H[3]=H[3]+d>>>0;H[4]=H[4]+e>>>0;}return[H[0]>>24&0xff,H[0]>>16&0xff,H[0]>>8&0xff,H[0]&0xff,H[1]>>24&0xff,H[1]>>16&0xff,H[1]>>8&0xff,H[1]&0xff,H[2]>>24&0xff,H[2]>>16&0xff,H[2]>>8&0xff,H[2]&0xff,H[3]>>24&0xff,H[3]>>16&0xff,H[3]>>8&0xff,H[3]&0xff,H[4]>>24&0xff,H[4]>>16&0xff,H[4]>>8&0xff,H[4]&0xff];}var _default=sha1;exports.default=_default;},{}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _validate=_interopRequireDefault(require("./validate.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
 * Convert array of 16 byte values to UUID string format of the form:
 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 */var byteToHex=[];for(var i=0;i<256;++i){byteToHex.push((i+0x100).toString(16).substr(1));}function stringify(arr){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;// Note: Be careful editing this code!  It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
var uuid=(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+'-'+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+'-'+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+'-'+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+'-'+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase();// Consistency check for valid UUID.  If this throws, it's likely due to one
// of the following:
// - One or more input array values don't map to a hex octet (leading to
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
if(!(0,_validate.default)(uuid)){throw TypeError('Stringified UUID is invalid');}return uuid;}var _default=stringify;exports.default=_default;},{"./validate.js":38}],33:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _rng=_interopRequireDefault(require("./rng.js"));var _stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
var _nodeId=void 0;var _clockseq=void 0;// Previous uuid creation time
var _lastMSecs=0;var _lastNSecs=0;// See https://github.com/uuidjs/uuid for API details
function v1(options,buf,offset){var i=buf&&offset||0;var b=buf||new Array(16);options=options||{};var node=options.node||_nodeId;var clockseq=options.clockseq!==undefined?options.clockseq:_clockseq;// node and clockseq need to be initialized to random values if they're not
// specified.  We do this lazily to minimize issues related to insufficient
// system entropy.  See #189
if(node==null||clockseq==null){var seedBytes=options.random||(options.rng||_rng.default)();if(node==null){// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
node=_nodeId=[seedBytes[0]|0x01,seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]];}if(clockseq==null){// Per 4.2.2, randomize (14 bit) clockseq
clockseq=_clockseq=(seedBytes[6]<<8|seedBytes[7])&0x3fff;}}// UUID timestamps are 100 nano-second units since the Gregorian epoch,
// (1582-10-15 00:00).  JSNumbers aren't precise enough for this, so
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
var msecs=options.msecs!==undefined?options.msecs:Date.now();// Per 4.2.1.2, use count of uuid's generated during the current clock
// cycle to simulate higher resolution clock
var nsecs=options.nsecs!==undefined?options.nsecs:_lastNSecs+1;// Time since last uuid creation (in msecs)
var dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/10000;// Per 4.2.1.2, Bump clockseq on clock regression
if(dt<0&&options.clockseq===undefined){clockseq=clockseq+1&0x3fff;}// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
// time interval
if((dt<0||msecs>_lastMSecs)&&options.nsecs===undefined){nsecs=0;}// Per 4.2.1.2 Throw error if too many uuids are requested
if(nsecs>=10000){throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");}_lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;// Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs+=12219292800000;// `time_low`
var tl=((msecs&0xfffffff)*10000+nsecs)%0x100000000;b[i++]=tl>>>24&0xff;b[i++]=tl>>>16&0xff;b[i++]=tl>>>8&0xff;b[i++]=tl&0xff;// `time_mid`
var tmh=msecs/0x100000000*10000&0xfffffff;b[i++]=tmh>>>8&0xff;b[i++]=tmh&0xff;// `time_high_and_version`
b[i++]=tmh>>>24&0xf|0x10;// include version
b[i++]=tmh>>>16&0xff;// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++]=clockseq>>>8|0x80;// `clock_seq_low`
b[i++]=clockseq&0xff;// `node`
for(var n=0;n<6;++n){b[i+n]=node[n];}return buf||(0,_stringify.default)(b);}var _default=v1;exports.default=_default;},{"./rng.js":30,"./stringify.js":32}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js"));var _md=_interopRequireDefault(require("./md5.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}var v3=(0,_v.default)('v3',0x30,_md.default);var _default=v3;exports.default=_default;},{"./md5.js":26,"./v35.js":35}],35:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=_default;exports.URL=exports.DNS=void 0;var _stringify=_interopRequireDefault(require("./stringify.js"));var _parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function stringToBytes(str){str=unescape(encodeURIComponent(str));// UTF8 escape
var bytes=[];for(var i=0;i<str.length;++i){bytes.push(str.charCodeAt(i));}return bytes;}var DNS='6ba7b810-9dad-11d1-80b4-00c04fd430c8';exports.DNS=DNS;var URL='6ba7b811-9dad-11d1-80b4-00c04fd430c8';exports.URL=URL;function _default(name,version,hashfunc){function generateUUID(value,namespace,buf,offset){if(typeof value==='string'){value=stringToBytes(value);}if(typeof namespace==='string'){namespace=(0,_parse.default)(namespace);}if(namespace.length!==16){throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');}// Compute hash of namespace and value, Per 4.3
// Future: Use spread syntax when supported on all platforms, e.g. `bytes =
// hashfunc([...namespace, ... value])`
var bytes=new Uint8Array(16+value.length);bytes.set(namespace);bytes.set(value,namespace.length);bytes=hashfunc(bytes);bytes[6]=bytes[6]&0x0f|version;bytes[8]=bytes[8]&0x3f|0x80;if(buf){offset=offset||0;for(var i=0;i<16;++i){buf[offset+i]=bytes[i];}return buf;}return(0,_stringify.default)(bytes);}// Function#name is not settable on some platforms (#270)
try{generateUUID.name=name;// eslint-disable-next-line no-empty
}catch(err){}// For CommonJS default export support
generateUUID.DNS=DNS;generateUUID.URL=URL;return generateUUID;}},{"./parse.js":28,"./stringify.js":32}],36:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _rng=_interopRequireDefault(require("./rng.js"));var _stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function v4(options,buf,offset){options=options||{};var rnds=options.random||(options.rng||_rng.default)();// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6]=rnds[6]&0x0f|0x40;rnds[8]=rnds[8]&0x3f|0x80;// Copy bytes to buffer, if provided
if(buf){offset=offset||0;for(var i=0;i<16;++i){buf[offset+i]=rnds[i];}return buf;}return(0,_stringify.default)(rnds);}var _default=v4;exports.default=_default;},{"./rng.js":30,"./stringify.js":32}],37:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js"));var _sha=_interopRequireDefault(require("./sha1.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}var v5=(0,_v.default)('v5',0x50,_sha.default);var _default=v5;exports.default=_default;},{"./sha1.js":31,"./v35.js":35}],38:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _regex=_interopRequireDefault(require("./regex.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function validate(uuid){return typeof uuid==='string'&&_regex.default.test(uuid);}var _default=validate;exports.default=_default;},{"./regex.js":29}],39:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _validate=_interopRequireDefault(require("./validate.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function version(uuid){if(!(0,_validate.default)(uuid)){throw TypeError('Invalid UUID');}return parseInt(uuid.substr(14,1),16);}var _default=version;exports.default=_default;},{"./validate.js":38}],40:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.jsonSchema=exports.fromString=exports.empty=exports.isUuid=exports.regex=exports.uuid=void 0;var util_1=require("util");var uuid_1=require("uuid");var regex={v4:/(?:^[0-9a-f]{8}\x2D[0-9a-f]{4}\x2D4[0-9a-f]{3}\x2D[0-9a-f]{4}\x2D[0-9a-f]{12}$)|(?:^0{8}\x2D0{4}\x2D0{4}\x2D0{4}\x2D0{12}$)/,v5:/(?:^[0-9a-f]{8}\x2D[0-9a-f]{4}\x2D5[0-9a-f]{3}\x2D[0-9a-f]{4}\x2D[0-9a-f]{12}$)|(?:^0{8}\x2D0{4}\x2D0{4}\x2D0{4}\x2D0{12}$)/};exports.regex=regex;var jsonSchema={v4:{type:'string',pattern:regex.v4.toString().slice(1,-2)},v5:{type:'string',pattern:regex.v5.toString().slice(1,-2)}};exports.jsonSchema=jsonSchema;var uuidv4=(0,util_1.deprecate)(function(){return(0,uuid_1.v4)();},'uuidv4() is deprecated. Use v4() from the uuid module instead.');exports.uuid=uuidv4;var isUuid=(0,util_1.deprecate)(function(value){return(0,uuid_1.validate)(value)&&((0,uuid_1.version)(value)===4||(0,uuid_1.version)(value)===5);},'isUuid() is deprecated. Use validate() from the uuid module instead.');exports.isUuid=isUuid;var empty=(0,util_1.deprecate)(function(){return uuid_1.NIL;},'empty() is deprecated. Use NIL from the uuid module instead.');exports.empty=empty;var fromString=(0,util_1.deprecate)(function(text){var namespace=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'bb5d0ffa-9a4c-4d7c-8fc2-0a7d2220ba45';return(0,uuid_1.v5)(text,namespace);},'fromString() is deprecated. Use v5() from the uuid module instead.');exports.fromString=fromString;},{"util":24,"uuid":25}]},{},[19]);