<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">/*! jQuery UI - v1.9.0 - 2012-10-18
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.menu.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js
* Copyright (c) 2012 jQuery Foundation and other contributors Licensed MIT */

(function(e,t){function i(t,n){var r,i,o,u=t.nodeName.toLowerCase();return"area"===u?(r=t.parentNode,i=r.name,!t.href||!i||r.nodeName.toLowerCase()!=="map"?!1:(o=e("img[usemap=#"+i+"]")[0],!!o&amp;&amp;s(o))):(/input|select|textarea|button|object/.test(u)?!t.disabled:"a"===u?t.href||n:n)&amp;&amp;s(t)}function s(t){return!e(t).parents().andSelf().filter(function(){return e.css(this,"visibility")==="hidden"||e.expr.filters.hidden(this)}).length}var n=0,r=/^ui-id-\d+$/;e.ui=e.ui||{};if(e.ui.version)return;e.extend(e.ui,{version:"1.9.0",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,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,SPACE:32,TAB:9,UP:38}}),e.fn.extend({_focus:e.fn.focus,focus:function(t,n){return typeof t=="number"?this.each(function(){var r=this;setTimeout(function(){e(r).focus(),n&amp;&amp;n.call(r)},t)}):this._focus.apply(this,arguments)},scrollParent:function(){var t;return e.browser.msie&amp;&amp;/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?t=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&amp;&amp;/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):t=this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(n){if(n!==t)return this.css("zIndex",n);if(this.length){var r=e(this[0]),i,s;while(r.length&amp;&amp;r[0]!==document){i=r.css("position");if(i==="absolute"||i==="relative"||i==="fixed"){s=parseInt(r.css("zIndex"),10);if(!isNaN(s)&amp;&amp;s!==0)return s}r=r.parent()}}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++n)})},removeUniqueId:function(){return this.each(function(){r.test(this.id)&amp;&amp;e(this).removeAttr("id")})}}),e("&lt;a&gt;").outerWidth(1).jquery||e.each(["Width","Height"],function(n,r){function u(t,n,r,s){return e.each(i,function(){n-=parseFloat(e.css(t,"padding"+this))||0,r&amp;&amp;(n-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&amp;&amp;(n-=parseFloat(e.css(t,"margin"+this))||0)}),n}var i=r==="Width"?["Left","Right"]:["Top","Bottom"],s=r.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+r]=function(n){return n===t?o["inner"+r].call(this):this.each(function(){e(this).css(s,u(this,n)+"px")})},e.fn["outer"+r]=function(t,n){return typeof t!="number"?o["outer"+r].call(this,t):this.each(function(){e(this).css(s,u(this,t,!0,n)+"px")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var n=e.attr(t,"tabindex"),r=isNaN(n);return(r||n&gt;=0)&amp;&amp;i(t,!r)}}),e(function(){var t=document.body,n=t.appendChild(n=document.createElement("div"));n.offsetHeight,e.extend(n.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),e.support.minHeight=n.offsetHeight===100,e.support.selectstart="onselectstart"in n,t.removeChild(n).style.display="none"}),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,n,r){var i,s=e.ui[t].prototype;for(i in r)s.plugins[i]=s.plugins[i]||[],s.plugins[i].push([n,r[i]])},call:function(e,t,n){var r,i=e.plugins[t];if(!i||!e.element[0].parentNode||e.element[0].parentNode.nodeType===11)return;for(r=0;r&lt;i.length;r++)e.options[i[r][0]]&amp;&amp;i[r][1].apply(e.element,n)}},contains:e.contains,hasScroll:function(t,n){if(e(t).css("overflow")==="hidden")return!1;var r=n&amp;&amp;n==="left"?"scrollLeft":"scrollTop",i=!1;return t[r]&gt;0?!0:(t[r]=1,i=t[r]&gt;0,t[r]=0,i)},isOverAxis:function(e,t,n){return e&gt;t&amp;&amp;e&lt;t+n},isOver:function(t,n,r,i,s,o){return e.ui.isOverAxis(t,r,s)&amp;&amp;e.ui.isOverAxis(n,i,o)}})})(jQuery);(function(e,t){var n=0,r=Array.prototype.slice,i=e.cleanData;e.cleanData=function(t){for(var n=0,r;(r=t[n])!=null;n++)try{e(r).triggerHandler("remove")}catch(s){}i(t)},e.widget=function(t,n,r){var i,s,o,u,a=t.split(".")[0];t=t.split(".")[1],i=a+"-"+t,r||(r=n,n=e.Widget),e.expr[":"][i.toLowerCase()]=function(t){return!!e.data(t,i)},e[a]=e[a]||{},s=e[a][t],o=e[a][t]=function(e,t){if(!this._createWidget)return new o(e,t);arguments.length&amp;&amp;this._createWidget(e,t)},e.extend(o,s,{version:r.version,_proto:e.extend({},r),_childConstructors:[]}),u=new n,u.options=e.widget.extend({},u.options),e.each(r,function(t,i){e.isFunction(i)&amp;&amp;(r[t]=function(){var e=function(){return n.prototype[t].apply(this,arguments)},r=function(e){return n.prototype[t].apply(this,e)};return function(){var t=this._super,n=this._superApply,s;return this._super=e,this._superApply=r,s=i.apply(this,arguments),this._super=t,this._superApply=n,s}}())}),o.prototype=e.widget.extend(u,{widgetEventPrefix:t},r,{constructor:o,namespace:a,widgetName:t,widgetBaseClass:i,widgetFullName:i}),s?(e.each(s._childConstructors,function(t,n){var r=n.prototype;e.widget(r.namespace+"."+r.widgetName,o,n._proto)}),delete s._childConstructors):n._childConstructors.push(o),e.widget.bridge(t,o)},e.widget.extend=function(n){var i=r.call(arguments,1),s=0,o=i.length,u,a;for(;s&lt;o;s++)for(u in i[s])a=i[s][u],i[s].hasOwnProperty(u)&amp;&amp;a!==t&amp;&amp;(n[u]=e.isPlainObject(a)?e.widget.extend({},n[u],a):a);return n},e.widget.bridge=function(n,i){var s=i.prototype.widgetFullName;e.fn[n]=function(o){var u=typeof o=="string",a=r.call(arguments,1),f=this;return o=!u&amp;&amp;a.length?e.widget.extend.apply(null,[o].concat(a)):o,u?this.each(function(){var r,i=e.data(this,s);if(!i)return e.error("cannot call methods on "+n+" prior to initialization; "+"attempted to call method '"+o+"'");if(!e.isFunction(i[o])||o.charAt(0)==="_")return e.error("no such method '"+o+"' for "+n+" widget instance");r=i[o].apply(i,a);if(r!==i&amp;&amp;r!==t)return f=r&amp;&amp;r.jquery?f.pushStack(r.get()):r,!1}):this.each(function(){var t=e.data(this,s);t?t.option(o||{})._init():new i(o,this)}),f}},e.Widget=function(e,t){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"&lt;div&gt;",options:{disabled:!1,create:null},_createWidget:function(t,r){r=e(r||this.defaultElement||this)[0],this.element=e(r),this.uuid=n++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this.bindings=e(),this.hoverable=e(),this.focusable=e(),r!==this&amp;&amp;(e.data(r,this.widgetName,this),e.data(r,this.widgetFullName,this),this._on({remove:"destroy"}),this.document=e(r.style?r.ownerDocument:r.document||r),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(n,r){var i=n,s,o,u;if(arguments.length===0)return e.widget.extend({},this.options);if(typeof n=="string"){i={},s=n.split("."),n=s.shift();if(s.length){o=i[n]=e.widget.extend({},this.options[n]);for(u=0;u&lt;s.length-1;u++)o[s[u]]=o[s[u]]||{},o=o[s[u]];n=s.pop();if(r===t)return o[n]===t?null:o[n];o[n]=r}else{if(r===t)return this.options[n]===t?null:this.options[n];i[n]=r}}return this._setOptions(i),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,e==="disabled"&amp;&amp;(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(t,n){n?(t=e(t),this.bindings=this.bindings.add(t)):(n=t,t=this.element);var r=this;e.each(n,function(n,i){function s(){if(r.options.disabled===!0||e(this).hasClass("ui-state-disabled"))return;return(typeof i=="string"?r[i]:i).apply(r,arguments)}typeof i!="string"&amp;&amp;(s.guid=i.guid=i.guid||s.guid||e.guid++);var o=n.match(/^(\w+)\s*(.*)$/),u=o[1]+r.eventNamespace,a=o[2];a?r.widget().delegate(a,u,s):t.bind(u,s)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(t).undelegate(t)},_delay:function(e,t){function n(){return(typeof e=="string"?r[e]:e).apply(r,arguments)}var r=this;return setTimeout(n,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,n,r){var i,s,o=this.options[t];r=r||{},n=e.Event(n),n.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),n.target=this.element[0],s=n.originalEvent;if(s)for(i in s)i in n||(n[i]=s[i]);return this.element.trigger(n,r),!(e.isFunction(o)&amp;&amp;o.apply(this.element[0],[n].concat(r))===!1||n.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,n){e.Widget.prototype["_"+t]=function(r,i,s){typeof i=="string"&amp;&amp;(i={effect:i});var o,u=i?i===!0||typeof i=="number"?n:i.effect||n:t;i=i||{},typeof i=="number"&amp;&amp;(i={duration:i}),o=!e.isEmptyObject(i),i.complete=s,i.delay&amp;&amp;r.delay(i.delay),o&amp;&amp;e.effects&amp;&amp;(e.effects.effect[u]||e.uiBackCompat!==!1&amp;&amp;e.effects[u])?r[t](i):u!==t&amp;&amp;r[u]?r[u](i.duration,i.easing,s):r.queue(function(n){e(this)[t](),s&amp;&amp;s.call(r[0]),n()})}}),e.uiBackCompat!==!1&amp;&amp;(e.Widget.prototype._getCreateOptions=function(){return e.metadata&amp;&amp;e.metadata.get(this.element[0])[this.widgetName]})})(jQuery);(function(e,t){var n=!1;e(document).mouseup(function(e){n=!1}),e.widget("ui.mouse",{version:"1.9.0",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(n){if(!0===e.data(n.target,t.widgetName+".preventClickEvent"))return e.removeData(n.target,t.widgetName+".preventClickEvent"),n.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&amp;&amp;e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(n)return;this._mouseStarted&amp;&amp;this._mouseUp(t),this._mouseDownEvent=t;var r=this,i=t.which===1,s=typeof this.options.cancel=="string"&amp;&amp;t.target.nodeName?e(t.target).closest(this.options.cancel).length:!1;if(!i||s||!this._mouseCapture(t))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){r.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(t)&amp;&amp;this._mouseDelayMet(t)){this._mouseStarted=this._mouseStart(t)!==!1;if(!this._mouseStarted)return t.preventDefault(),!0}return!0===e.data(t.target,this.widgetName+".preventClickEvent")&amp;&amp;e.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return r._mouseMove(e)},this._mouseUpDelegate=function(e){return r._mouseUp(e)},e(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),n=!0,!0},_mouseMove:function(t){return!e.browser.msie||document.documentMode&gt;=9||!!t.button?this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&amp;&amp;this._mouseDelayMet(t)&amp;&amp;(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted):this._mouseUp(t)},_mouseUp:function(t){return e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&amp;&amp;(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&amp;&amp;e.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))&gt;=this.options.distance},_mouseDelayMet:function(e){return this.mouseDelayMet},_mouseStart:function(e){},_mouseDrag:function(e){},_mouseStop:function(e){},_mouseCapture:function(e){return!0}})})(jQuery);(function(e,t){function h(e,t,n){return[parseInt(e[0],10)*(l.test(e[0])?t/100:1),parseInt(e[1],10)*(l.test(e[1])?n/100:1)]}function p(t,n){return parseInt(e.css(t,n),10)||0}e.ui=e.ui||{};var n,r=Math.max,i=Math.abs,s=Math.round,o=/left|center|right/,u=/top|center|bottom/,a=/[\+\-]\d+%?/,f=/^\w+/,l=/%$/,c=e.fn.position;e.position={scrollbarWidth:function(){if(n!==t)return n;var r,i,s=e("&lt;div style='display:block;width:50px;height:50px;overflow:hidden;'&gt;&lt;div style='height:100px;width:auto;'&gt;&lt;/div&gt;&lt;/div&gt;"),o=s.children()[0];return e("body").append(s),r=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,r===i&amp;&amp;(i=s[0].clientWidth),s.remove(),n=r-i},getScrollInfo:function(t){var n=t.isWindow?"":t.element.css("overflow-x"),r=t.isWindow?"":t.element.css("overflow-y"),i=n==="scroll"||n==="auto"&amp;&amp;t.width&lt;t.element[0].scrollWidth,s=r==="scroll"||r==="auto"&amp;&amp;t.height&lt;t.element[0].scrollHeight;return{width:i?e.position.scrollbarWidth():0,height:s?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var n=e(t||window),r=e.isWindow(n[0]);return{element:n,isWindow:r,offset:n.offset()||{left:0,top:0},scrollLeft:n.scrollLeft(),scrollTop:n.scrollTop(),width:r?n.width():n.outerWidth(),height:r?n.height():n.outerHeight()}}},e.fn.position=function(t){if(!t||!t.of)return c.apply(this,arguments);t=e.extend({},t);var n,l,d,v,m,g=e(t.of),y=e.position.getWithinInfo(t.within),b=e.position.getScrollInfo(y),w=g[0],E=(t.collision||"flip").split(" "),S={};return w.nodeType===9?(l=g.width(),d=g.height(),v={top:0,left:0}):e.isWindow(w)?(l=g.width(),d=g.height(),v={top:g.scrollTop(),left:g.scrollLeft()}):w.preventDefault?(t.at="left top",l=d=0,v={top:w.pageY,left:w.pageX}):(l=g.outerWidth(),d=g.outerHeight(),v=g.offset()),m=e.extend({},v),e.each(["my","at"],function(){var e=(t[this]||"").split(" "),n,r;e.length===1&amp;&amp;(e=o.test(e[0])?e.concat(["center"]):u.test(e[0])?["center"].concat(e):["center","center"]),e[0]=o.test(e[0])?e[0]:"center",e[1]=u.test(e[1])?e[1]:"center",n=a.exec(e[0]),r=a.exec(e[1]),S[this]=[n?n[0]:0,r?r[0]:0],t[this]=[f.exec(e[0])[0],f.exec(e[1])[0]]}),E.length===1&amp;&amp;(E[1]=E[0]),t.at[0]==="right"?m.left+=l:t.at[0]==="center"&amp;&amp;(m.left+=l/2),t.at[1]==="bottom"?m.top+=d:t.at[1]==="center"&amp;&amp;(m.top+=d/2),n=h(S.at,l,d),m.left+=n[0],m.top+=n[1],this.each(function(){var o,u,a=e(this),f=a.outerWidth(),c=a.outerHeight(),w=p(this,"marginLeft"),x=p(this,"marginTop"),T=f+w+p(this,"marginRight")+b.width,N=c+x+p(this,"marginBottom")+b.height,C=e.extend({},m),k=h(S.my,a.outerWidth(),a.outerHeight());t.my[0]==="right"?C.left-=f:t.my[0]==="center"&amp;&amp;(C.left-=f/2),t.my[1]==="bottom"?C.top-=c:t.my[1]==="center"&amp;&amp;(C.top-=c/2),C.left+=k[0],C.top+=k[1],e.support.offsetFractions||(C.left=s(C.left),C.top=s(C.top)),o={marginLeft:w,marginTop:x},e.each(["left","top"],function(r,i){e.ui.position[E[r]]&amp;&amp;e.ui.position[E[r]][i](C,{targetWidth:l,targetHeight:d,elemWidth:f,elemHeight:c,collisionPosition:o,collisionWidth:T,collisionHeight:N,offset:[n[0]+k[0],n[1]+k[1]],my:t.my,at:t.at,within:y,elem:a})}),e.fn.bgiframe&amp;&amp;a.bgiframe(),t.using&amp;&amp;(u=function(e){var n=v.left-C.left,s=n+l-f,o=v.top-C.top,u=o+d-c,h={target:{element:g,left:v.left,top:v.top,width:l,height:d},element:{element:a,left:C.left,top:C.top,width:f,height:c},horizontal:s&lt;0?"left":n&gt;0?"right":"center",vertical:u&lt;0?"top":o&gt;0?"bottom":"middle"};l&lt;f&amp;&amp;i(n+s)&lt;l&amp;&amp;(h.horizontal="center"),d&lt;c&amp;&amp;i(o+u)&lt;d&amp;&amp;(h.vertical="middle"),r(i(n),i(s))&gt;r(i(o),i(u))?h.important="horizontal":h.important="vertical",t.using.call(this,e,h)}),a.offset(e.extend(C,{using:u}))})},e.ui.position={fit:{left:function(e,t){var n=t.within,i=n.isWindow?n.scrollLeft:n.offset.left,s=n.width,o=e.left-t.collisionPosition.marginLeft,u=i-o,a=o+t.collisionWidth-s-i,f;t.collisionWidth&gt;s?u&gt;0&amp;&amp;a&lt;=0?(f=e.left+u+t.collisionWidth-s-i,e.left+=u-f):a&gt;0&amp;&amp;u&lt;=0?e.left=i:u&gt;a?e.left=i+s-t.collisionWidth:e.left=i:u&gt;0?e.left+=u:a&gt;0?e.left-=a:e.left=r(e.left-o,e.left)},top:function(e,t){var n=t.within,i=n.isWindow?n.scrollTop:n.offset.top,s=t.within.height,o=e.top-t.collisionPosition.marginTop,u=i-o,a=o+t.collisionHeight-s-i,f;t.collisionHeight&gt;s?u&gt;0&amp;&amp;a&lt;=0?(f=e.top+u+t.collisionHeight-s-i,e.top+=u-f):a&gt;0&amp;&amp;u&lt;=0?e.top=i:u&gt;a?e.top=i+s-t.collisionHeight:e.top=i:u&gt;0?e.top+=u:a&gt;0?e.top-=a:e.top=r(e.top-o,e.top)}},flip:{left:function(e,t){var n=t.within,r=n.offset.left+n.scrollLeft,s=n.width,o=n.isWindow?n.scrollLeft:n.offset.left,u=e.left-t.collisionPosition.marginLeft,a=u-o,f=u+t.collisionWidth-s-o,l=t.my[0]==="left"?-t.elemWidth:t.my[0]==="right"?t.elemWidth:0,c=t.at[0]==="left"?t.targetWidth:t.at[0]==="right"?-t.targetWidth:0,h=-2*t.offset[0],p,d;if(a&lt;0){p=e.left+l+c+h+t.collisionWidth-s-r;if(p&lt;0||p&lt;i(a))e.left+=l+c+h}else if(f&gt;0){d=e.left-t.collisionPosition.marginLeft+l+c+h-o;if(d&gt;0||i(d)&lt;f)e.left+=l+c+h}},top:function(e,t){var n=t.within,r=n.offset.top+n.scrollTop,s=n.height,o=n.isWindow?n.scrollTop:n.offset.top,u=e.top-t.collisionPosition.marginTop,a=u-o,f=u+t.collisionHeight-s-o,l=t.my[1]==="top",c=l?-t.elemHeight:t.my[1]==="bottom"?t.elemHeight:0,h=t.at[1]==="top"?t.targetHeight:t.at[1]==="bottom"?-t.targetHeight:0,p=-2*t.offset[1],d,v;a&lt;0?(v=e.top+c+h+p+t.collisionHeight-s-r,e.top+c+h+p&gt;a&amp;&amp;(v&lt;0||v&lt;i(a))&amp;&amp;(e.top+=c+h+p)):f&gt;0&amp;&amp;(d=e.top-t.collisionPosition.marginTop+c+h+p-o,e.top+c+h+p&gt;f&amp;&amp;(d&gt;0||i(d)&lt;f)&amp;&amp;(e.top+=c+h+p))}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,n,r,i,s,o=document.getElementsByTagName("body")[0],u=document.createElement("div");t=document.createElement(o?"div":"body"),r={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},o&amp;&amp;e.extend(r,{position:"absolute",left:"-1000px",top:"-1000px"});for(s in r)t.style[s]=r[s];t.appendChild(u),n=o||document.documentElement,n.insertBefore(t,n.firstChild),u.style.cssText="position: absolute; left: 10.7432222px;",i=e(u).offset().left,e.support.offsetFractions=i&gt;10&amp;&amp;i&lt;11,t.innerHTML="",n.removeChild(t)}(),e.uiBackCompat!==!1&amp;&amp;function(e){var n=e.fn.position;e.fn.position=function(r){if(!r||!r.offset)return n.call(this,r);var i=r.offset.split(" "),s=r.at.split(" ");return i.length===1&amp;&amp;(i[1]=i[0]),/^\d/.test(i[0])&amp;&amp;(i[0]="+"+i[0]),/^\d/.test(i[1])&amp;&amp;(i[1]="+"+i[1]),s.length===1&amp;&amp;(/left|center|right/.test(s[0])?s[1]="center":(s[1]=s[0],s[0]="center")),n.call(this,e.extend(r,{at:s[0]+i[0]+" "+s[1]+i[1],offset:t}))}}(jQuery)})(jQuery);(function(e,t){e.widget("ui.draggable",e.ui.mouse,{version:"1.9.0",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){this.options.helper=="original"&amp;&amp;!/^(?:r|a|f)/.test(this.element.css("position"))&amp;&amp;(this.element[0].style.position="relative"),this.options.addClasses&amp;&amp;this.element.addClass("ui-draggable"),this.options.disabled&amp;&amp;this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(t){var n=this.options;return this.helper||n.disabled||e(t.target).is(".ui-resizable-handle")?!1:(this.handle=this._getHandle(t),this.handle?(e(n.iframeFix===!0?"iframe":n.iframeFix).each(function(){e('&lt;div class="ui-draggable-iframeFix" style="background: #fff;"&gt;&lt;/div&gt;').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(e(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(t){var n=this.options;return this.helper=this._createHelper(t),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),e.ui.ddmanager&amp;&amp;(e.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},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,n.cursorAt&amp;&amp;this._adjustOffsetFromHelper(n.cursorAt),n.containment&amp;&amp;this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&amp;&amp;!n.dropBehaviour&amp;&amp;e.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),e.ui.ddmanager&amp;&amp;e.ui.ddmanager.dragStart(this,t),!0)},_mouseDrag:function(t,n){this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute");if(!n){var r=this._uiHash();if(this._trigger("drag",t,r)===!1)return this._mouseUp({}),!1;this.position=r.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";return e.ui.ddmanager&amp;&amp;e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var n=!1;e.ui.ddmanager&amp;&amp;!this.options.dropBehaviour&amp;&amp;(n=e.ui.ddmanager.drop(this,t)),this.dropped&amp;&amp;(n=this.dropped,this.dropped=!1);var r=this.element[0],i=!1;while(r&amp;&amp;(r=r.parentNode))r==document&amp;&amp;(i=!0);if(!i&amp;&amp;this.options.helper==="original")return!1;if(this.options.revert=="invalid"&amp;&amp;!n||this.options.revert=="valid"&amp;&amp;n||this.options.revert===!0||e.isFunction(this.options.revert)&amp;&amp;this.options.revert.call(this.element,n)){var s=this;e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){s._trigger("stop",t)!==!1&amp;&amp;s._clear()})}else this._trigger("stop",t)!==!1&amp;&amp;this._clear();return!1},_mouseUp:function(t){return e("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),e.ui.ddmanager&amp;&amp;e.ui.ddmanager.dragStop(this,t),e.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(t){var n=!this.options.handle||!e(this.options.handle,this.element).length?!0:!1;return e(this.options.handle,this.element).find("*").andSelf().each(function(){this==t.target&amp;&amp;(n=!0)}),n},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t])):n.helper=="clone"?this.element.clone().removeAttr("id"):this.element;return r.parents("body").length||r.appendTo(n.appendTo=="parent"?this.element[0].parentNode:n.appendTo),r[0]!=this.element[0]&amp;&amp;!/(fixed|absolute)/.test(r.css("position"))&amp;&amp;r.css("position","absolute"),r},_adjustOffsetFromHelper:function(t){typeof t=="string"&amp;&amp;(t=t.split(" ")),e.isArray(t)&amp;&amp;(t={left:+t[0],top:+t[1]||0}),"left"in t&amp;&amp;(this.offset.click.left=t.left+this.margins.left),"right"in t&amp;&amp;(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&amp;&amp;(this.offset.click.top=t.top+this.margins.top),"bottom"in t&amp;&amp;(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();this.cssPosition=="absolute"&amp;&amp;this.scrollParent[0]!=document&amp;&amp;e.contains(this.scrollParent[0],this.offsetParent[0])&amp;&amp;(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&amp;&amp;this.offsetParent[0].tagName.toLowerCase()=="html"&amp;&amp;e.browser.msie)t={top:0,left:0};return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var e=this.element.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){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(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t=this.options;t.containment=="parent"&amp;&amp;(t.containment=this.helper[0].parentNode);if(t.containment=="document"||t.containment=="window")this.containment=[t.containment=="document"?0:e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t.containment=="document"?0:e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(t.containment=="document"?0:e(window).scrollLeft())+e(t.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(t.containment=="document"?0:e(window).scrollTop())+(e(t.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(t.containment)&amp;&amp;t.containment.constructor!=Array){var n=e(t.containment),r=n[0];if(!r)return;var i=n.offset(),s=e(r).css("overflow")!="hidden";this.containment=[(parseInt(e(r).css("borderLeftWidth"),10)||0)+(parseInt(e(r).css("paddingLeft"),10)||0),(parseInt(e(r).css("borderTopWidth"),10)||0)+(parseInt(e(r).css("paddingTop"),10)||0),(s?Math.max(r.scrollWidth,r.offsetWidth):r.offsetWidth)-(parseInt(e(r).css("borderLeftWidth"),10)||0)-(parseInt(e(r).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(s?Math.max(r.scrollHeight,r.offsetHeight):r.offsetHeight)-(parseInt(e(r).css("borderTopWidth"),10)||0)-(parseInt(e(r).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=n}else t.containment.constructor==Array&amp;&amp;(this.containment=t.containment)},_convertPositionTo:function(t,n){n||(n=this.position);var r=t=="absolute"?1:-1,i=this.options,s=this.cssPosition!="absolute"||this.scrollParent[0]!=document&amp;&amp;!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(s[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():o?0:s.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():o?0:s.scrollLeft())*r}},_generatePosition:function(t){var n=this.options,r=this.cssPosition!="absolute"||this.scrollParent[0]!=document&amp;&amp;!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,i=/(html|body)/i.test(r[0].tagName),s=t.pageX,o=t.pageY;if(this.originalPosition){var u;if(this.containment){if(this.relative_container){var a=this.relative_container.offset();u=[this.containment[0]+a.left,this.containment[1]+a.top,this.containment[2]+a.left,this.containment[3]+a.top]}else u=this.containment;t.pageX-this.offset.click.left&lt;u[0]&amp;&amp;(s=u[0]+this.offset.click.left),t.pageY-this.offset.click.top&lt;u[1]&amp;&amp;(o=u[1]+this.offset.click.top),t.pageX-this.offset.click.left&gt;u[2]&amp;&amp;(s=u[2]+this.offset.click.left),t.pageY-this.offset.click.top&gt;u[3]&amp;&amp;(o=u[3]+this.offset.click.top)}if(n.grid){var f=n.grid[1]?this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1]:this.originalPageY;o=u?f-this.offset.click.top&lt;u[1]||f-this.offset.click.top&gt;u[3]?f-this.offset.click.top&lt;u[1]?f+n.grid[1]:f-n.grid[1]:f:f;var l=n.grid[0]?this.originalPageX+Math.round((s-this.originalPageX)/n.grid[0])*n.grid[0]:this.originalPageX;s=u?l-this.offset.click.left&lt;u[0]||l-this.offset.click.left&gt;u[2]?l-this.offset.click.left&lt;u[0]?l+n.grid[0]:l-n.grid[0]:l:l}}return{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():i?0:r.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:r.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]!=this.element[0]&amp;&amp;!this.cancelHelperRemoval&amp;&amp;this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(t,n,r){return r=r||this._uiHash(),e.ui.plugin.call(this,t,[n,r]),t=="drag"&amp;&amp;(this.positionAbs=this._convertPositionTo("absolute")),e.Widget.prototype._trigger.call(this,t,n,r)},plugins:{},_uiHash:function(e){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,n){var r=e(this).data("draggable"),i=r.options,s=e.extend({},n,{item:r.element});r.sortables=[],e(i.connectToSortable).each(function(){var n=e.data(this,"sortable");n&amp;&amp;!n.options.disabled&amp;&amp;(r.sortables.push({instance:n,shouldRevert:n.options.revert}),n.refreshPositions(),n._trigger("activate",t,s))})},stop:function(t,n){var r=e(this).data("draggable"),i=e.extend({},n,{item:r.element});e.each(r.sortables,function(){this.instance.isOver?(this.instance.isOver=0,r.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&amp;&amp;(this.instance.options.revert=!0),this.instance._mouseStop(t),this.instance.options.helper=this.instance.options._helper,r.options.helper=="original"&amp;&amp;this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",t,i))})},drag:function(t,n){var r=e(this).data("draggable"),i=this,s=function(t){var n=this.offset.click.top,r=this.offset.click.left,i=this.positionAbs.top,s=this.positionAbs.left,o=t.height,u=t.width,a=t.top,f=t.left;return e.ui.isOver(i+n,s+r,a,f,o,u)};e.each(r.sortables,function(s){this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this.instance._intersectsWith(this.instance.containerCache)?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(i).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return n.helper[0]},t.target=this.instance.currentItem[0],this.instance._mouseCapture(t,!0),this.instance._mouseStart(t,!0,!0),this.instance.offset.click.top=r.offset.click.top,this.instance.offset.click.left=r.offset.click.left,this.instance.offset.parent.left-=r.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=r.offset.parent.top-this.instance.offset.parent.top,r._trigger("toSortable",t),r.dropped=this.instance.element,r.currentItem=r.element,this.instance.fromOutside=r),this.instance.currentItem&amp;&amp;this.instance._mouseDrag(t)):this.instance.isOver&amp;&amp;(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",t,this.instance._uiHash(this.instance)),this.instance._mouseStop(t,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&amp;&amp;this.instance.placeholder.remove(),r._trigger("fromSortable",t),r.dropped=!1)})}}),e.ui.plugin.add("draggable","cursor",{start:function(t,n){var r=e("body"),i=e(this).data("draggable").options;r.css("cursor")&amp;&amp;(i._cursor=r.css("cursor")),r.css("cursor",i.cursor)},stop:function(t,n){var r=e(this).data("draggable").options;r._cursor&amp;&amp;e("body").css("cursor",r._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,n){var r=e(n.helper),i=e(this).data("draggable").options;r.css("opacity")&amp;&amp;(i._opacity=r.css("opacity")),r.css("opacity",i.opacity)},stop:function(t,n){var r=e(this).data("draggable").options;r._opacity&amp;&amp;e(n.helper).css("opacity",r._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(t,n){var r=e(this).data("draggable");r.scrollParent[0]!=document&amp;&amp;r.scrollParent[0].tagName!="HTML"&amp;&amp;(r.overflowOffset=r.scrollParent.offset())},drag:function(t,n){var r=e(this).data("draggable"),i=r.options,s=!1;if(r.scrollParent[0]!=document&amp;&amp;r.scrollParent[0].tagName!="HTML"){if(!i.axis||i.axis!="x")r.overflowOffset.top+r.scrollParent[0].offsetHeight-t.pageY&lt;i.scrollSensitivity?r.scrollParent[0].scrollTop=s=r.scrollParent[0].scrollTop+i.scrollSpeed:t.pageY-r.overflowOffset.top&lt;i.scrollSensitivity&amp;&amp;(r.scrollParent[0].scrollTop=s=r.scrollParent[0].scrollTop-i.scrollSpeed);if(!i.axis||i.axis!="y")r.overflowOffset.left+r.scrollParent[0].offsetWidth-t.pageX&lt;i.scrollSensitivity?r.scrollParent[0].scrollLeft=s=r.scrollParent[0].scrollLeft+i.scrollSpeed:t.pageX-r.overflowOffset.left&lt;i.scrollSensitivity&amp;&amp;(r.scrollParent[0].scrollLeft=s=r.scrollParent[0].scrollLeft-i.scrollSpeed)}else{if(!i.axis||i.axis!="x")t.pageY-e(document).scrollTop()&lt;i.scrollSensitivity?s=e(document).scrollTop(e(document).scrollTop()-i.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())&lt;i.scrollSensitivity&amp;&amp;(s=e(document).scrollTop(e(document).scrollTop()+i.scrollSpeed));if(!i.axis||i.axis!="y")t.pageX-e(document).scrollLeft()&lt;i.scrollSensitivity?s=e(document).scrollLeft(e(document).scrollLeft()-i.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())&lt;i.scrollSensitivity&amp;&amp;(s=e(document).scrollLeft(e(document).scrollLeft()+i.scrollSpeed))}s!==!1&amp;&amp;e.ui.ddmanager&amp;&amp;!i.dropBehaviour&amp;&amp;e.ui.ddmanager.prepareOffsets(r,t)}}),e.ui.plugin.add("draggable","snap",{start:function(t,n){var r=e(this).data("draggable"),i=r.options;r.snapElements=[],e(i.snap.constructor!=String?i.snap.items||":data(draggable)":i.snap).each(function(){var t=e(this),n=t.offset();this!=r.element[0]&amp;&amp;r.snapElements.push({item:this,width:t.outerWidth(),height:t.outerHeight(),top:n.top,left:n.left})})},drag:function(t,n){var r=e(this).data("draggable"),i=r.options,s=i.snapTolerance,o=n.offset.left,u=o+r.helperProportions.width,a=n.offset.top,f=a+r.helperProportions.height;for(var l=r.snapElements.length-1;l&gt;=0;l--){var c=r.snapElements[l].left,h=c+r.snapElements[l].width,p=r.snapElements[l].top,d=p+r.snapElements[l].height;if(!(c-s&lt;o&amp;&amp;o&lt;h+s&amp;&amp;p-s&lt;a&amp;&amp;a&lt;d+s||c-s&lt;o&amp;&amp;o&lt;h+s&amp;&amp;p-s&lt;f&amp;&amp;f&lt;d+s||c-s&lt;u&amp;&amp;u&lt;h+s&amp;&amp;p-s&lt;a&amp;&amp;a&lt;d+s||c-s&lt;u&amp;&amp;u&lt;h+s&amp;&amp;p-s&lt;f&amp;&amp;f&lt;d+s)){r.snapElements[l].snapping&amp;&amp;r.options.snap.release&amp;&amp;r.options.snap.release.call(r.element,t,e.extend(r._uiHash(),{snapItem:r.snapElements[l].item})),r.snapElements[l].snapping=!1;continue}if(i.snapMode!="inner"){var v=Math.abs(p-f)&lt;=s,m=Math.abs(d-a)&lt;=s,g=Math.abs(c-u)&lt;=s,y=Math.abs(h-o)&lt;=s;v&amp;&amp;(n.position.top=r._convertPositionTo("relative",{top:p-r.helperProportions.height,left:0}).top-r.margins.top),m&amp;&amp;(n.position.top=r._convertPositionTo("relative",{top:d,left:0}).top-r.margins.top),g&amp;&amp;(n.position.left=r._convertPositionTo("relative",{top:0,left:c-r.helperProportions.width}).left-r.margins.left),y&amp;&amp;(n.position.left=r._convertPositionTo("relative",{top:0,left:h}).left-r.margins.left)}var b=v||m||g||y;if(i.snapMode!="outer"){var v=Math.abs(p-a)&lt;=s,m=Math.abs(d-f)&lt;=s,g=Math.abs(c-o)&lt;=s,y=Math.abs(h-u)&lt;=s;v&amp;&amp;(n.position.top=r._convertPositionTo("relative",{top:p,left:0}).top-r.margins.top),m&amp;&amp;(n.position.top=r._convertPositionTo("relative",{top:d-r.helperProportions.height,left:0}).top-r.margins.top),g&amp;&amp;(n.position.left=r._convertPositionTo("relative",{top:0,left:c}).left-r.margins.left),y&amp;&amp;(n.position.left=r._convertPositionTo("relative",{top:0,left:h-r.helperProportions.width}).left-r.margins.left)}!r.snapElements[l].snapping&amp;&amp;(v||m||g||y||b)&amp;&amp;r.options.snap.snap&amp;&amp;r.options.snap.snap.call(r.element,t,e.extend(r._uiHash(),{snapItem:r.snapElements[l].item})),r.snapElements[l].snapping=v||m||g||y||b}}}),e.ui.plugin.add("draggable","stack",{start:function(t,n){var r=e(this).data("draggable").options,i=e.makeArray(e(r.stack)).sort(function(t,n){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(n).css("zIndex"),10)||0)});if(!i.length)return;var s=parseInt(i[0].style.zIndex)||0;e(i).each(function(e){this.style.zIndex=s+e}),this[0].style.zIndex=s+i.length}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,n){var r=e(n.helper),i=e(this).data("draggable").options;r.css("zIndex")&amp;&amp;(i._zIndex=r.css("zIndex")),r.css("zIndex",i.zIndex)},stop:function(t,n){var r=e(this).data("draggable").options;r._zIndex&amp;&amp;e(n.helper).css("zIndex",r._zIndex)}})})(jQuery);(function(e,t){e.widget("ui.droppable",{version:"1.9.0",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect"},_create:function(){var t=this.options,n=t.accept;this.isover=0,this.isout=1,this.accept=e.isFunction(n)?n:function(e){return e.is(n)},this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},e.ui.ddmanager.droppables[t.scope]=e.ui.ddmanager.droppables[t.scope]||[],e.ui.ddmanager.droppables[t.scope].push(this),t.addClasses&amp;&amp;this.element.addClass("ui-droppable")},_destroy:function(){var t=e.ui.ddmanager.droppables[this.options.scope];for(var n=0;n&lt;t.length;n++)t[n]==this&amp;&amp;t.splice(n,1);this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(t,n){t=="accept"&amp;&amp;(this.accept=e.isFunction(n)?n:function(e){return e.is(n)}),e.Widget.prototype._setOption.apply(this,arguments)},_activate:function(t){var n=e.ui.ddmanager.current;this.options.activeClass&amp;&amp;this.element.addClass(this.options.activeClass),n&amp;&amp;this._trigger("activate",t,this.ui(n))},_deactivate:function(t){var n=e.ui.ddmanager.current;this.options.activeClass&amp;&amp;this.element.removeClass(this.options.activeClass),n&amp;&amp;this._trigger("deactivate",t,this.ui(n))},_over:function(t){var n=e.ui.ddmanager.current;if(!n||(n.currentItem||n.element)[0]==this.element[0])return;this.accept.call(this.element[0],n.currentItem||n.element)&amp;&amp;(this.options.hoverClass&amp;&amp;this.element.addClass(this.options.hoverClass),this._trigger("over",t,this.ui(n)))},_out:function(t){var n=e.ui.ddmanager.current;if(!n||(n.currentItem||n.element)[0]==this.element[0])return;this.accept.call(this.element[0],n.currentItem||n.element)&amp;&amp;(this.options.hoverClass&amp;&amp;this.element.removeClass(this.options.hoverClass),this._trigger("out",t,this.ui(n)))},_drop:function(t,n){var r=n||e.ui.ddmanager.current;if(!r||(r.currentItem||r.element)[0]==this.element[0])return!1;var i=!1;return this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var t=e.data(this,"droppable");if(t.options.greedy&amp;&amp;!t.options.disabled&amp;&amp;t.options.scope==r.options.scope&amp;&amp;t.accept.call(t.element[0],r.currentItem||r.element)&amp;&amp;e.ui.intersect(r,e.extend(t,{offset:t.element.offset()}),t.options.tolerance))return i=!0,!1}),i?!1:this.accept.call(this.element[0],r.currentItem||r.element)?(this.options.activeClass&amp;&amp;this.element.removeClass(this.options.activeClass),this.options.hoverClass&amp;&amp;this.element.removeClass(this.options.hoverClass),this._trigger("drop",t,this.ui(r)),this.element):!1},ui:function(e){return{draggable:e.currentItem||e.element,helper:e.helper,position:e.position,offset:e.positionAbs}}}),e.ui.intersect=function(t,n,r){if(!n.offset)return!1;var i=(t.positionAbs||t.position.absolute).left,s=i+t.helperProportions.width,o=(t.positionAbs||t.position.absolute).top,u=o+t.helperProportions.height,a=n.offset.left,f=a+n.proportions.width,l=n.offset.top,c=l+n.proportions.height;switch(r){case"fit":return a&lt;=i&amp;&amp;s&lt;=f&amp;&amp;l&lt;=o&amp;&amp;u&lt;=c;case"intersect":return a&lt;i+t.helperProportions.width/2&amp;&amp;s-t.helperProportions.width/2&lt;f&amp;&amp;l&lt;o+t.helperProportions.height/2&amp;&amp;u-t.helperProportions.height/2&lt;c;case"pointer":var h=(t.positionAbs||t.position.absolute).left+(t.clickOffset||t.offset.click).left,p=(t.positionAbs||t.position.absolute).top+(t.clickOffset||t.offset.click).top,d=e.ui.isOver(p,h,l,a,n.proportions.height,n.proportions.width);return d;case"touch":return(o&gt;=l&amp;&amp;o&lt;=c||u&gt;=l&amp;&amp;u&lt;=c||o&lt;l&amp;&amp;u&gt;c)&amp;&amp;(i&gt;=a&amp;&amp;i&lt;=f||s&gt;=a&amp;&amp;s&lt;=f||i&lt;a&amp;&amp;s&gt;f);default:return!1}},e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,n){var r=e.ui.ddmanager.droppables[t.options.scope]||[],i=n?n.type:null,s=(t.currentItem||t.element).find(":data(droppable)").andSelf();e:for(var o=0;o&lt;r.length;o++){if(r[o].options.disabled||t&amp;&amp;!r[o].accept.call(r[o].element[0],t.currentItem||t.element))continue;for(var u=0;u&lt;s.length;u++)if(s[u]==r[o].element[0]){r[o].proportions.height=0;continue e}r[o].visible=r[o].element.css("display")!="none";if(!r[o].visible)continue;i=="mousedown"&amp;&amp;r[o]._activate.call(r[o],n),r[o].offset=r[o].element.offset(),r[o].proportions={width:r[o].element[0].offsetWidth,height:r[o].element[0].offsetHeight}}},drop:function(t,n){var r=!1;return e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(!this.options)return;!this.options.disabled&amp;&amp;this.visible&amp;&amp;e.ui.intersect(t,this,this.options.tolerance)&amp;&amp;(r=this._drop.call(this,n)||r),!this.options.disabled&amp;&amp;this.visible&amp;&amp;this.accept.call(this.element[0],t.currentItem||t.element)&amp;&amp;(this.isout=1,this.isover=0,this._deactivate.call(this,n))}),r},dragStart:function(t,n){t.element.parentsUntil("body").bind("scroll.droppable",function(){t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,n)})},drag:function(t,n){t.options.refreshPositions&amp;&amp;e.ui.ddmanager.prepareOffsets(t,n),e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible)return;var r=e.ui.intersect(t,this,this.options.tolerance),i=!r&amp;&amp;this.isover==1?"isout":r&amp;&amp;this.isover==0?"isover":null;if(!i)return;var s;if(this.options.greedy){var o=this.options.scope,u=this.element.parents(":data(droppable)").filter(function(){return e.data(this,"droppable").options.scope===o});u.length&amp;&amp;(s=e.data(u[0],"droppable"),s.greedyChild=i=="isover"?1:0)}s&amp;&amp;i=="isover"&amp;&amp;(s.isover=0,s.isout=1,s._out.call(s,n)),this[i]=1,this[i=="isout"?"isover":"isout"]=0,this[i=="isover"?"_over":"_out"].call(this,n),s&amp;&amp;i=="isout"&amp;&amp;(s.isout=0,s.isover=1,s._over.call(s,n))})},dragStop:function(t,n){t.element.parentsUntil("body").unbind("scroll.droppable"),t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,n)}}})(jQuery);(function(e,t){e.widget("ui.resizable",e.ui.mouse,{version:"1.9.0",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1e3},_create:function(){var t=this,n=this.options;this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!n.aspectRatio,aspectRatio:n.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:n.helper||n.ghost||n.animate?n.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&amp;&amp;(this.element.wrap(e('&lt;div class="ui-wrapper" style="overflow: hidden;"&gt;&lt;/div&gt;').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=!0,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=n.handles||(e(".ui-resizable-handle",this.element).length?{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"}:"e,s,se");if(this.handles.constructor==String){this.handles=="all"&amp;&amp;(this.handles="n,e,s,w,se,sw,ne,nw");var r=this.handles.split(",");this.handles={};for(var i=0;i&lt;r.length;i++){var s=e.trim(r[i]),o="ui-resizable-"+s,u=e('&lt;div class="ui-resizable-handle '+o+'"&gt;&lt;/div&gt;');u.css({zIndex:n.zIndex}),"se"==s&amp;&amp;u.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(u)}}this._renderAxis=function(t){t=t||this.element;for(var n in this.handles){this.handles[n].constructor==String&amp;&amp;(this.handles[n]=e(this.handles[n],this.element).show());if(this.elementIsWrapper&amp;&amp;this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var r=e(this.handles[n],this.element),i=0;i=/sw|ne|nw|se|n|s/.test(n)?r.outerHeight():r.outerWidth();var s=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join("");t.css(s,i),this._proportionallyResize()}if(!e(this.handles[n]).length)continue}},this._renderAxis(this.element),this._handles=e(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){if(!t.resizing){if(this.className)var e=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);t.axis=e&amp;&amp;e[1]?e[1]:"se"}}),n.autoHide&amp;&amp;(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){if(n.disabled)return;e(this).removeClass("ui-resizable-autohide"),t._handles.show()}).mouseleave(function(){if(n.disabled)return;t.resizing||(e(this).addClass("ui-resizable-autohide"),t._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){t(this.element);var n=this.element;n.after(this.originalElement.css({position:n.css("position"),width:n.outerWidth(),height:n.outerHeight(),top:n.css("top"),left:n.css("left")})).remove()}return this.originalElement.css("resize",this.originalResizeStyle),t(this.originalElement),this},_mouseCapture:function(t){var n=!1;for(var r in this.handles)e(this.handles[r])[0]==t.target&amp;&amp;(n=!0);return!this.options.disabled&amp;&amp;n},_mouseStart:function(t){var r=this.options,i=this.element.position(),s=this.element;this.resizing=!0,this.documentScroll={top:e(document).scrollTop(),left:e(document).scrollLeft()},(s.is(".ui-draggable")||/absolute/.test(s.css("position")))&amp;&amp;s.css({position:"absolute",top:i.top,left:i.left}),this._renderProxy();var o=n(this.helper.css("left")),u=n(this.helper.css("top"));r.containment&amp;&amp;(o+=e(r.containment).scrollLeft()||0,u+=e(r.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:o,top:u},this.size=this._helper?{width:s.outerWidth(),height:s.outerHeight()}:{width:s.width(),height:s.height()},this.originalSize=this._helper?{width:s.outerWidth(),height:s.outerHeight()}:{width:s.width(),height:s.height()},this.originalPosition={left:o,top:u},this.sizeDiff={width:s.outerWidth()-s.width(),height:s.outerHeight()-s.height()},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio=typeof r.aspectRatio=="number"?r.aspectRatio:this.originalSize.width/this.originalSize.height||1;var a=e(".ui-resizable-"+this.axis).css("cursor");return e("body").css("cursor",a=="auto"?this.axis+"-resize":a),s.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(e){var t=this.helper,n=this.options,r={},i=this,s=this.originalMousePosition,o=this.axis,u=e.pageX-s.left||0,a=e.pageY-s.top||0,f=this._change[o];if(!f)return!1;var l=f.apply(this,[e,u,a]);this._updateVirtualBoundaries(e.shiftKey);if(this._aspectRatio||e.shiftKey)l=this._updateRatio(l,e);return l=this._respectSize(l,e),this._propagate("resize",e),t.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"}),!this._helper&amp;&amp;this._proportionallyResizeElements.length&amp;&amp;this._proportionallyResize(),this._updateCache(l),this._trigger("resize",e,this.ui()),!1},_mouseStop:function(t){this.resizing=!1;var n=this.options,r=this;if(this._helper){var i=this._proportionallyResizeElements,s=i.length&amp;&amp;/textarea/i.test(i[0].nodeName),o=s&amp;&amp;e.ui.hasScroll(i[0],"left")?0:r.sizeDiff.height,u=s?0:r.sizeDiff.width,a={width:r.helper.width()-u,height:r.helper.height()-o},f=parseInt(r.element.css("left"),10)+(r.position.left-r.originalPosition.left)||null,l=parseInt(r.element.css("top"),10)+(r.position.top-r.originalPosition.top)||null;n.animate||this.element.css(e.extend(a,{top:l,left:f})),r.helper.height(r.size.height),r.helper.width(r.size.width),this._helper&amp;&amp;!n.animate&amp;&amp;this._proportionallyResize()}return e("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&amp;&amp;this.helper.remove(),!1},_updateVirtualBoundaries:function(e){var t=this.options,n,i,s,o,u;u={minWidth:r(t.minWidth)?t.minWidth:0,maxWidth:r(t.maxWidth)?t.maxWidth:Infinity,minHeight:r(t.minHeight)?t.minHeight:0,maxHeight:r(t.maxHeight)?t.maxHeight:Infinity};if(this._aspectRatio||e)n=u.minHeight*this.aspectRatio,s=u.minWidth/this.aspectRatio,i=u.maxHeight*this.aspectRatio,o=u.maxWidth/this.aspectRatio,n&gt;u.minWidth&amp;&amp;(u.minWidth=n),s&gt;u.minHeight&amp;&amp;(u.minHeight=s),i&lt;u.maxWidth&amp;&amp;(u.maxWidth=i),o&lt;u.maxHeight&amp;&amp;(u.maxHeight=o);this._vBoundaries=u},_updateCache:function(e){var t=this.options;this.offset=this.helper.offset(),r(e.left)&amp;&amp;(this.position.left=e.left),r(e.top)&amp;&amp;(this.position.top=e.top),r(e.height)&amp;&amp;(this.size.height=e.height),r(e.width)&amp;&amp;(this.size.width=e.width)},_updateRatio:function(e,t){var n=this.options,i=this.position,s=this.size,o=this.axis;return r(e.height)?e.width=e.height*this.aspectRatio:r(e.width)&amp;&amp;(e.height=e.width/this.aspectRatio),o=="sw"&amp;&amp;(e.left=i.left+(s.width-e.width),e.top=null),o=="nw"&amp;&amp;(e.top=i.top+(s.height-e.height),e.left=i.left+(s.width-e.width)),e},_respectSize:function(e,t){var n=this.helper,i=this._vBoundaries,s=this._aspectRatio||t.shiftKey,o=this.axis,u=r(e.width)&amp;&amp;i.maxWidth&amp;&amp;i.maxWidth&lt;e.width,a=r(e.height)&amp;&amp;i.maxHeight&amp;&amp;i.maxHeight&lt;e.height,f=r(e.width)&amp;&amp;i.minWidth&amp;&amp;i.minWidth&gt;e.width,l=r(e.height)&amp;&amp;i.minHeight&amp;&amp;i.minHeight&gt;e.height;f&amp;&amp;(e.width=i.minWidth),l&amp;&amp;(e.height=i.minHeight),u&amp;&amp;(e.width=i.maxWidth),a&amp;&amp;(e.height=i.maxHeight);var c=this.originalPosition.left+this.originalSize.width,h=this.position.top+this.size.height,p=/sw|nw|w/.test(o),d=/nw|ne|n/.test(o);f&amp;&amp;p&amp;&amp;(e.left=c-i.minWidth),u&amp;&amp;p&amp;&amp;(e.left=c-i.maxWidth),l&amp;&amp;d&amp;&amp;(e.top=h-i.minHeight),a&amp;&amp;d&amp;&amp;(e.top=h-i.maxHeight);var v=!e.width&amp;&amp;!e.height;return v&amp;&amp;!e.left&amp;&amp;e.top?e.top=null:v&amp;&amp;!e.top&amp;&amp;e.left&amp;&amp;(e.left=null),e},_proportionallyResize:function(){var t=this.options;if(!this._proportionallyResizeElements.length)return;var n=this.helper||this.element;for(var r=0;r&lt;this._proportionallyResizeElements.length;r++){var i=this._proportionallyResizeElements[r];if(!this.borderDif){var s=[i.css("borderTopWidth"),i.css("borderRightWidth"),i.css("borderBottomWidth"),i.css("borderLeftWidth")],o=[i.css("paddingTop"),i.css("paddingRight"),i.css("paddingBottom"),i.css("paddingLeft")];this.borderDif=e.map(s,function(e,t){var n=parseInt(e,10)||0,r=parseInt(o[t],10)||0;return n+r})}i.css({height:n.height()-this.borderDif[0]-this.borderDif[2]||0,width:n.width()-this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var t=this.element,n=this.options;this.elementOffset=t.offset();if(this._helper){this.helper=this.helper||e('&lt;div style="overflow:hidden;"&gt;&lt;/div&gt;');var r=e.browser.msie&amp;&amp;e.browser.version&lt;7,i=r?1:0,s=r?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+s,height:this.element.outerHeight()+s,position:"absolute",left:this.elementOffset.left-i+"px",top:this.elementOffset.top-i+"px",zIndex:++n.zIndex}),this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(e,t,n){return{width:this.originalSize.width+t}},w:function(e,t,n){var r=this.options,i=this.originalSize,s=this.originalPosition;return{left:s.left+t,width:i.width-t}},n:function(e,t,n){var r=this.options,i=this.originalSize,s=this.originalPosition;return{top:s.top+n,height:i.height-n}},s:function(e,t,n){return{height:this.originalSize.height+n}},se:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},sw:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,n,r]))},ne:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},nw:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,n,r]))}},_propagate:function(t,n){e.ui.plugin.call(this,t,[n,this.ui()]),t!="resize"&amp;&amp;this._trigger(t,n,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),e.ui.plugin.add("resizable","alsoResize",{start:function(t,n){var r=e(this).data("resizable"),i=r.options,s=function(t){e(t).each(function(){var t=e(this);t.data("resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};typeof i.alsoResize=="object"&amp;&amp;!i.alsoResize.parentNode?i.alsoResize.length?(i.alsoResize=i.alsoResize[0],s(i.alsoResize)):e.each(i.alsoResize,function(e){s(e)}):s(i.alsoResize)},resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.originalSize,o=r.originalPosition,u={height:r.size.height-s.height||0,width:r.size.width-s.width||0,top:r.position.top-o.top||0,left:r.position.left-o.left||0},a=function(t,r){e(t).each(function(){var t=e(this),i=e(this).data("resizable-alsoresize"),s={},o=r&amp;&amp;r.length?r:t.parents(n.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(o,function(e,t){var n=(i[t]||0)+(u[t]||0);n&amp;&amp;n&gt;=0&amp;&amp;(s[t]=n||null)}),t.css(s)})};typeof i.alsoResize=="object"&amp;&amp;!i.alsoResize.nodeType?e.each(i.alsoResize,function(e,t){a(e,t)}):a(i.alsoResize)},stop:function(t,n){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","animate",{stop:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r._proportionallyResizeElements,o=s.length&amp;&amp;/textarea/i.test(s[0].nodeName),u=o&amp;&amp;e.ui.hasScroll(s[0],"left")?0:r.sizeDiff.height,a=o?0:r.sizeDiff.width,f={width:r.size.width-a,height:r.size.height-u},l=parseInt(r.element.css("left"),10)+(r.position.left-r.originalPosition.left)||null,c=parseInt(r.element.css("top"),10)+(r.position.top-r.originalPosition.top)||null;r.element.animate(e.extend(f,c&amp;&amp;l?{top:c,left:l}:{}),{duration:i.animateDuration,easing:i.animateEasing,step:function(){var n={width:parseInt(r.element.css("width"),10),height:parseInt(r.element.css("height"),10),top:parseInt(r.element.css("top"),10),left:parseInt(r.element.css("left"),10)};s&amp;&amp;s.length&amp;&amp;e(s[0]).css({width:n.width,height:n.height}),r._updateCache(n),r._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(t,r){var i=e(this).data("resizable"),s=i.options,o=i.element,u=s.containment,a=u instanceof e?u.get(0):/parent/.test(u)?o.parent().get(0):u;if(!a)return;i.containerElement=e(a);if(/document/.test(u)||u==document)i.containerOffset={left:0,top:0},i.containerPosition={left:0,top:0},i.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight};else{var f=e(a),l=[];e(["Top","Right","Left","Bottom"]).each(function(e,t){l[e]=n(f.css("padding"+t))}),i.containerOffset=f.offset(),i.containerPosition=f.position(),i.containerSize={height:f.innerHeight()-l[3],width:f.innerWidth()-l[1]};var c=i.containerOffset,h=i.containerSize.height,p=i.containerSize.width,d=e.ui.hasScroll(a,"left")?a.scrollWidth:p,v=e.ui.hasScroll(a)?a.scrollHeight:h;i.parentData={element:a,left:c.left,top:c.top,width:d,height:v}}},resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.containerSize,o=r.containerOffset,u=r.size,a=r.position,f=r._aspectRatio||t.shiftKey,l={top:0,left:0},c=r.containerElement;c[0]!=document&amp;&amp;/static/.test(c.css("position"))&amp;&amp;(l=o),a.left&lt;(r._helper?o.left:0)&amp;&amp;(r.size.width=r.size.width+(r._helper?r.position.left-o.left:r.position.left-l.left),f&amp;&amp;(r.size.height=r.size.width/r.aspectRatio),r.position.left=i.helper?o.left:0),a.top&lt;(r._helper?o.top:0)&amp;&amp;(r.size.height=r.size.height+(r._helper?r.position.top-o.top:r.position.top),f&amp;&amp;(r.size.width=r.size.height*r.aspectRatio),r.position.top=r._helper?o.top:0),r.offset.left=r.parentData.left+r.position.left,r.offset.top=r.parentData.top+r.position.top;var h=Math.abs((r._helper?r.offset.left-l.left:r.offset.left-l.left)+r.sizeDiff.width),p=Math.abs((r._helper?r.offset.top-l.top:r.offset.top-o.top)+r.sizeDiff.height),d=r.containerElement.get(0)==r.element.parent().get(0),v=/relative|absolute/.test(r.containerElement.css("position"));d&amp;&amp;v&amp;&amp;(h-=r.parentData.left),h+r.size.width&gt;=r.parentData.width&amp;&amp;(r.size.width=r.parentData.width-h,f&amp;&amp;(r.size.height=r.size.width/r.aspectRatio)),p+r.size.height&gt;=r.parentData.height&amp;&amp;(r.size.height=r.parentData.height-p,f&amp;&amp;(r.size.width=r.size.height*r.aspectRatio))},stop:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.position,o=r.containerOffset,u=r.containerPosition,a=r.containerElement,f=e(r.helper),l=f.offset(),c=f.outerWidth()-r.sizeDiff.width,h=f.outerHeight()-r.sizeDiff.height;r._helper&amp;&amp;!i.animate&amp;&amp;/relative/.test(a.css("position"))&amp;&amp;e(this).css({left:l.left-u.left-o.left,width:c,height:h}),r._helper&amp;&amp;!i.animate&amp;&amp;/static/.test(a.css("position"))&amp;&amp;e(this).css({left:l.left-u.left-o.left,width:c,height:h})}}),e.ui.plugin.add("resizable","ghost",{start:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.size;r.ghost=r.originalElement.clone(),r.ghost.css({opacity:.25,display:"block",position:"relative",height:s.height,width:s.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof i.ghost=="string"?i.ghost:""),r.ghost.appendTo(r.helper)},resize:function(t,n){var r=e(this).data("resizable"),i=r.options;r.ghost&amp;&amp;r.ghost.css({position:"relative",height:r.size.height,width:r.size.width})},stop:function(t,n){var r=e(this).data("resizable"),i=r.options;r.ghost&amp;&amp;r.helper&amp;&amp;r.helper.get(0).removeChild(r.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.size,o=r.originalSize,u=r.originalPosition,a=r.axis,f=i._aspectRatio||t.shiftKey;i.grid=typeof i.grid=="number"?[i.grid,i.grid]:i.grid;var l=Math.round((s.width-o.width)/(i.grid[0]||1))*(i.grid[0]||1),c=Math.round((s.height-o.height)/(i.grid[1]||1))*(i.grid[1]||1);/^(se|s|e)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c):/^(ne)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c,r.position.top=u.top-c):/^(sw)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c,r.position.left=u.left-l):(r.size.width=o.width+l,r.size.height=o.height+c,r.position.top=u.top-c,r.position.left=u.left-l)}});var n=function(e){return parseInt(e,10)||0},r=function(e){return!isNaN(parseInt(e,10))}})(jQuery);(function(e,t){e.widget("ui.selectable",e.ui.mouse,{version:"1.9.0",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch"},_create:function(){var t=this;this.element.addClass("ui-selectable"),this.dragged=!1;var n;this.refresh=function(){n=e(t.options.filter,t.element[0]),n.addClass("ui-selectee"),n.each(function(){var t=e(this),n=t.offset();e.data(this,"selectable-item",{element:this,$element:t,left:n.left,top:n.top,right:n.left+t.outerWidth(),bottom:n.top+t.outerHeight(),startselected:!1,selected:t.hasClass("ui-selected"),selecting:t.hasClass("ui-selecting"),unselecting:t.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=n.addClass("ui-selectee"),this._mouseInit(),this.helper=e("&lt;div class='ui-selectable-helper'&gt;&lt;/div&gt;")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(t){var n=this;this.opos=[t.pageX,t.pageY];if(this.options.disabled)return;var r=this.options;this.selectees=e(r.filter,this.element[0]),this._trigger("start",t),e(r.appendTo).append(this.helper),this.helper.css({left:t.clientX,top:t.clientY,width:0,height:0}),r.autoRefresh&amp;&amp;this.refresh(),this.selectees.filter(".ui-selected").each(function(){var r=e.data(this,"selectable-item");r.startselected=!0,!t.metaKey&amp;&amp;!t.ctrlKey&amp;&amp;(r.$element.removeClass("ui-selected"),r.selected=!1,r.$element.addClass("ui-unselecting"),r.unselecting=!0,n._trigger("unselecting",t,{unselecting:r.element}))}),e(t.target).parents().andSelf().each(function(){var r=e.data(this,"selectable-item");if(r){var i=!t.metaKey&amp;&amp;!t.ctrlKey||!r.$element.hasClass("ui-selected");return r.$element.removeClass(i?"ui-unselecting":"ui-selected").addClass(i?"ui-selecting":"ui-unselecting"),r.unselecting=!i,r.selecting=i,r.selected=i,i?n._trigger("selecting",t,{selecting:r.element}):n._trigger("unselecting",t,{unselecting:r.element}),!1}})},_mouseDrag:function(t){var n=this;this.dragged=!0;if(this.options.disabled)return;var r=this.options,i=this.opos[0],s=this.opos[1],o=t.pageX,u=t.pageY;if(i&gt;o){var a=o;o=i,i=a}if(s&gt;u){var a=u;u=s,s=a}return this.helper.css({left:i,top:s,width:o-i,height:u-s}),this.selectees.each(function(){var a=e.data(this,"selectable-item");if(!a||a.element==n.element[0])return;var f=!1;r.tolerance=="touch"?f=!(a.left&gt;o||a.right&lt;i||a.top&gt;u||a.bottom&lt;s):r.tolerance=="fit"&amp;&amp;(f=a.left&gt;i&amp;&amp;a.right&lt;o&amp;&amp;a.top&gt;s&amp;&amp;a.bottom&lt;u),f?(a.selected&amp;&amp;(a.$element.removeClass("ui-selected"),a.selected=!1),a.unselecting&amp;&amp;(a.$element.removeClass("ui-unselecting"),a.unselecting=!1),a.selecting||(a.$element.addClass("ui-selecting"),a.selecting=!0,n._trigger("selecting",t,{selecting:a.element}))):(a.selecting&amp;&amp;((t.metaKey||t.ctrlKey)&amp;&amp;a.startselected?(a.$element.removeClass("ui-selecting"),a.selecting=!1,a.$element.addClass("ui-selected"),a.selected=!0):(a.$element.removeClass("ui-selecting"),a.selecting=!1,a.startselected&amp;&amp;(a.$element.addClass("ui-unselecting"),a.unselecting=!0),n._trigger("unselecting",t,{unselecting:a.element}))),a.selected&amp;&amp;!t.metaKey&amp;&amp;!t.ctrlKey&amp;&amp;!a.startselected&amp;&amp;(a.$element.removeClass("ui-selected"),a.selected=!1,a.$element.addClass("ui-unselecting"),a.unselecting=!0,n._trigger("unselecting",t,{unselecting:a.element})))}),!1},_mouseStop:function(t){var n=this;this.dragged=!1;var r=this.options;return e(".ui-unselecting",this.element[0]).each(function(){var r=e.data(this,"selectable-item");r.$element.removeClass("ui-unselecting"),r.unselecting=!1,r.startselected=!1,n._trigger("unselected",t,{unselected:r.element})}),e(".ui-selecting",this.element[0]).each(function(){var r=e.data(this,"selectable-item");r.$element.removeClass("ui-selecting").addClass("ui-selected"),r.selecting=!1,r.selected=!0,r.startselected=!0,n._trigger("selected",t,{selected:r.element})}),this._trigger("stop",t),this.helper.remove(),!1}})})(jQuery);(function(e,t){e.widget("ui.sortable",e.ui.mouse,{version:"1.9.0",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"&gt; *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var e=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?e.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var e=this.items.length-1;e&gt;=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_setOption:function(t,n){t==="disabled"?(this.options[t]=n,this.widget().toggleClass("ui-sortable-disabled",!!n)):e.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(t,n){var r=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type=="static")return!1;this._refreshItems(t);var i=null,s=e(t.target).parents().each(function(){if(e.data(this,r.widgetName+"-item")==r)return i=e(this),!1});e.data(t.target,r.widgetName+"-item")==r&amp;&amp;(i=e(t.target));if(!i)return!1;if(this.options.handle&amp;&amp;!n){var o=!1;e(this.options.handle,i).find("*").andSelf().each(function(){this==t.target&amp;&amp;(o=!0)});if(!o)return!1}return this.currentItem=i,this._removeCurrentsFromItems(),!0},_mouseStart:function(t,n,r){var i=this.options;this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(t),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},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,i.cursorAt&amp;&amp;this._adjustOffsetFromHelper(i.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&amp;&amp;this.currentItem.hide(),this._createPlaceholder(),i.containment&amp;&amp;this._setContainment(),i.cursor&amp;&amp;(e("body").css("cursor")&amp;&amp;(this._storedCursor=e("body").css("cursor")),e("body").css("cursor",i.cursor)),i.opacity&amp;&amp;(this.helper.css("opacity")&amp;&amp;(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",i.opacity)),i.zIndex&amp;&amp;(this.helper.css("zIndex")&amp;&amp;(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",i.zIndex)),this.scrollParent[0]!=document&amp;&amp;this.scrollParent[0].tagName!="HTML"&amp;&amp;(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions();if(!r)for(var s=this.containers.length-1;s&gt;=0;s--)this.containers[s]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&amp;&amp;(e.ui.ddmanager.current=this),e.ui.ddmanager&amp;&amp;!i.dropBehaviour&amp;&amp;e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){var n=this.options,r=!1;this.scrollParent[0]!=document&amp;&amp;this.scrollParent[0].tagName!="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY&lt;n.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+n.scrollSpeed:t.pageY-this.overflowOffset.top&lt;n.scrollSensitivity&amp;&amp;(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-n.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX&lt;n.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+n.scrollSpeed:t.pageX-this.overflowOffset.left&lt;n.scrollSensitivity&amp;&amp;(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-n.scrollSpeed)):(t.pageY-e(document).scrollTop()&lt;n.scrollSensitivity?r=e(document).scrollTop(e(document).scrollTop()-n.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())&lt;n.scrollSensitivity&amp;&amp;(r=e(document).scrollTop(e(document).scrollTop()+n.scrollSpeed)),t.pageX-e(document).scrollLeft()&lt;n.scrollSensitivity?r=e(document).scrollLeft(e(document).scrollLeft()-n.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())&lt;n.scrollSensitivity&amp;&amp;(r=e(document).scrollLeft(e(document).scrollLeft()+n.scrollSpeed))),r!==!1&amp;&amp;e.ui.ddmanager&amp;&amp;!n.dropBehaviour&amp;&amp;e.ui.ddmanager.prepareOffsets(this,t)}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(var i=this.items.length-1;i&gt;=0;i--){var s=this.items[i],o=s.item[0],u=this._intersectsWithPointer(s);if(!u)continue;if(s.instance!==this.currentContainer)continue;if(o!=this.currentItem[0]&amp;&amp;this.placeholder[u==1?"next":"prev"]()[0]!=o&amp;&amp;!e.contains(this.placeholder[0],o)&amp;&amp;(this.options.type=="semi-dynamic"?!e.contains(this.element[0],o):!0)){this.direction=u==1?"down":"up";if(this.options.tolerance!="pointer"&amp;&amp;!this._intersectsWithSides(s))break;this._rearrange(t,s),this._trigger("change",t,this._uiHash());break}}return this._contactContainers(t),e.ui.ddmanager&amp;&amp;e.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,n){if(!t)return;e.ui.ddmanager&amp;&amp;!this.options.dropBehaviour&amp;&amp;e.ui.ddmanager.drop(this,t);if(this.options.revert){var r=this,i=this.placeholder.offset();this.reverting=!0,e(this.helper).animate({left:i.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:i.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){r._clear(t)})}else this._clear(t,n);return!1},cancel:function(){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 t=this.containers.length-1;t&gt;=0;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&amp;&amp;(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&amp;&amp;(this.placeholder[0].parentNode&amp;&amp;this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!="original"&amp;&amp;this.helper&amp;&amp;this.helper[0].parentNode&amp;&amp;this.helper.remove(),e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(t){var n=this._getItemsAsjQuery(t&amp;&amp;t.connected),r=[];return t=t||{},e(n).each(function(){var n=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[-=_](.+)/);n&amp;&amp;r.push((t.key||n[1]+"[]")+"="+(t.key&amp;&amp;t.expression?n[1]:n[2]))}),!r.length&amp;&amp;t.key&amp;&amp;r.push(t.key+"="),r.join("&amp;")},toArray:function(t){var n=this._getItemsAsjQuery(t&amp;&amp;t.connected),r=[];return t=t||{},n.each(function(){r.push(e(t.item||this).attr(t.attribute||"id")||"")}),r},_intersectsWith:function(e){var t=this.positionAbs.left,n=t+this.helperProportions.width,r=this.positionAbs.top,i=r+this.helperProportions.height,s=e.left,o=s+e.width,u=e.top,a=u+e.height,f=this.offset.click.top,l=this.offset.click.left,c=r+f&gt;u&amp;&amp;r+f&lt;a&amp;&amp;t+l&gt;s&amp;&amp;t+l&lt;o;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&amp;&amp;this.helperProportions[this.floating?"width":"height"]&gt;e[this.floating?"width":"height"]?c:s&lt;t+this.helperProportions.width/2&amp;&amp;n-this.helperProportions.width/2&lt;o&amp;&amp;u&lt;r+this.helperProportions.height/2&amp;&amp;i-this.helperProportions.height/2&lt;a},_intersectsWithPointer:function(t){var n=this.options.axis==="x"||e.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),r=this.options.axis==="y"||e.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width),i=n&amp;&amp;r,s=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return i?this.floating?o&amp;&amp;o=="right"||s=="down"?2:1:s&amp;&amp;(s=="down"?2:1):!1},_intersectsWithSides:function(t){var n=e.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),r=e.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),i=this._getDragVerticalDirection(),s=this._getDragHorizontalDirection();return this.floating&amp;&amp;s?s=="right"&amp;&amp;r||s=="left"&amp;&amp;!r:i&amp;&amp;(i=="down"&amp;&amp;n||i=="up"&amp;&amp;!n)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return e!=0&amp;&amp;(e&gt;0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return e!=0&amp;&amp;(e&gt;0?"right":"left")},refresh:function(e){return this._refreshItems(e),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor==String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){var n=[],r=[],i=this._connectWith();if(i&amp;&amp;t)for(var s=i.length-1;s&gt;=0;s--){var o=e(i[s]);for(var u=o.length-1;u&gt;=0;u--){var a=e.data(o[u],this.widgetName);a&amp;&amp;a!=this&amp;&amp;!a.options.disabled&amp;&amp;r.push([e.isFunction(a.options.items)?a.options.items.call(a.element):e(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a])}}r.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var s=r.length-1;s&gt;=0;s--)r[s][0].each(function(){n.push(this)});return e(n)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");for(var t=0;t&lt;this.items.length;t++)for(var n=0;n&lt;e.length;n++)e[n]==this.items[t].item[0]&amp;&amp;this.items.splice(t,1)},_refreshItems:function(t){this.items=[],this.containers=[this];var n=this.items,r=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],i=this._connectWith();if(i&amp;&amp;this.ready)for(var s=i.length-1;s&gt;=0;s--){var o=e(i[s]);for(var u=o.length-1;u&gt;=0;u--){var a=e.data(o[u],this.widgetName);a&amp;&amp;a!=this&amp;&amp;!a.options.disabled&amp;&amp;(r.push([e.isFunction(a.options.items)?a.options.items.call(a.element[0],t,{item:this.currentItem}):e(a.options.items,a.element),a]),this.containers.push(a))}}for(var s=r.length-1;s&gt;=0;s--){var f=r[s][1],l=r[s][0];for(var u=0,c=l.length;u&lt;c;u++){var h=e(l[u]);h.data(this.widgetName+"-item",f),n.push({item:h,instance:f,width:0,height:0,left:0,top:0})}}},refreshPositions:function(t){this.offsetParent&amp;&amp;this.helper&amp;&amp;(this.offset.parent=this._getParentOffset());for(var n=this.items.length-1;n&gt;=0;n--){var r=this.items[n];if(r.instance!=this.currentContainer&amp;&amp;this.currentContainer&amp;&amp;r.item[0]!=this.currentItem[0])continue;var i=this.options.toleranceElement?e(this.options.toleranceElement,r.item):r.item;t||(r.width=i.outerWidth(),r.height=i.outerHeight());var s=i.offset();r.left=s.left,r.top=s.top}if(this.options.custom&amp;&amp;this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var n=this.containers.length-1;n&gt;=0;n--){var s=this.containers[n].element.offset();this.containers[n].containerCache.left=s.left,this.containers[n].containerCache.top=s.top,this.containers[n].containerCache.width=this.containers[n].element.outerWidth(),this.containers[n].containerCache.height=this.containers[n].element.outerHeight()}return this},_createPlaceholder:function(t){t=t||this;var n=t.options;if(!n.placeholder||n.placeholder.constructor==String){var r=n.placeholder;n.placeholder={element:function(){var n=e(document.createElement(t.currentItem[0].nodeName)).addClass(r||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return r||(n.style.visibility="hidden"),n},update:function(e,i){if(r&amp;&amp;!n.forcePlaceholderSize)return;i.height()||i.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),i.width()||i.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10))}}}t.placeholder=e(n.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),n.placeholder.update(t,t.placeholder)},_contactContainers:function(t){var n=null,r=null;for(var i=this.containers.length-1;i&gt;=0;i--){if(e.contains(this.currentItem[0],this.containers[i].element[0]))continue;if(this._intersectsWith(this.containers[i].containerCache)){if(n&amp;&amp;e.contains(this.containers[i].element[0],n.element[0]))continue;n=this.containers[i],r=i}else this.containers[i].containerCache.over&amp;&amp;(this.containers[i]._trigger("out",t,this._uiHash(this)),this.containers[i].containerCache.over=0)}if(!n)return;if(this.containers.length===1)this.containers[r]._trigger("over",t,this._uiHash(this)),this.containers[r].containerCache.over=1;else if(this.currentContainer!=this.containers[r]){var s=1e4,o=null,u=this.positionAbs[this.containers[r].floating?"left":"top"];for(var a=this.items.length-1;a&gt;=0;a--){if(!e.contains(this.containers[r].element[0],this.items[a].item[0]))continue;var f=this.containers[r].floating?this.items[a].item.offset().left:this.items[a].item.offset().top;Math.abs(f-u)&lt;s&amp;&amp;(s=Math.abs(f-u),o=this.items[a],this.direction=f-u&gt;0?"down":"up")}if(!o&amp;&amp;!this.options.dropOnEmpty)return;this.currentContainer=this.containers[r],o?this._rearrange(t,o,null,!0):this._rearrange(t,null,this.containers[r].element,!0),this._trigger("change",t,this._uiHash()),this.containers[r]._trigger("change",t,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[r]._trigger("over",t,this._uiHash(this)),this.containers[r].containerCache.over=1}},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t,this.currentItem])):n.helper=="clone"?this.currentItem.clone():this.currentItem;return r.parents("body").length||e(n.appendTo!="parent"?n.appendTo:this.currentItem[0].parentNode)[0].appendChild(r[0]),r[0]==this.currentItem[0]&amp;&amp;(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")}),(r[0].style.width==""||n.forceHelperSize)&amp;&amp;r.width(this.currentItem.width()),(r[0].style.height==""||n.forceHelperSize)&amp;&amp;r.height(this.currentItem.height()),r},_adjustOffsetFromHelper:function(t){typeof t=="string"&amp;&amp;(t=t.split(" ")),e.isArray(t)&amp;&amp;(t={left:+t[0],top:+t[1]||0}),"left"in t&amp;&amp;(this.offset.click.left=t.left+this.margins.left),"right"in t&amp;&amp;(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&amp;&amp;(this.offset.click.top=t.top+this.margins.top),"bottom"in t&amp;&amp;(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();this.cssPosition=="absolute"&amp;&amp;this.scrollParent[0]!=document&amp;&amp;e.contains(this.scrollParent[0],this.offsetParent[0])&amp;&amp;(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&amp;&amp;this.offsetParent[0].tagName.toLowerCase()=="html"&amp;&amp;e.browser.msie)t={top:0,left:0};return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var e=this.currentItem.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t=this.options;t.containment=="parent"&amp;&amp;(t.containment=this.helper[0].parentNode);if(t.containment=="document"||t.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e(t.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(e(t.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(t.containment)){var n=e(t.containment)[0],r=e(t.containment).offset(),i=e(n).css("overflow")!="hidden";this.containment=[r.left+(parseInt(e(n).css("borderLeftWidth"),10)||0)+(parseInt(e(n).css("paddingLeft"),10)||0)-this.margins.left,r.top+(parseInt(e(n).css("borderTopWidth"),10)||0)+(parseInt(e(n).css("paddingTop"),10)||0)-this.margins.top,r.left+(i?Math.max(n.scrollWidth,n.offsetWidth):n.offsetWidth)-(parseInt(e(n).css("borderLeftWidth"),10)||0)-(parseInt(e(n).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,r.top+(i?Math.max(n.scrollHeight,n.offsetHeight):n.offsetHeight)-(parseInt(e(n).css("borderTopWidth"),10)||0)-(parseInt(e(n).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(t,n){n||(n=this.position);var r=t=="absolute"?1:-1,i=this.options,s=this.cssPosition!="absolute"||this.scrollParent[0]!=document&amp;&amp;!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(s[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():o?0:s.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():o?0:s.scrollLeft())*r}},_generatePosition:function(t){var n=this.options,r=this.cssPosition!="absolute"||this.scrollParent[0]!=document&amp;&amp;!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,i=/(html|body)/i.test(r[0].tagName);this.cssPosition=="relative"&amp;&amp;(this.scrollParent[0]==document||this.scrollParent[0]==this.offsetParent[0])&amp;&amp;(this.offset.relative=this._getRelativeOffset());var s=t.pageX,o=t.pageY;if(this.originalPosition){this.containment&amp;&amp;(t.pageX-this.offset.click.left&lt;this.containment[0]&amp;&amp;(s=this.containment[0]+this.offset.click.left),t.pageY-this.offset.click.top&lt;this.containment[1]&amp;&amp;(o=this.containment[1]+this.offset.click.top),t.pageX-this.offset.click.left&gt;this.containment[2]&amp;&amp;(s=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top&gt;this.containment[3]&amp;&amp;(o=this.containment[3]+this.offset.click.top));if(n.grid){var u=this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1];o=this.containment?u-this.offset.click.top&lt;this.containment[1]||u-this.offset.click.top&gt;this.containment[3]?u-this.offset.click.top&lt;this.containment[1]?u+n.grid[1]:u-n.grid[1]:u:u;var a=this.originalPageX+Math.round((s-this.originalPageX)/n.grid[0])*n.grid[0];s=this.containment?a-this.offset.click.left&lt;this.containment[0]||a-this.offset.click.left&gt;this.containment[2]?a-this.offset.click.left&lt;this.containment[0]?a+n.grid[0]:a-n.grid[0]:a:a}}return{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():i?0:r.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:r.scrollLeft())}},_rearrange:function(e,t,n,r){n?n[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var i=this.counter;this._delay(function(){i==this.counter&amp;&amp;this.refreshPositions(!r)})},_clear:function(t,n){this.reverting=!1;var r=[];!this._noFinalSort&amp;&amp;this.currentItem.parent().length&amp;&amp;this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var i in this._storedCSS)if(this._storedCSS[i]=="auto"||this._storedCSS[i]=="static")this._storedCSS[i]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&amp;&amp;!n&amp;&amp;r.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))}),(this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&amp;&amp;!n&amp;&amp;r.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&amp;&amp;(n||(r.push(function(e){this._trigger("remove",e,this._uiHash())}),r.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),r.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer))));for(var i=this.containers.length-1;i&gt;=0;i--)n||r.push(function(e){return function(t){e._trigger("deactivate",t,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over&amp;&amp;(r.push(function(e){return function(t){e._trigger("out",t,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over=0);this._storedCursor&amp;&amp;e("body").css("cursor",this._storedCursor),this._storedOpacity&amp;&amp;this.helper.css("opacity",this._storedOpacity),this._storedZIndex&amp;&amp;this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex),this.dragging=!1;if(this.cancelHelperRemoval){if(!n){this._trigger("beforeStop",t,this._uiHash());for(var i=0;i&lt;r.length;i++)r[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!1}n||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!=this.currentItem[0]&amp;&amp;this.helper.remove(),this.helper=null;if(!n){for(var i=0;i&lt;r.length;i++)r[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&amp;&amp;this.cancel()},_uiHash:function(t){var n=t||this;return{helper:n.helper,placeholder:n.placeholder||e([]),position:n.position,originalPosition:n.originalPosition,offset:n.positionAbs,item:n.currentItem,sender:t?t.element:null}}})})(jQuery);(function(e,t){var n=0,r={},i={};r.height=r.paddingTop=r.paddingBottom=r.borderTopWidth=r.borderBottomWidth="hide",i.height=i.paddingTop=i.paddingBottom=i.borderTopWidth=i.borderBottomWidth="show",e.widget("ui.accordion",{version:"1.9.0",options:{active:0,animate:{},collapsible:!1,event:"click",header:"&gt; li &gt; :first-child,&gt; :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},_create:function(){var t=this.accordionId="ui-accordion-"+(this.element.attr("id")||++n),r=this.options;this.prevShow=this.prevHide=e(),this.element.addClass("ui-accordion ui-widget ui-helper-reset"),this.headers=this.element.find(r.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all"),this._hoverable(this.headers),this._focusable(this.headers),this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").hide(),!r.collapsible&amp;&amp;r.active===!1&amp;&amp;(r.active=0),r.active&lt;0&amp;&amp;(r.active+=this.headers.length),this.active=this._findActive(r.active).addClass("ui-accordion-header-active ui-state-active").toggleClass("ui-corner-all ui-corner-top"),this.active.next().addClass("ui-accordion-content-active").show(),this._createIcons(),this.originalHeight=this.element[0].style.height,this.refresh(),this.element.attr("role","tablist"),this.headers.attr("role","tab").each(function(n){var r=e(this),i=r.attr("id"),s=r.next(),o=s.attr("id");i||(i=t+"-header-"+n,r.attr("id",i)),o||(o=t+"-panel-"+n,s.attr("id",o)),r.attr("aria-controls",o),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false",tabIndex:-1}).next().attr({"aria-expanded":"false","aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true",tabIndex:0}).next().attr({"aria-expanded":"true","aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._on(this.headers,{keydown:"_keydown"}),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._setupEvents(r.event)},_getCreateEventData:function(){return{header:this.active,content:this.active.length?this.active.next():e()}},_createIcons:function(){var t=this.options.icons;t&amp;&amp;(e("&lt;span&gt;").addClass("ui-accordion-header-icon ui-icon "+t.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(t.header).addClass(t.activeHeader),this.headers.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var e;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.removeClass("ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-selected").removeAttr("aria-controls").removeAttr("tabIndex").each(function(){/^ui-accordion/.test(this.id)&amp;&amp;this.removeAttribute("id")}),this._destroyIcons(),e=this.headers.next().css("display","").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-labelledby").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled").each(function(){/^ui-accordion/.test(this.id)&amp;&amp;this.removeAttribute("id")}),this.options.heightStyle!=="content"&amp;&amp;(this.element.css("height",this.originalHeight),e.css("height",""))},_setOption:function(e,t){if(e==="active"){this._activate(t);return}e==="event"&amp;&amp;(this.options.event&amp;&amp;this._off(this.headers,this.options.event),this._setupEvents(t)),this._super(e,t),e==="collapsible"&amp;&amp;!t&amp;&amp;this.options.active===!1&amp;&amp;this._activate(0),e==="icons"&amp;&amp;(this._destroyIcons(),t&amp;&amp;this._createIcons()),e==="disabled"&amp;&amp;this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!t)},_keydown:function(t){if(t.altKey||t.ctrlKey)return;var n=e.ui.keyCode,r=this.headers.length,i=this.headers.index(t.target),s=!1;switch(t.keyCode){case n.RIGHT:case n.DOWN:s=this.headers[(i+1)%r];break;case n.LEFT:case n.UP:s=this.headers[(i-1+r)%r];break;case n.SPACE:case n.ENTER:this._eventHandler(t);break;case n.HOME:s=this.headers[0];break;case n.END:s=this.headers[r-1]}s&amp;&amp;(e(t.target).attr("tabIndex",-1),e(s).attr("tabIndex",0),s.focus(),t.preventDefault())},_panelKeyDown:function(t){t.keyCode===e.ui.keyCode.UP&amp;&amp;t.ctrlKey&amp;&amp;e(t.currentTarget).prev().focus()},refresh:function(){var t,n,r=this.options.heightStyle,i=this.element.parent();this.element.css("height",this.originalHeight),r==="fill"?(e.support.minHeight||(n=i.css("overflow"),i.css("overflow","hidden")),t=i.height(),this.element.siblings(":visible").each(function(){var n=e(this),r=n.css("position");if(r==="absolute"||r==="fixed")return;t-=n.outerHeight(!0)}),n&amp;&amp;i.css("overflow",n),this.headers.each(function(){t-=e(this).outerHeight(!0)}),this.headers.next().each(function(){e(this).height(Math.max(0,t-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):r==="auto"&amp;&amp;(t=0,this.headers.next().each(function(){t=Math.max(t,e(this).height("").height())}).height(t)),r!=="content"&amp;&amp;this.element.height(this.element.height())},_activate:function(t){var n=this._findActive(t)[0];if(n===this.active[0])return;n=n||this.active[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop})},_findActive:function(t){return typeof t=="number"?this.headers.eq(t):e()},_setupEvents:function(t){var n={};if(!t)return;e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._on(this.headers,n)},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i[0]===r[0],o=s&amp;&amp;n.collapsible,u=o?e():i.next(),a=r.next(),f={oldHeader:r,oldPanel:a,newHeader:o?e():i,newPanel:u};t.preventDefault();if(s&amp;&amp;!n.collapsible||this._trigger("beforeActivate",t,f)===!1)return;n.active=o?!1:this.headers.index(i),this.active=s?e():i,this._toggle(f),r.removeClass("ui-accordion-header-active ui-state-active"),n.icons&amp;&amp;r.children(".ui-accordion-header-icon").removeClass(n.icons.activeHeader).addClass(n.icons.header),s||(i.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),n.icons&amp;&amp;i.children(".ui-accordion-header-icon").removeClass(n.icons.header).addClass(n.icons.activeHeader),i.next().addClass("ui-accordion-content-active"))},_toggle:function(t){var n=t.newPanel,r=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=n,this.prevHide=r,this.options.animate?this._animate(n,r,t):(r.hide(),n.show(),this._toggleComplete(t)),r.attr({"aria-expanded":"false","aria-hidden":"true"}),r.prev().attr("aria-selected","false"),n.length&amp;&amp;r.length?r.prev().attr("tabIndex",-1):n.length&amp;&amp;this.headers.filter(function(){return e(this).attr("tabIndex")===0}).attr("tabIndex",-1),n.attr({"aria-expanded":"true","aria-hidden":"false"}).prev().attr({"aria-selected":"true",tabIndex:0})},_animate:function(e,t,n){var s,o,u,a=this,f=0,l=e.length&amp;&amp;(!t.length||e.index()&lt;t.index()),c=this.options.animate||{},h=l&amp;&amp;c.down||c,p=function(){a._toggleComplete(n)};typeof h=="number"&amp;&amp;(u=h),typeof h=="string"&amp;&amp;(o=h),o=o||h.easing||c.easing,u=u||h.duration||c.duration;if(!t.length)return e.animate(i,u,o,p);if(!e.length)return t.animate(r,u,o,p);s=e.show().outerHeight(),t.animate(r,{duration:u,easing:o,step:function(e,t){t.now=Math.round(e)}}),e.hide().animate(i,{duration:u,easing:o,complete:p,step:function(e,n){n.now=Math.round(e),n.prop!=="height"?f+=n.now:a.options.heightStyle!=="content"&amp;&amp;(n.now=Math.round(s-t.outerHeight()-f),f=0)}})},_toggleComplete:function(e){var t=e.oldPanel;t.removeClass("ui-accordion-content-active").prev().removeClass("ui-corner-top").addClass("ui-corner-all"),t.length&amp;&amp;(t.parent()[0].className=t.parent()[0].className),this._trigger("activate",null,e)}}),e.uiBackCompat!==!1&amp;&amp;(function(e,t){e.extend(t.options,{navigation:!1,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}});var n=t._create;t._create=function(){if(this.options.navigation){var t=this,r=this.element.find(this.options.header),i=r.next(),s=r.add(i).find("a").filter(this.options.navigationFilter)[0];s&amp;&amp;r.add(i).each(function(n){if(e.contains(this,s))return t.options.active=Math.floor(n/2),!1})}n.call(this)}}(jQuery,jQuery.ui.accordion.prototype),function(e,t){e.extend(t.options,{heightStyle:null,autoHeight:!0,clearStyle:!1,fillSpace:!1});var n=t._create,r=t._setOption;e.extend(t,{_create:function(){this.options.heightStyle=this.options.heightStyle||this._mergeHeightStyle(),n.call(this)},_setOption:function(e,t){if(e==="autoHeight"||e==="clearStyle"||e==="fillSpace")this.options.heightStyle=this._mergeHeightStyle();r.apply(this,arguments)},_mergeHeightStyle:function(){var e=this.options;if(e.fillSpace)return"fill";if(e.clearStyle)return"content";if(e.autoHeight)return"auto"}})}(jQuery,jQuery.ui.accordion.prototype),function(e,t){e.extend(t.options.icons,{activeHeader:null,headerSelected:"ui-icon-triangle-1-s"});var n=t._createIcons;t._createIcons=function(){this.options.icons&amp;&amp;(this.options.icons.activeHeader=this.options.icons.activeHeader||this.options.icons.headerSelected),n.call(this)}}(jQuery,jQuery.ui.accordion.prototype),function(e,t){t.activate=t._activate;var n=t._findActive;t._findActive=function(e){return e===-1&amp;&amp;(e=!1),e&amp;&amp;typeof e!="number"&amp;&amp;(e=this.headers.index(this.headers.filter(e)),e===-1&amp;&amp;(e=!1)),n.call(this,e)}}(jQuery,jQuery.ui.accordion.prototype),jQuery.ui.accordion.prototype.resize=jQuery.ui.accordion.prototype.refresh,function(e,t){e.extend(t.options,{change:null,changestart:null});var n=t._trigger;t._trigger=function(e,t,r){var i=n.apply(this,arguments);return i?(e==="beforeActivate"?i=n.call(this,"changestart",t,{oldHeader:r.oldHeader,oldContent:r.oldPanel,newHeader:r.newHeader,newContent:r.newPanel}):e==="activate"&amp;&amp;(i=n.call(this,"change",t,{oldHeader:r.oldHeader,oldContent:r.oldPanel,newHeader:r.newHeader,newContent:r.newPanel})),i):!1}}(jQuery,jQuery.ui.accordion.prototype),function(e,t){e.extend(t.options,{animate:null,animated:"slide"});var n=t._create;t._create=function(){var e=this.options;e.animate===null&amp;&amp;(e.animated?e.animated==="slide"?e.animate=300:e.animated==="bounceslide"?e.animate={duration:200,down:{easing:"easeOutBounce",duration:1e3}}:e.animate=e.animated:e.animate=!1),n.call(this)}}(jQuery,jQuery.ui.accordion.prototype))})(jQuery);(function(e,t){var n=0;e.widget("ui.autocomplete",{version:"1.9.0",defaultElement:"&lt;input&gt;",options:{appendTo:"body",autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},pending:0,_create:function(){var t,n,r;this.isMultiLine=this._isMultiLine(),this.valueMethod=this.element[this.element.is("input,textarea")?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on({keydown:function(i){if(this.element.prop("readOnly")){t=!0,r=!0,n=!0;return}t=!1,r=!1,n=!1;var s=e.ui.keyCode;switch(i.keyCode){case s.PAGE_UP:t=!0,this._move("previousPage",i);break;case s.PAGE_DOWN:t=!0,this._move("nextPage",i);break;case s.UP:t=!0,this._keyEvent("previous",i);break;case s.DOWN:t=!0,this._keyEvent("next",i);break;case s.ENTER:case s.NUMPAD_ENTER:this.menu.active&amp;&amp;(t=!0,i.preventDefault(),this.menu.select(i));break;case s.TAB:this.menu.active&amp;&amp;this.menu.select(i);break;case s.ESCAPE:this.menu.element.is(":visible")&amp;&amp;(this._value(this.term),this.close(i),i.preventDefault());break;default:n=!0,this._searchTimeout(i)}},keypress:function(r){if(t){t=!1,r.preventDefault();return}if(n)return;var i=e.ui.keyCode;switch(r.keyCode){case i.PAGE_UP:this._move("previousPage",r);break;case i.PAGE_DOWN:this._move("nextPage",r);break;case i.UP:this._keyEvent("previous",r);break;case i.DOWN:this._keyEvent("next",r)}},input:function(e){if(r){r=!1,e.preventDefault();return}this._searchTimeout(e)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){if(this.cancelBlur){delete this.cancelBlur;return}clearTimeout(this.searching),this.close(e),this._change(e)}}),this._initSource(),this.menu=e("&lt;ul&gt;").addClass("ui-autocomplete").appendTo(this.document.find(this.options.appendTo||"body")[0]).menu({input:e(),role:null}).zIndex(this.element.zIndex()+1).hide().data("menu"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var n=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(r){r.target!==t.element[0]&amp;&amp;r.target!==n&amp;&amp;!e.contains(n,r.target)&amp;&amp;t.close()})})},menufocus:function(t,n){if(this.isNewMenu){this.isNewMenu=!1;if(t.originalEvent&amp;&amp;/^mouse/.test(t.originalEvent.type)){this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)});return}}var r=n.item.data("ui-autocomplete-item")||n.item.data("item.autocomplete");!1!==this._trigger("focus",t,{item:r})?t.originalEvent&amp;&amp;/^key/.test(t.originalEvent.type)&amp;&amp;this._value(r.value):this.liveRegion.text(r.value)},menuselect:function(e,t){var n=t.item.data("ui-autocomplete-item")||t.item.data("item.autocomplete"),r=this.previous;this.element[0]!==this.document[0].activeElement&amp;&amp;(this.element.focus(),this.previous=r,this._delay(function(){this.previous=r,this.selectedItem=n})),!1!==this._trigger("select",e,{item:n})&amp;&amp;this._value(n.value),this.term=this._value(),this.close(e),this.selectedItem=n}}),this.liveRegion=e("&lt;span&gt;",{role:"status","aria-live":"polite"}).addClass("ui-helper-hidden-accessible").insertAfter(this.element),e.fn.bgiframe&amp;&amp;this.menu.element.bgiframe(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),e==="source"&amp;&amp;this._initSource(),e==="appendTo"&amp;&amp;this.menu.element.appendTo(this.document.find(t||"body")[0]),e==="disabled"&amp;&amp;t&amp;&amp;this.xhr&amp;&amp;this.xhr.abort()},_isMultiLine:function(){return this.element.is("textarea")?!0:this.element.is("input")?!1:this.element.prop("isContentEditable")},_initSource:function(){var t,n,r=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(n,r){r(e.ui.autocomplete.filter(t,n.term))}):typeof this.options.source=="string"?(n=this.options.source,this.source=function(t,i){r.xhr&amp;&amp;r.xhr.abort(),r.xhr=e.ajax({url:n,data:t,dataType:"json",success:function(e,t){i(e)},error:function(){i([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){this.term!==this._value()&amp;&amp;(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){e=e!=null?e:this._value(),this.term=this._value();if(e.length&lt;this.options.minLength)return this.close(t);if(this._trigger("search",t)===!1)return;return this._search(e)},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var e=this,t=++n;return function(r){t===n&amp;&amp;e.__response(r),e.pending--,e.pending||e.element.removeClass("ui-autocomplete-loading")}},__response:function(e){e&amp;&amp;(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&amp;&amp;e&amp;&amp;e.length&amp;&amp;!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&amp;&amp;(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&amp;&amp;this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&amp;&amp;t[0].label&amp;&amp;t[0].value?t:e.map(t,function(t){return typeof t=="string"?{label:t,value:t}:e.extend({label:t.label||t.value,value:t.value||t.label},t)})},_suggest:function(t){var n=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(n,t),this.menu.refresh(),n.show(),this._resizeMenu(),n.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&amp;&amp;this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,n){var r=this;e.each(n,function(e,n){r._renderItemData(t,n)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,n){return e("&lt;li&gt;").append(e("&lt;a&gt;").text(n.label)).appendTo(t)},_move:function(e,t){if(!this.menu.element.is(":visible")){this.search(null,t);return}if(this.menu.isFirstItem()&amp;&amp;/^previous/.test(e)||this.menu.isLastItem()&amp;&amp;/^next/.test(e)){this._value(this.term),this.menu.blur();return}this.menu[e](t)},widget:function(){return this.menu.element},_value:function(e){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){if(!this.isMultiLine||this.menu.element.is(":visible"))this._move(e,t),t.preventDefault()}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&amp;")},filter:function(t,n){var r=new RegExp(e.ui.autocomplete.escapeRegex(n),"i");return e.grep(t,function(e){return r.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e&gt;1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var t;this._superApply(arguments);if(this.options.disabled||this.cancelSearch)return;e&amp;&amp;e.length?t=this.options.messages.results(e.length):t=this.options.messages.noResults,this.liveRegion.text(t)}})})(jQuery);(function(e,t){var n,r,i,s,o="ui-button ui-widget ui-state-default ui-corner-all",u="ui-state-hover ui-state-active ",a="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",f=function(){var t=e(this).find(":ui-button");setTimeout(function(){t.button("refresh")},1)},l=function(t){var n=t.name,r=t.form,i=e([]);return n&amp;&amp;(r?i=e(r).find("[name='"+n+"']"):i=e("[name='"+n+"']",t.ownerDocument).filter(function(){return!this.form})),i};e.widget("ui.button",{version:"1.9.0",defaultElement:"&lt;button&gt;",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,f),typeof this.options.disabled!="boolean"?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var t=this,u=this.options,a=this.type==="checkbox"||this.type==="radio",c="ui-state-hover"+(a?"":" ui-state-active"),h="ui-state-focus";u.label===null&amp;&amp;(u.label=this.type==="input"?this.buttonElement.val():this.buttonElement.html()),this.buttonElement.addClass(o).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){if(u.disabled)return;e(this).addClass("ui-state-hover"),this===n&amp;&amp;e(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){if(u.disabled)return;e(this).removeClass(c)}).bind("click"+this.eventNamespace,function(e){u.disabled&amp;&amp;(e.preventDefault(),e.stopImmediatePropagation())}),this.element.bind("focus"+this.eventNamespace,function(){t.buttonElement.addClass(h)}).bind("blur"+this.eventNamespace,function(){t.buttonElement.removeClass(h)}),a&amp;&amp;(this.element.bind("change"+this.eventNamespace,function(){if(s)return;t.refresh()}),this.buttonElement.bind("mousedown"+this.eventNamespace,function(e){if(u.disabled)return;s=!1,r=e.pageX,i=e.pageY}).bind("mouseup"+this.eventNamespace,function(e){if(u.disabled)return;if(r!==e.pageX||i!==e.pageY)s=!0})),this.type==="checkbox"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(u.disabled||s)return!1;e(this).toggleClass("ui-state-active"),t.buttonElement.attr("aria-pressed",t.element[0].checked)}):this.type==="radio"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(u.disabled||s)return!1;e(this).addClass("ui-state-active"),t.buttonElement.attr("aria-pressed","true");var n=t.element[0];l(n).not(n).map(function(){return e(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){if(u.disabled)return!1;e(this).addClass("ui-state-active"),n=this,t.document.one("mouseup",function(){n=null})}).bind("mouseup"+this.eventNamespace,function(){if(u.disabled)return!1;e(this).removeClass("ui-state-active")}).bind("keydown"+this.eventNamespace,function(t){if(u.disabled)return!1;(t.keyCode===e.ui.keyCode.SPACE||t.keyCode===e.ui.keyCode.ENTER)&amp;&amp;e(this).addClass("ui-state-active")}).bind("keyup"+this.eventNamespace,function(){e(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&amp;&amp;this.buttonElement.keyup(function(t){t.keyCode===e.ui.keyCode.SPACE&amp;&amp;e(this).click()})),this._setOption("disabled",u.disabled),this._resetButton()},_determineButtonType:function(){var e,t,n;this.element.is("[type=checkbox]")?this.type="checkbox":this.element.is("[type=radio]")?this.type="radio":this.element.is("input")?this.type="input":this.type="button",this.type==="checkbox"||this.type==="radio"?(e=this.element.parents().last(),t="label[for='"+this.element.attr("id")+"']",this.buttonElement=e.find(t),this.buttonElement.length||(e=e.length?e.siblings():this.element.siblings(),this.buttonElement=e.filter(t),this.buttonElement.length||(this.buttonElement=e.find(t))),this.element.addClass("ui-helper-hidden-accessible"),n=this.element.is(":checked"),n&amp;&amp;this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",n)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(o+" "+u+" "+a).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(e,t){this._super(e,t);if(e==="disabled"){t?this.element.prop("disabled",!0):this.element.prop("disabled",!1);return}this._resetButton()},refresh:function(){var t=this.element.is(":disabled");t!==this.options.disabled&amp;&amp;this._setOption("disabled",t),this.type==="radio"?l(this.element[0]).each(function(){e(this).is(":checked")?e(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):e(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):this.type==="checkbox"&amp;&amp;(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(){if(this.type==="input"){this.options.label&amp;&amp;this.element.val(this.options.label);return}var t=this.buttonElement.removeClass(a),n=e("&lt;span&gt;&lt;/span&gt;",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(t.empty()).text(),r=this.options.icons,i=r.primary&amp;&amp;r.secondary,s=[];r.primary||r.secondary?(this.options.text&amp;&amp;s.push("ui-button-text-icon"+(i?"s":r.primary?"-primary":"-secondary")),r.primary&amp;&amp;t.prepend("&lt;span class='ui-button-icon-primary ui-icon "+r.primary+"'&gt;&lt;/span&gt;"),r.secondary&amp;&amp;t.append("&lt;span class='ui-button-icon-secondary ui-icon "+r.secondary+"'&gt;&lt;/span&gt;"),this.options.text||(s.push(i?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||t.attr("title",e.trim(n)))):s.push("ui-button-text-only"),t.addClass(s.join(" "))}}),e.widget("ui.buttonset",{version:"1.9.0",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(e,t){e==="disabled"&amp;&amp;this.buttons.button("option",e,t),this._super(e,t)},refresh:function(){var t=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(t?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(t?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}})})(jQuery);(function($,undefined){function Datepicker(){this.debug=!1,this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,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:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,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:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},$.extend(this._defaults,this.regional[""]),this.dpDiv=bindHover($('&lt;div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"&gt;&lt;/div&gt;'))}function bindHover(e){var t="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.delegate(t,"mouseout",function(){$(this).removeClass("ui-state-hover"),this.className.indexOf("ui-datepicker-prev")!=-1&amp;&amp;$(this).removeClass("ui-datepicker-prev-hover"),this.className.indexOf("ui-datepicker-next")!=-1&amp;&amp;$(this).removeClass("ui-datepicker-next-hover")}).delegate(t,"mouseover",function(){$.datepicker._isDisabledDatepicker(instActive.inline?e.parent()[0]:instActive.input[0])||($(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),$(this).addClass("ui-state-hover"),this.className.indexOf("ui-datepicker-prev")!=-1&amp;&amp;$(this).addClass("ui-datepicker-prev-hover"),this.className.indexOf("ui-datepicker-next")!=-1&amp;&amp;$(this).addClass("ui-datepicker-next-hover"))})}function extendRemove(e,t){$.extend(e,t);for(var n in t)if(t[n]==null||t[n]==undefined)e[n]=t[n];return e}$.extend($.ui,{datepicker:{version:"1.9.0"}});var PROP_NAME="datepicker",dpuuid=(new Date).getTime(),instActive;$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){this.debug&amp;&amp;console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(e){return extendRemove(this._defaults,e||{}),this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase(),inline=nodeName=="div"||nodeName=="span";target.id||(this.uuid+=1,target.id="dp"+this.uuid);var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{}),nodeName=="input"?this._connectDatepicker(target,inst):inline&amp;&amp;this._inlineDatepicker(target,inst)},_newInst:function(e,t){var n=e[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1");return{id:n,input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:t,dpDiv:t?bindHover($('&lt;div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"&gt;&lt;/div&gt;')):this.dpDiv}},_connectDatepicker:function(e,t){var n=$(e);t.append=$([]),t.trigger=$([]);if(n.hasClass(this.markerClassName))return;this._attachments(n,t),n.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(e,n,r){t.settings[n]=r}).bind("getData.datepicker",function(e,n){return this._get(t,n)}),this._autoSize(t),$.data(e,PROP_NAME,t),t.settings.disabled&amp;&amp;this._disableDatepicker(e)},_attachments:function(e,t){var n=this._get(t,"appendText"),r=this._get(t,"isRTL");t.append&amp;&amp;t.append.remove(),n&amp;&amp;(t.append=$('&lt;span class="'+this._appendClass+'"&gt;'+n+"&lt;/span&gt;"),e[r?"before":"after"](t.append)),e.unbind("focus",this._showDatepicker),t.trigger&amp;&amp;t.trigger.remove();var i=this._get(t,"showOn");(i=="focus"||i=="both")&amp;&amp;e.focus(this._showDatepicker);if(i=="button"||i=="both"){var s=this._get(t,"buttonText"),o=this._get(t,"buttonImage");t.trigger=$(this._get(t,"buttonImageOnly")?$("&lt;img/&gt;").addClass(this._triggerClass).attr({src:o,alt:s,title:s}):$('&lt;button type="button"&gt;&lt;/button&gt;').addClass(this._triggerClass).html(o==""?s:$("&lt;img/&gt;").attr({src:o,alt:s,title:s}))),e[r?"before":"after"](t.trigger),t.trigger.click(function(){return $.datepicker._datepickerShowing&amp;&amp;$.datepicker._lastInput==e[0]?$.datepicker._hideDatepicker():$.datepicker._datepickerShowing&amp;&amp;$.datepicker._lastInput!=e[0]?($.datepicker._hideDatepicker(),$.datepicker._showDatepicker(e[0])):$.datepicker._showDatepicker(e[0]),!1})}},_autoSize:function(e){if(this._get(e,"autoSize")&amp;&amp;!e.inline){var t=new Date(2009,11,20),n=this._get(e,"dateFormat");if(n.match(/[DM]/)){var r=function(e){var t=0,n=0;for(var r=0;r&lt;e.length;r++)e[r].length&gt;t&amp;&amp;(t=e[r].length,n=r);return n};t.setMonth(r(this._get(e,n.match(/MM/)?"monthNames":"monthNamesShort"))),t.setDate(r(this._get(e,n.match(/DD/)?"dayNames":"dayNamesShort"))+20-t.getDay())}e.input.attr("size",this._formatDate(e,t).length)}},_inlineDatepicker:function(e,t){var n=$(e);if(n.hasClass(this.markerClassName))return;n.addClass(this.markerClassName).append(t.dpDiv).bind("setData.datepicker",function(e,n,r){t.settings[n]=r}).bind("getData.datepicker",function(e,n){return this._get(t,n)}),$.data(e,PROP_NAME,t),this._setDate(t,this._getDefaultDate(t),!0),this._updateDatepicker(t),this._updateAlternate(t),t.settings.disabled&amp;&amp;this._disableDatepicker(e),t.dpDiv.css("display","block")},_dialogDatepicker:function(e,t,n,r,i){var s=this._dialogInst;if(!s){this.uuid+=1;var o="dp"+this.uuid;this._dialogInput=$('&lt;input type="text" id="'+o+'" style="position: absolute; top: -100px; width: 0px;"/&gt;'),this._dialogInput.keydown(this._doKeyDown),$("body").append(this._dialogInput),s=this._dialogInst=this._newInst(this._dialogInput,!1),s.settings={},$.data(this._dialogInput[0],PROP_NAME,s)}extendRemove(s.settings,r||{}),t=t&amp;&amp;t.constructor==Date?this._formatDate(s,t):t,this._dialogInput.val(t),this._pos=i?i.length?i:[i.pageX,i.pageY]:null;if(!this._pos){var u=document.documentElement.clientWidth,a=document.documentElement.clientHeight,f=document.documentElement.scrollLeft||document.body.scrollLeft,l=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[u/2-100+f,a/2-150+l]}return this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),s.settings.onSelect=n,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),$.blockUI&amp;&amp;$.blockUI(this.dpDiv),$.data(this._dialogInput[0],PROP_NAME,s),this},_destroyDatepicker:function(e){var t=$(e),n=$.data(e,PROP_NAME);if(!t.hasClass(this.markerClassName))return;var r=e.nodeName.toLowerCase();$.removeData(e,PROP_NAME),r=="input"?(n.append.remove(),n.trigger.remove(),t.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(r=="div"||r=="span")&amp;&amp;t.removeClass(this.markerClassName).empty()},_enableDatepicker:function(e){var t=$(e),n=$.data(e,PROP_NAME);if(!t.hasClass(this.markerClassName))return;var r=e.nodeName.toLowerCase();if(r=="input")e.disabled=!1,n.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(r=="div"||r=="span"){var i=t.children("."+this._inlineClass);i.children().removeClass("ui-state-disabled"),i.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)}this._disabledInputs=$.map(this._disabledInputs,function(t){return t==e?null:t})},_disableDatepicker:function(e){var t=$(e),n=$.data(e,PROP_NAME);if(!t.hasClass(this.markerClassName))return;var r=e.nodeName.toLowerCase();if(r=="input")e.disabled=!0,n.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(r=="div"||r=="span"){var i=t.children("."+this._inlineClass);i.children().addClass("ui-state-disabled"),i.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)}this._disabledInputs=$.map(this._disabledInputs,function(t){return t==e?null:t}),this._disabledInputs[this._disabledInputs.length]=e},_isDisabledDatepicker:function(e){if(!e)return!1;for(var t=0;t&lt;this._disabledInputs.length;t++)if(this._disabledInputs[t]==e)return!0;return!1},_getInst:function(e){try{return $.data(e,PROP_NAME)}catch(t){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(e,t,n){var r=this._getInst(e);if(arguments.length==2&amp;&amp;typeof t=="string")return t=="defaults"?$.extend({},$.datepicker._defaults):r?t=="all"?$.extend({},r.settings):this._get(r,t):null;var i=t||{};typeof t=="string"&amp;&amp;(i={},i[t]=n);if(r){this._curInst==r&amp;&amp;this._hideDatepicker();var s=this._getDateDatepicker(e,!0),o=this._getMinMaxDate(r,"min"),u=this._getMinMaxDate(r,"max");extendRemove(r.settings,i),o!==null&amp;&amp;i.dateFormat!==undefined&amp;&amp;i.minDate===undefined&amp;&amp;(r.settings.minDate=this._formatDate(r,o)),u!==null&amp;&amp;i.dateFormat!==undefined&amp;&amp;i.maxDate===undefined&amp;&amp;(r.settings.maxDate=this._formatDate(r,u)),this._attachments($(e),r),this._autoSize(r),this._setDate(r,s),this._updateAlternate(r),this._updateDatepicker(r)}},_changeDatepicker:function(e,t,n){this._optionDatepicker(e,t,n)},_refreshDatepicker:function(e){var t=this._getInst(e);t&amp;&amp;this._updateDatepicker(t)},_setDateDatepicker:function(e,t){var n=this._getInst(e);n&amp;&amp;(this._setDate(n,t),this._updateDatepicker(n),this._updateAlternate(n))},_getDateDatepicker:function(e,t){var n=this._getInst(e);return n&amp;&amp;!n.inline&amp;&amp;this._setDateFromField(n,t),n?this._getDate(n):null},_doKeyDown:function(e){var t=$.datepicker._getInst(e.target),n=!0,r=t.dpDiv.is(".ui-datepicker-rtl");t._keyEvent=!0;if($.datepicker._datepickerShowing)switch(e.keyCode){case 9:$.datepicker._hideDatepicker(),n=!1;break;case 13:var i=$("td."+$.datepicker._dayOverClass+":not(."+$.datepicker._currentClass+")",t.dpDiv);i[0]&amp;&amp;$.datepicker._selectDay(e.target,t.selectedMonth,t.selectedYear,i[0]);var s=$.datepicker._get(t,"onSelect");if(s){var o=$.datepicker._formatDate(t);s.apply(t.input?t.input[0]:null,[o,t])}else $.datepicker._hideDatepicker();return!1;case 27:$.datepicker._hideDatepicker();break;case 33:$.datepicker._adjustDate(e.target,e.ctrlKey?-$.datepicker._get(t,"stepBigMonths"):-$.datepicker._get(t,"stepMonths"),"M");break;case 34:$.datepicker._adjustDate(e.target,e.ctrlKey?+$.datepicker._get(t,"stepBigMonths"):+$.datepicker._get(t,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&amp;&amp;$.datepicker._clearDate(e.target),n=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&amp;&amp;$.datepicker._gotoToday(e.target),n=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&amp;&amp;$.datepicker._adjustDate(e.target,r?1:-1,"D"),n=e.ctrlKey||e.metaKey,e.originalEvent.altKey&amp;&amp;$.datepicker._adjustDate(e.target,e.ctrlKey?-$.datepicker._get(t,"stepBigMonths"):-$.datepicker._get(t,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&amp;&amp;$.datepicker._adjustDate(e.target,-7,"D"),n=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&amp;&amp;$.datepicker._adjustDate(e.target,r?-1:1,"D"),n=e.ctrlKey||e.metaKey,e.originalEvent.altKey&amp;&amp;$.datepicker._adjustDate(e.target,e.ctrlKey?+$.datepicker._get(t,"stepBigMonths"):+$.datepicker._get(t,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&amp;&amp;$.datepicker._adjustDate(e.target,7,"D"),n=e.ctrlKey||e.metaKey;break;default:n=!1}else e.keyCode==36&amp;&amp;e.ctrlKey?$.datepicker._showDatepicker(this):n=!1;n&amp;&amp;(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(e){var t=$.datepicker._getInst(e.target);if($.datepicker._get(t,"constrainInput")){var n=$.datepicker._possibleChars($.datepicker._get(t,"dateFormat")),r=String.fromCharCode(e.charCode==undefined?e.keyCode:e.charCode);return e.ctrlKey||e.metaKey||r&lt;" "||!n||n.indexOf(r)&gt;-1}},_doKeyUp:function(e){var t=$.datepicker._getInst(e.target);if(t.input.val()!=t.lastVal)try{var n=$.datepicker.parseDate($.datepicker._get(t,"dateFormat"),t.input?t.input.val():null,$.datepicker._getFormatConfig(t));n&amp;&amp;($.datepicker._setDateFromField(t),$.datepicker._updateAlternate(t),$.datepicker._updateDatepicker(t))}catch(r){$.datepicker.log(r)}return!0},_showDatepicker:function(e){e=e.target||e,e.nodeName.toLowerCase()!="input"&amp;&amp;(e=$("input",e.parentNode)[0]);if($.datepicker._isDisabledDatepicker(e)||$.datepicker._lastInput==e)return;var t=$.datepicker._getInst(e);$.datepicker._curInst&amp;&amp;$.datepicker._curInst!=t&amp;&amp;($.datepicker._curInst.dpDiv.stop(!0,!0),t&amp;&amp;$.datepicker._datepickerShowing&amp;&amp;$.datepicker._hideDatepicker($.datepicker._curInst.input[0]));var n=$.datepicker._get(t,"beforeShow"),r=n?n.apply(e,[e,t]):{};if(r===!1)return;extendRemove(t.settings,r),t.lastVal=null,$.datepicker._lastInput=e,$.datepicker._setDateFromField(t),$.datepicker._inDialog&amp;&amp;(e.value=""),$.datepicker._pos||($.datepicker._pos=$.datepicker._findPos(e),$.datepicker._pos[1]+=e.offsetHeight);var i=!1;$(e).parents().each(function(){return i|=$(this).css("position")=="fixed",!i});var s={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null,t.dpDiv.empty(),t.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),$.datepicker._updateDatepicker(t),s=$.datepicker._checkOffset(t,s,i),t.dpDiv.css({position:$.datepicker._inDialog&amp;&amp;$.blockUI?"static":i?"fixed":"absolute",display:"none",left:s.left+"px",top:s.top+"px"});if(!t.inline){var o=$.datepicker._get(t,"showAnim"),u=$.datepicker._get(t,"duration"),a=function(){var e=t.dpDiv.find("iframe.ui-datepicker-cover");if(!!e.length){var n=$.datepicker._getBorders(t.dpDiv);e.css({left:-n[0],top:-n[1],width:t.dpDiv.outerWidth(),height:t.dpDiv.outerHeight()})}};t.dpDiv.zIndex($(e).zIndex()+1),$.datepicker._datepickerShowing=!0,$.effects&amp;&amp;($.effects.effect[o]||$.effects[o])?t.dpDiv.show(o,$.datepicker._get(t,"showOptions"),u,a):t.dpDiv[o||"show"](o?u:null,a),(!o||!u)&amp;&amp;a(),t.input.is(":visible")&amp;&amp;!t.input.is(":disabled")&amp;&amp;t.input.focus(),$.datepicker._curInst=t}},_updateDatepicker:function(e){this.maxRows=4;var t=$.datepicker._getBorders(e.dpDiv);instActive=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var n=e.dpDiv.find("iframe.ui-datepicker-cover");!n.length||n.css({left:-t[0],top:-t[1],width:e.dpDiv.outerWidth(),height:e.dpDiv.outerHeight()}),e.dpDiv.find("."+this._dayOverClass+" a").mouseover();var r=this._getNumberOfMonths(e),i=r[1],s=17;e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),i&gt;1&amp;&amp;e.dpDiv.addClass("ui-datepicker-multi-"+i).css("width",s*i+"em"),e.dpDiv[(r[0]!=1||r[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e==$.datepicker._curInst&amp;&amp;$.datepicker._datepickerShowing&amp;&amp;e.input&amp;&amp;e.input.is(":visible")&amp;&amp;!e.input.is(":disabled")&amp;&amp;e.input[0]!=document.activeElement&amp;&amp;e.input.focus();if(e.yearshtml){var o=e.yearshtml;setTimeout(function(){o===e.yearshtml&amp;&amp;e.yearshtml&amp;&amp;e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),o=e.yearshtml=null},0)}},_getBorders:function(e){var t=function(e){return{thin:1,medium:2,thick:3}[e]||e};return[parseFloat(t(e.css("border-left-width"))),parseFloat(t(e.css("border-top-width")))]},_checkOffset:function(e,t,n){var r=e.dpDiv.outerWidth(),i=e.dpDiv.outerHeight(),s=e.input?e.input.outerWidth():0,o=e.input?e.input.outerHeight():0,u=document.documentElement.clientWidth+(n?0:$(document).scrollLeft()),a=document.documentElement.clientHeight+(n?0:$(document).scrollTop());return t.left-=this._get(e,"isRTL")?r-s:0,t.left-=n&amp;&amp;t.left==e.input.offset().left?$(document).scrollLeft():0,t.top-=n&amp;&amp;t.top==e.input.offset().top+o?$(document).scrollTop():0,t.left-=Math.min(t.left,t.left+r&gt;u&amp;&amp;u&gt;r?Math.abs(t.left+r-u):0),t.top-=Math.min(t.top,t.top+i&gt;a&amp;&amp;a&gt;i?Math.abs(i+o):0),t},_findPos:function(e){var t=this._getInst(e),n=this._get(t,"isRTL");while(e&amp;&amp;(e.type=="hidden"||e.nodeType!=1||$.expr.filters.hidden(e)))e=e[n?"previousSibling":"nextSibling"];var r=$(e).offset();return[r.left,r.top]},_hideDatepicker:function(e){var t=this._curInst;if(!t||e&amp;&amp;t!=$.data(e,PROP_NAME))return;if(this._datepickerShowing){var n=this._get(t,"showAnim"),r=this._get(t,"duration"),i=function(){$.datepicker._tidyDialog(t)};$.effects&amp;&amp;($.effects.effect[n]||$.effects[n])?t.dpDiv.hide(n,$.datepicker._get(t,"showOptions"),r,i):t.dpDiv[n=="slideDown"?"slideUp":n=="fadeIn"?"fadeOut":"hide"](n?r:null,i),n||i(),this._datepickerShowing=!1;var s=this._get(t,"onClose");s&amp;&amp;s.apply(t.input?t.input[0]:null,[t.input?t.input.val():"",t]),this._lastInput=null,this._inDialog&amp;&amp;(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),$.blockUI&amp;&amp;($.unblockUI(),$("body").append(this.dpDiv))),this._inDialog=!1}},_tidyDialog:function(e){e.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(!$.datepicker._curInst)return;var t=$(e.target),n=$.datepicker._getInst(t[0]);(t[0].id!=$.datepicker._mainDivId&amp;&amp;t.parents("#"+$.datepicker._mainDivId).length==0&amp;&amp;!t.hasClass($.datepicker.markerClassName)&amp;&amp;!t.closest("."+$.datepicker._triggerClass).length&amp;&amp;$.datepicker._datepickerShowing&amp;&amp;(!$.datepicker._inDialog||!$.blockUI)||t.hasClass($.datepicker.markerClassName)&amp;&amp;$.datepicker._curInst!=n)&amp;&amp;$.datepicker._hideDatepicker()},_adjustDate:function(e,t,n){var r=$(e),i=this._getInst(r[0]);if(this._isDisabledDatepicker(r[0]))return;this._adjustInstDate(i,t+(n=="M"?this._get(i,"showCurrentAtPos"):0),n),this._updateDatepicker(i)},_gotoToday:function(e){var t=$(e),n=this._getInst(t[0]);if(this._get(n,"gotoCurrent")&amp;&amp;n.currentDay)n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear;else{var r=new Date;n.selectedDay=r.getDate(),n.drawMonth=n.selectedMonth=r.getMonth(),n.drawYear=n.selectedYear=r.getFullYear()}this._notifyChange(n),this._adjustDate(t)},_selectMonthYear:function(e,t,n){var r=$(e),i=this._getInst(r[0]);i["selected"+(n=="M"?"Month":"Year")]=i["draw"+(n=="M"?"Month":"Year")]=parseInt(t.options[t.selectedIndex].value,10),this._notifyChange(i),this._adjustDate(r)},_selectDay:function(e,t,n,r){var i=$(e);if($(r).hasClass(this._unselectableClass)||this._isDisabledDatepicker(i[0]))return;var s=this._getInst(i[0]);s.selectedDay=s.currentDay=$("a",r).html(),s.selectedMonth=s.currentMonth=t,s.selectedYear=s.currentYear=n,this._selectDate(e,this._formatDate(s,s.currentDay,s.currentMonth,s.currentYear))},_clearDate:function(e){var t=$(e),n=this._getInst(t[0]);this._selectDate(t,"")},_selectDate:function(e,t){var n=$(e),r=this._getInst(n[0]);t=t!=null?t:this._formatDate(r),r.input&amp;&amp;r.input.val(t),this._updateAlternate(r);var i=this._get(r,"onSelect");i?i.apply(r.input?r.input[0]:null,[t,r]):r.input&amp;&amp;r.input.trigger("change"),r.inline?this._updateDatepicker(r):(this._hideDatepicker(),this._lastInput=r.input[0],typeof r.input[0]!="object"&amp;&amp;r.input.focus(),this._lastInput=null)},_updateAlternate:function(e){var t=this._get(e,"altField");if(t){var n=this._get(e,"altFormat")||this._get(e,"dateFormat"),r=this._getDate(e),i=this.formatDate(n,r,this._getFormatConfig(e));$(t).each(function(){$(this).val(i)})}},noWeekends:function(e){var t=e.getDay();return[t&gt;0&amp;&amp;t&lt;6,""]},iso8601Week:function(e){var t=new Date(e.getTime());t.setDate(t.getDate()+4-(t.getDay()||7));var n=t.getTime();return t.setMonth(0),t.setDate(1),Math.floor(Math.round((n-t)/864e5)/7)+1},parseDate:function(e,t,n){if(e==null||t==null)throw"Invalid arguments";t=typeof t=="object"?t.toString():t+"";if(t=="")return null;var r=(n?n.shortYearCutoff:null)||this._defaults.shortYearCutoff;r=typeof r!="string"?r:(new Date).getFullYear()%100+parseInt(r,10);var i=(n?n.dayNamesShort:null)||this._defaults.dayNamesShort,s=(n?n.dayNames:null)||this._defaults.dayNames,o=(n?n.monthNamesShort:null)||this._defaults.monthNamesShort,u=(n?n.monthNames:null)||this._defaults.monthNames,a=-1,f=-1,l=-1,c=-1,h=!1,p=function(t){var n=y+1&lt;e.length&amp;&amp;e.charAt(y+1)==t;return n&amp;&amp;y++,n},d=function(e){var n=p(e),r=e=="@"?14:e=="!"?20:e=="y"&amp;&amp;n?4:e=="o"?3:2,i=new RegExp("^\\d{1,"+r+"}"),s=t.substring(g).match(i);if(!s)throw"Missing number at position "+g;return g+=s[0].length,parseInt(s[0],10)},v=function(e,n,r){var i=$.map(p(e)?r:n,function(e,t){return[[t,e]]}).sort(function(e,t){return-(e[1].length-t[1].length)}),s=-1;$.each(i,function(e,n){var r=n[1];if(t.substr(g,r.length).toLowerCase()==r.toLowerCase())return s=n[0],g+=r.length,!1});if(s!=-1)return s+1;throw"Unknown name at position "+g},m=function(){if(t.charAt(g)!=e.charAt(y))throw"Unexpected literal at position "+g;g++},g=0;for(var y=0;y&lt;e.length;y++)if(h)e.charAt(y)=="'"&amp;&amp;!p("'")?h=!1:m();else switch(e.charAt(y)){case"d":l=d("d");break;case"D":v("D",i,s);break;case"o":c=d("o");break;case"m":f=d("m");break;case"M":f=v("M",o,u);break;case"y":a=d("y");break;case"@":var b=new Date(d("@"));a=b.getFullYear(),f=b.getMonth()+1,l=b.getDate();break;case"!":var b=new Date((d("!")-this._ticksTo1970)/1e4);a=b.getFullYear(),f=b.getMonth()+1,l=b.getDate();break;case"'":p("'")?m():h=!0;break;default:m()}if(g&lt;t.length){var w=t.substr(g);if(!/^\s+/.test(w))throw"Extra/unparsed characters found in date: "+w}a==-1?a=(new Date).getFullYear():a&lt;100&amp;&amp;(a+=(new Date).getFullYear()-(new Date).getFullYear()%100+(a&lt;=r?0:-100));if(c&gt;-1){f=1,l=c;do{var E=this._getDaysInMonth(a,f-1);if(l&lt;=E)break;f++,l-=E}while(!0)}var b=this._daylightSavingAdjust(new Date(a,f-1,l));if(b.getFullYear()!=a||b.getMonth()+1!=f||b.getDate()!=l)throw"Invalid date";return b},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(e,t,n){if(!t)return"";var r=(n?n.dayNamesShort:null)||this._defaults.dayNamesShort,i=(n?n.dayNames:null)||this._defaults.dayNames,s=(n?n.monthNamesShort:null)||this._defaults.monthNamesShort,o=(n?n.monthNames:null)||this._defaults.monthNames,u=function(t){var n=h+1&lt;e.length&amp;&amp;e.charAt(h+1)==t;return n&amp;&amp;h++,n},a=function(e,t,n){var r=""+t;if(u(e))while(r.length&lt;n)r="0"+r;return r},f=function(e,t,n,r){return u(e)?r[t]:n[t]},l="",c=!1;if(t)for(var h=0;h&lt;e.length;h++)if(c)e.charAt(h)=="'"&amp;&amp;!u("'")?c=!1:l+=e.charAt(h);else switch(e.charAt(h)){case"d":l+=a("d",t.getDate(),2);break;case"D":l+=f("D",t.getDay(),r,i);break;case"o":l+=a("o",Math.round(((new Date(t.getFullYear(),t.getMonth(),t.getDate())).getTime()-(new Date(t.getFullYear(),0,0)).getTime())/864e5),3);break;case"m":l+=a("m",t.getMonth()+1,2);break;case"M":l+=f("M",t.getMonth(),s,o);break;case"y":l+=u("y")?t.getFullYear():(t.getYear()%100&lt;10?"0":"")+t.getYear()%100;break;case"@":l+=t.getTime();break;case"!":l+=t.getTime()*1e4+this._ticksTo1970;break;case"'":u("'")?l+="'":c=!0;break;default:l+=e.charAt(h)}return l},_possibleChars:function(e){var t="",n=!1,r=function(t){var n=i+1&lt;e.length&amp;&amp;e.charAt(i+1)==t;return n&amp;&amp;i++,n};for(var i=0;i&lt;e.length;i++)if(n)e.charAt(i)=="'"&amp;&amp;!r("'")?n=!1:t+=e.charAt(i);else switch(e.charAt(i)){case"d":case"m":case"y":case"@":t+="0123456789";break;case"D":case"M":return null;case"'":r("'")?t+="'":n=!0;break;default:t+=e.charAt(i)}return t},_get:function(e,t){return e.settings[t]!==undefined?e.settings[t]:this._defaults[t]},_setDateFromField:function(e,t){if(e.input.val()==e.lastVal)return;var n=this._get(e,"dateFormat"),r=e.lastVal=e.input?e.input.val():null,i,s;i=s=this._getDefaultDate(e);var o=this._getFormatConfig(e);try{i=this.parseDate(n,r,o)||s}catch(u){this.log(u),r=t?"":r}e.selectedDay=i.getDate(),e.drawMonth=e.selectedMonth=i.getMonth(),e.drawYear=e.selectedYear=i.getFullYear(),e.currentDay=r?i.getDate():0,e.currentMonth=r?i.getMonth():0,e.currentYear=r?i.getFullYear():0,this._adjustInstDate(e)},_getDefaultDate:function(e){return this._restrictMinMax(e,this._determineDate(e,this._get(e,"defaultDate"),new Date))},_determineDate:function(e,t,n){var r=function(e){var t=new Date;return t.setDate(t.getDate()+e),t},i=function(t){try{return $.datepicker.parseDate($.datepicker._get(e,"dateFormat"),t,$.datepicker._getFormatConfig(e))}catch(n){}var r=(t.toLowerCase().match(/^c/)?$.datepicker._getDate(e):null)||new Date,i=r.getFullYear(),s=r.getMonth(),o=r.getDate(),u=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,a=u.exec(t);while(a){switch(a[2]||"d"){case"d":case"D":o+=parseInt(a[1],10);break;case"w":case"W":o+=parseInt(a[1],10)*7;break;case"m":case"M":s+=parseInt(a[1],10),o=Math.min(o,$.datepicker._getDaysInMonth(i,s));break;case"y":case"Y":i+=parseInt(a[1],10),o=Math.min(o,$.datepicker._getDaysInMonth(i,s))}a=u.exec(t)}return new Date(i,s,o)},s=t==null||t===""?n:typeof t=="string"?i(t):typeof t=="number"?isNaN(t)?n:r(t):new Date(t.getTime());return s=s&amp;&amp;s.toString()=="Invalid Date"?n:s,s&amp;&amp;(s.setHours(0),s.setMinutes(0),s.setSeconds(0),s.setMilliseconds(0)),this._daylightSavingAdjust(s)},_daylightSavingAdjust:function(e){return e?(e.setHours(e.getHours()&gt;12?e.getHours()+2:0),e):null},_setDate:function(e,t,n){var r=!t,i=e.selectedMonth,s=e.selectedYear,o=this._restrictMinMax(e,this._determineDate(e,t,new Date));e.selectedDay=e.currentDay=o.getDate(),e.drawMonth=e.selectedMonth=e.currentMonth=o.getMonth(),e.drawYear=e.selectedYear=e.currentYear=o.getFullYear(),(i!=e.selectedMonth||s!=e.selectedYear)&amp;&amp;!n&amp;&amp;this._notifyChange(e),this._adjustInstDate(e),e.input&amp;&amp;e.input.val(r?"":this._formatDate(e))},_getDate:function(e){var t=!e.currentYear||e.input&amp;&amp;e.input.val()==""?null:this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return t},_attachHandlers:function(e){var t=this._get(e,"stepMonths"),n="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){window["DP_jQuery_"+dpuuid].datepicker._adjustDate(n,-t,"M")},next:function(){window["DP_jQuery_"+dpuuid].datepicker._adjustDate(n,+t,"M")},hide:function(){window["DP_jQuery_"+dpuuid].datepicker._hideDatepicker()},today:function(){window["DP_jQuery_"+dpuuid].datepicker._gotoToday(n)},selectDay:function(){return window["DP_jQuery_"+dpuuid].datepicker._selectDay(n,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return window["DP_jQuery_"+dpuuid].datepicker._selectMonthYear(n,this,"M"),!1},selectYear:function(){return window["DP_jQuery_"+dpuuid].datepicker._selectMonthYear(n,this,"Y"),!1}};$(this).bind(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})},_generateHTML:function(e){var t=new Date;t=this._daylightSavingAdjust(new Date(t.getFullYear(),t.getMonth(),t.getDate()));var n=this._get(e,"isRTL"),r=this._get(e,"showButtonPanel"),i=this._get(e,"hideIfNoPrevNext"),s=this._get(e,"navigationAsDateFormat"),o=this._getNumberOfMonths(e),u=this._get(e,"showCurrentAtPos"),a=this._get(e,"stepMonths"),f=o[0]!=1||o[1]!=1,l=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),c=this._getMinMaxDate(e,"min"),h=this._getMinMaxDate(e,"max"),p=e.drawMonth-u,d=e.drawYear;p&lt;0&amp;&amp;(p+=12,d--);if(h){var v=this._daylightSavingAdjust(new Date(h.getFullYear(),h.getMonth()-o[0]*o[1]+1,h.getDate()));v=c&amp;&amp;v&lt;c?c:v;while(this._daylightSavingAdjust(new Date(d,p,1))&gt;v)p--,p&lt;0&amp;&amp;(p=11,d--)}e.drawMonth=p,e.drawYear=d;var m=this._get(e,"prevText");m=s?this.formatDate(m,this._daylightSavingAdjust(new Date(d,p-a,1)),this._getFormatConfig(e)):m;var g=this._canAdjustMonth(e,-1,d,p)?'&lt;a class="ui-datepicker-prev ui-corner-all" data-handler="prev" data-event="click" title="'+m+'"&gt;&lt;span class="ui-icon ui-icon-circle-triangle-'+(n?"e":"w")+'"&gt;'+m+"&lt;/span&gt;&lt;/a&gt;":i?"":'&lt;a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+m+'"&gt;&lt;span class="ui-icon ui-icon-circle-triangle-'+(n?"e":"w")+'"&gt;'+m+"&lt;/span&gt;&lt;/a&gt;",y=this._get(e,"nextText");y=s?this.formatDate(y,this._daylightSavingAdjust(new Date(d,p+a,1)),this._getFormatConfig(e)):y;var b=this._canAdjustMonth(e,1,d,p)?'&lt;a class="ui-datepicker-next ui-corner-all" data-handler="next" data-event="click" title="'+y+'"&gt;&lt;span class="ui-icon ui-icon-circle-triangle-'+(n?"w":"e")+'"&gt;'+y+"&lt;/span&gt;&lt;/a&gt;":i?"":'&lt;a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+y+'"&gt;&lt;span class="ui-icon ui-icon-circle-triangle-'+(n?"w":"e")+'"&gt;'+y+"&lt;/span&gt;&lt;/a&gt;",w=this._get(e,"currentText"),E=this._get(e,"gotoCurrent")&amp;&amp;e.currentDay?l:t;w=s?this.formatDate(w,E,this._getFormatConfig(e)):w;var S=e.inline?"":'&lt;button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click"&gt;'+this._get(e,"closeText")+"&lt;/button&gt;",x=r?'&lt;div class="ui-datepicker-buttonpane ui-widget-content"&gt;'+(n?S:"")+(this._isInRange(e,E)?'&lt;button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" data-handler="today" data-event="click"&gt;'+w+"&lt;/button&gt;":"")+(n?"":S)+"&lt;/div&gt;":"",T=parseInt(this._get(e,"firstDay"),10);T=isNaN(T)?0:T;var N=this._get(e,"showWeek"),C=this._get(e,"dayNames"),k=this._get(e,"dayNamesShort"),L=this._get(e,"dayNamesMin"),A=this._get(e,"monthNames"),O=this._get(e,"monthNamesShort"),M=this._get(e,"beforeShowDay"),_=this._get(e,"showOtherMonths"),D=this._get(e,"selectOtherMonths"),P=this._get(e,"calculateWeek")||this.iso8601Week,H=this._getDefaultDate(e),B="";for(var j=0;j&lt;o[0];j++){var F="";this.maxRows=4;for(var I=0;I&lt;o[1];I++){var q=this._daylightSavingAdjust(new Date(d,p,e.selectedDay)),R=" ui-corner-all",U="";if(f){U+='&lt;div class="ui-datepicker-group';if(o[1]&gt;1)switch(I){case 0:U+=" ui-datepicker-group-first",R=" ui-corner-"+(n?"right":"left");break;case o[1]-1:U+=" ui-datepicker-group-last",R=" ui-corner-"+(n?"left":"right");break;default:U+=" ui-datepicker-group-middle",R=""}U+='"&gt;'}U+='&lt;div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+R+'"&gt;'+(/all|left/.test(R)&amp;&amp;j==0?n?b:g:"")+(/all|right/.test(R)&amp;&amp;j==0?n?g:b:"")+this._generateMonthYearHeader(e,p,d,c,h,j&gt;0||I&gt;0,A,O)+'&lt;/div&gt;&lt;table class="ui-datepicker-calendar"&gt;&lt;thead&gt;'+"&lt;tr&gt;";var z=N?'&lt;th class="ui-datepicker-week-col"&gt;'+this._get(e,"weekHeader")+"&lt;/th&gt;":"";for(var W=0;W&lt;7;W++){var X=(W+T)%7;z+="&lt;th"+((W+T+6)%7&gt;=5?' class="ui-datepicker-week-end"':"")+"&gt;"+'&lt;span title="'+C[X]+'"&gt;'+L[X]+"&lt;/span&gt;&lt;/th&gt;"}U+=z+"&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;";var V=this._getDaysInMonth(d,p);d==e.selectedYear&amp;&amp;p==e.selectedMonth&amp;&amp;(e.selectedDay=Math.min(e.selectedDay,V));var J=(this._getFirstDayOfMonth(d,p)-T+7)%7,K=Math.ceil((J+V)/7),Q=f?this.maxRows&gt;K?this.maxRows:K:K;this.maxRows=Q;var G=this._daylightSavingAdjust(new Date(d,p,1-J));for(var Y=0;Y&lt;Q;Y++){U+="&lt;tr&gt;";var Z=N?'&lt;td class="ui-datepicker-week-col"&gt;'+this._get(e,"calculateWeek")(G)+"&lt;/td&gt;":"";for(var W=0;W&lt;7;W++){var et=M?M.apply(e.input?e.input[0]:null,[G]):[!0,""],tt=G.getMonth()!=p,nt=tt&amp;&amp;!D||!et[0]||c&amp;&amp;G&lt;c||h&amp;&amp;G&gt;h;Z+='&lt;td class="'+((W+T+6)%7&gt;=5?" ui-datepicker-week-end":"")+(tt?" ui-datepicker-other-month":"")+(G.getTime()==q.getTime()&amp;&amp;p==e.selectedMonth&amp;&amp;e._keyEvent||H.getTime()==G.getTime()&amp;&amp;H.getTime()==q.getTime()?" "+this._dayOverClass:"")+(nt?" "+this._unselectableClass+" ui-state-disabled":"")+(tt&amp;&amp;!_?"":" "+et[1]+(G.getTime()==l.getTime()?" "+this._currentClass:"")+(G.getTime()==t.getTime()?" ui-datepicker-today":""))+'"'+((!tt||_)&amp;&amp;et[2]?' title="'+et[2]+'"':"")+(nt?"":' data-handler="selectDay" data-event="click" data-month="'+G.getMonth()+'" data-year="'+G.getFullYear()+'"')+"&gt;"+(tt&amp;&amp;!_?"&amp;#xa0;":nt?'&lt;span class="ui-state-default"&gt;'+G.getDate()+"&lt;/span&gt;":'&lt;a class="ui-state-default'+(G.getTime()==t.getTime()?" ui-state-highlight":"")+(G.getTime()==l.getTime()?" ui-state-active":"")+(tt?" ui-priority-secondary":"")+'" href="#"&gt;'+G.getDate()+"&lt;/a&gt;")+"&lt;/td&gt;",G.setDate(G.getDate()+1),G=this._daylightSavingAdjust(G)}U+=Z+"&lt;/tr&gt;"}p++,p&gt;11&amp;&amp;(p=0,d++),U+="&lt;/tbody&gt;&lt;/table&gt;"+(f?"&lt;/div&gt;"+(o[0]&gt;0&amp;&amp;I==o[1]-1?'&lt;div class="ui-datepicker-row-break"&gt;&lt;/div&gt;':""):""),F+=U}B+=F}return B+=x+($.browser.msie&amp;&amp;parseInt($.browser.version,10)&lt;7&amp;&amp;!e.inline?'&lt;iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"&gt;&lt;/iframe&gt;':""),e._keyEvent=!1,B},_generateMonthYearHeader:function(e,t,n,r,i,s,o,u){var a=this._get(e,"changeMonth"),f=this._get(e,"changeYear"),l=this._get(e,"showMonthAfterYear"),c='&lt;div class="ui-datepicker-title"&gt;',h="";if(s||!a)h+='&lt;span class="ui-datepicker-month"&gt;'+o[t]+"&lt;/span&gt;";else{var p=r&amp;&amp;r.getFullYear()==n,d=i&amp;&amp;i.getFullYear()==n;h+='&lt;select class="ui-datepicker-month" data-handler="selectMonth" data-event="change"&gt;';for(var v=0;v&lt;12;v++)(!p||v&gt;=r.getMonth())&amp;&amp;(!d||v&lt;=i.getMonth())&amp;&amp;(h+='&lt;option value="'+v+'"'+(v==t?' selected="selected"':"")+"&gt;"+u[v]+"&lt;/option&gt;");h+="&lt;/select&gt;"}l||(c+=h+(s||!a||!f?"&amp;#xa0;":""));if(!e.yearshtml){e.yearshtml="";if(s||!f)c+='&lt;span class="ui-datepicker-year"&gt;'+n+"&lt;/span&gt;";else{var m=this._get(e,"yearRange").split(":"),g=(new Date).getFullYear(),y=function(e){var t=e.match(/c[+-].*/)?n+parseInt(e.substring(1),10):e.match(/[+-].*/)?g+parseInt(e,10):parseInt(e,10);return isNaN(t)?g:t},b=y(m[0]),w=Math.max(b,y(m[1]||""));b=r?Math.max(b,r.getFullYear()):b,w=i?Math.min(w,i.getFullYear()):w,e.yearshtml+='&lt;select class="ui-datepicker-year" data-handler="selectYear" data-event="change"&gt;';for(;b&lt;=w;b++)e.yearshtml+='&lt;option value="'+b+'"'+(b==n?' selected="selected"':"")+"&gt;"+b+"&lt;/option&gt;";e.yearshtml+="&lt;/select&gt;",c+=e.yearshtml,e.yearshtml=null}}return c+=this._get(e,"yearSuffix"),l&amp;&amp;(c+=(s||!a||!f?"&amp;#xa0;":"")+h),c+="&lt;/div&gt;",c},_adjustInstDate:function(e,t,n){var r=e.drawYear+(n=="Y"?t:0),i=e.drawMonth+(n=="M"?t:0),s=Math.min(e.selectedDay,this._getDaysInMonth(r,i))+(n=="D"?t:0),o=this._restrictMinMax(e,this._daylightSavingAdjust(new Date(r,i,s)));e.selectedDay=o.getDate(),e.drawMonth=e.selectedMonth=o.getMonth(),e.drawYear=e.selectedYear=o.getFullYear(),(n=="M"||n=="Y")&amp;&amp;this._notifyChange(e)},_restrictMinMax:function(e,t){var n=this._getMinMaxDate(e,"min"),r=this._getMinMaxDate(e,"max"),i=n&amp;&amp;t&lt;n?n:t;return i=r&amp;&amp;i&gt;r?r:i,i},_notifyChange:function(e){var t=this._get(e,"onChangeMonthYear");t&amp;&amp;t.apply(e.input?e.input[0]:null,[e.selectedYear,e.selectedMonth+1,e])},_getNumberOfMonths:function(e){var t=this._get(e,"numberOfMonths");return t==null?[1,1]:typeof t=="number"?[1,t]:t},_getMinMaxDate:function(e,t){return this._determineDate(e,this._get(e,t+"Date"),null)},_getDaysInMonth:function(e,t){return 32-this._daylightSavingAdjust(new Date(e,t,32)).getDate()},_getFirstDayOfMonth:function(e,t){return(new Date(e,t,1)).getDay()},_canAdjustMonth:function(e,t,n,r){var i=this._getNumberOfMonths(e),s=this._daylightSavingAdjust(new Date(n,r+(t&lt;0?t:i[0]*i[1]),1));return t&lt;0&amp;&amp;s.setDate(this._getDaysInMonth(s.getFullYear(),s.getMonth())),this._isInRange(e,s)},_isInRange:function(e,t){var n=this._getMinMaxDate(e,"min"),r=this._getMinMaxDate(e,"max");return(!n||t.getTime()&gt;=n.getTime())&amp;&amp;(!r||t.getTime()&lt;=r.getTime())},_getFormatConfig:function(e){var t=this._get(e,"shortYearCutoff");return t=typeof t!="string"?t:(new Date).getFullYear()%100+parseInt(t,10),{shortYearCutoff:t,dayNamesShort:this._get(e,"dayNamesShort"),dayNames:this._get(e,"dayNames"),monthNamesShort:this._get(e,"monthNamesShort"),monthNames:this._get(e,"monthNames")}},_formatDate:function(e,t,n,r){t||(e.currentDay=e.selectedDay,e.currentMonth=e.selectedMonth,e.currentYear=e.selectedYear);var i=t?typeof t=="object"?t:this._daylightSavingAdjust(new Date(r,n,t)):this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return this.formatDate(this._get(e,"dateFormat"),i,this._getFormatConfig(e))}}),$.fn.datepicker=function(e){if(!this.length)return this;$.datepicker.initialized||($(document).mousedown($.datepicker._checkExternalClick).find(document.body).append($.datepicker.dpDiv),$.datepicker.initialized=!0);var t=Array.prototype.slice.call(arguments,1);return typeof e!="string"||e!="isDisabled"&amp;&amp;e!="getDate"&amp;&amp;e!="widget"?e=="option"&amp;&amp;arguments.length==2&amp;&amp;typeof arguments[1]=="string"?$.datepicker["_"+e+"Datepicker"].apply($.datepicker,[this[0]].concat(t)):this.each(function(){typeof e=="string"?$.datepicker["_"+e+"Datepicker"].apply($.datepicker,[this].concat(t)):$.datepicker._attachDatepicker(this,e)}):$.datepicker["_"+e+"Datepicker"].apply($.datepicker,[this[0]].concat(t))},$.datepicker=new Datepicker,$.datepicker.initialized=!1,$.datepicker.uuid=(new Date).getTime(),$.datepicker.version="1.9.0",window["DP_jQuery_"+dpuuid]=$})(jQuery);(function(e,t){var n="ui-dialog ui-widget ui-widget-content ui-corner-all ",r={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},i={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0};e.widget("ui.dialog",{version:"1.9.0",options:{autoOpen:!0,buttons:{},closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:!1,maxWidth:!1,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var n=e(this).css(t).offset().top;n&lt;0&amp;&amp;e(this).css("top",t.top-n)}},resizable:!0,show:null,stack:!0,title:"",width:300,zIndex:1e3},_create:function(){this.originalTitle=this.element.attr("title"),typeof this.originalTitle!="string"&amp;&amp;(this.originalTitle=""),this.oldPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.options.title=this.options.title||this.originalTitle;var t=this,r=this.options,i=r.title||"&amp;#160;",s=(this.uiDialog=e("&lt;div&gt;")).addClass(n+r.dialogClass).css({display:"none",outline:0,zIndex:r.zIndex}).attr("tabIndex",-1).keydown(function(n){r.closeOnEscape&amp;&amp;!n.isDefaultPrevented()&amp;&amp;n.keyCode&amp;&amp;n.keyCode===e.ui.keyCode.ESCAPE&amp;&amp;(t.close(n),n.preventDefault())}).mousedown(function(e){t.moveToTop(!1,e)}).appendTo("body"),o=this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(s),u=(this.uiDialogTitlebar=e("&lt;div&gt;")).addClass("ui-dialog-titlebar  ui-widget-header  ui-corner-all  ui-helper-clearfix").prependTo(s),a=e("&lt;a href='#'&gt;&lt;/a&gt;").addClass("ui-dialog-titlebar-close  ui-corner-all").attr("role","button").click(function(e){e.preventDefault(),t.close(e)}).appendTo(u),f=(this.uiDialogTitlebarCloseText=e("&lt;span&gt;")).addClass("ui-icon ui-icon-closethick").text(r.closeText).appendTo(a),l=e("&lt;span&gt;").uniqueId().addClass("ui-dialog-title").html(i).prependTo(u),c=(this.uiDialogButtonPane=e("&lt;div&gt;")).addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),h=(this.uiButtonSet=e("&lt;div&gt;")).addClass("ui-dialog-buttonset").appendTo(c);s.attr({role:"dialog","aria-labelledby":l.attr("id")}),u.find("*").add(u).disableSelection(),this._hoverable(a),this._focusable(a),r.draggable&amp;&amp;e.fn.draggable&amp;&amp;this._makeDraggable(),r.resizable&amp;&amp;e.fn.resizable&amp;&amp;this._makeResizable(),this._createButtons(r.buttons),this._isOpen=!1,e.fn.bgiframe&amp;&amp;s.bgiframe(),this._on(s,{keydown:function(t){if(!r.modal||t.keyCode!==e.ui.keyCode.TAB)return;var n=e(":tabbable",s),i=n.filter(":first"),o=n.filter(":last");if(t.target===o[0]&amp;&amp;!t.shiftKey)return i.focus(1),!1;if(t.target===i[0]&amp;&amp;t.shiftKey)return o.focus(1),!1}})},_init:function(){this.options.autoOpen&amp;&amp;this.open()},_destroy:function(){var e,t=this.oldPosition;this.overlay&amp;&amp;this.overlay.destroy(),this.uiDialog.hide(),this.element.removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body"),this.uiDialog.remove(),this.originalTitle&amp;&amp;this.element.attr("title",this.originalTitle),e=t.parent.children().eq(t.index),e.length&amp;&amp;e[0]!==this.element[0]?e.before(this.element):t.parent.append(this.element)},widget:function(){return this.uiDialog},close:function(t){var n=this,r,i;if(!this._isOpen)return;if(!1===this._trigger("beforeClose",t))return;return this._isOpen=!1,this.overlay&amp;&amp;this.overlay.destroy(),this.options.hide?this.uiDialog.hide(this.options.hide,function(){n._trigger("close",t)}):(this.uiDialog.hide(),this._trigger("close",t)),e.ui.dialog.overlay.resize(),this.options.modal&amp;&amp;(r=0,e(".ui-dialog").each(function(){this!==n.uiDialog[0]&amp;&amp;(i=e(this).css("z-index"),isNaN(i)||(r=Math.max(r,i)))}),e.ui.dialog.maxZ=r),this},isOpen:function(){return this._isOpen},moveToTop:function(t,n){var r=this.options,i;return r.modal&amp;&amp;!t||!r.stack&amp;&amp;!r.modal?this._trigger("focus",n):(r.zIndex&gt;e.ui.dialog.maxZ&amp;&amp;(e.ui.dialog.maxZ=r.zIndex),this.overlay&amp;&amp;(e.ui.dialog.maxZ+=1,e.ui.dialog.overlay.maxZ=e.ui.dialog.maxZ,this.overlay.$el.css("z-index",e.ui.dialog.overlay.maxZ)),i={scrollTop:this.element.scrollTop(),scrollLeft:this.element.scrollLeft()},e.ui.dialog.maxZ+=1,this.uiDialog.css("z-index",e.ui.dialog.maxZ),this.element.attr(i),this._trigger("focus",n),this)},open:function(){if(this._isOpen)return;var t,n=this.options,r=this.uiDialog;return this._size(),this._position(n.position),r.show(n.show),this.overlay=n.modal?new e.ui.dialog.overlay(this):null,this.moveToTop(!0),t=this.element.find(":tabbable"),t.length||(t=this.uiDialogButtonPane.find(":tabbable"),t.length||(t=r)),t.eq(0).focus(),this._isOpen=!0,this._trigger("open"),this},_createButtons:function(t){var n,r,i=this,s=!1;this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),typeof t=="object"&amp;&amp;t!==null&amp;&amp;e.each(t,function(){return!(s=!0)}),s?(e.each(t,function(t,n){n=e.isFunction(n)?{click:n,text:t}:n;var r=e("&lt;button type='button'&gt;").attr(n,!0).unbind("click").click(function(){n.click.apply(i.element[0],arguments)}).appendTo(i.uiButtonSet);e.fn.button&amp;&amp;r.button()}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog)):this.uiDialog.removeClass("ui-dialog-buttons")},_makeDraggable:function(){function r(e){return{position:e.position,offset:e.offset}}var t=this,n=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(n,i){e(this).addClass("ui-dialog-dragging"),t._trigger("dragStart",n,r(i))},drag:function(e,n){t._trigger("drag",e,r(n))},stop:function(i,s){n.position=[s.position.left-t.document.scrollLeft(),s.position.top-t.document.scrollTop()],e(this).removeClass("ui-dialog-dragging"),t._trigger("dragStop",i,r(s)),e.ui.dialog.overlay.resize()}})},_makeResizable:function(n){function u(e){return{originalPosition:e.originalPosition,originalSize:e.originalSize,position:e.position,size:e.size}}n=n===t?this.options.resizable:n;var r=this,i=this.options,s=this.uiDialog.css("position"),o=typeof n=="string"?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:i.maxWidth,maxHeight:i.maxHeight,minWidth:i.minWidth,minHeight:this._minHeight(),handles:o,start:function(t,n){e(this).addClass("ui-dialog-resizing"),r._trigger("resizeStart",t,u(n))},resize:function(e,t){r._trigger("resize",e,u(t))},stop:function(t,n){e(this).removeClass("ui-dialog-resizing"),i.height=e(this).height(),i.width=e(this).width(),r._trigger("resizeStop",t,u(n)),e.ui.dialog.overlay.resize()}}).css("position",s).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var e=this.options;return e.height==="auto"?e.minHeight:Math.min(e.minHeight,e.height)},_position:function(t){var n=[],r=[0,0],i;if(t){if(typeof t=="string"||typeof t=="object"&amp;&amp;"0"in t)n=t.split?t.split(" "):[t[0],t[1]],n.length===1&amp;&amp;(n[1]=n[0]),e.each(["left","top"],function(e,t){+n[e]===n[e]&amp;&amp;(r[e]=n[e],n[e]=t)}),t={my:n.join(" "),at:n.join(" "),offset:r.join(" ")};t=e.extend({},e.ui.dialog.prototype.options.position,t)}else t=e.ui.dialog.prototype.options.position;i=this.uiDialog.is(":visible"),i||this.uiDialog.show(),this.uiDialog.position(t),i||this.uiDialog.hide()},_setOptions:function(t){var n=this,s={},o=!1;e.each(t,function(e,t){n._setOption(e,t),e in r&amp;&amp;(o=!0),e in i&amp;&amp;(s[e]=t)}),o&amp;&amp;this._size(),this.uiDialog.is(":data(resizable)")&amp;&amp;this.uiDialog.resizable("option",s)},_setOption:function(t,r){var i,s,o=this.uiDialog;switch(t){case"buttons":this._createButtons(r);break;case"closeText":this.uiDialogTitlebarCloseText.text(""+r);break;case"dialogClass":o.removeClass(this.options.dialogClass).addClass(n+r);break;case"disabled":r?o.addClass("ui-dialog-disabled"):o.removeClass("ui-dialog-disabled");break;case"draggable":i=o.is(":data(draggable)"),i&amp;&amp;!r&amp;&amp;o.draggable("destroy"),!i&amp;&amp;r&amp;&amp;this._makeDraggable();break;case"position":this._position(r);break;case"resizable":s=o.is(":data(resizable)"),s&amp;&amp;!r&amp;&amp;o.resizable("destroy"),s&amp;&amp;typeof r=="string"&amp;&amp;o.resizable("option","handles",r),!s&amp;&amp;r!==!1&amp;&amp;this._makeResizable(r);break;case"title":e(".ui-dialog-title",this.uiDialogTitlebar).html(""+(r||"&amp;#160;"))}this._super(t,r)},_size:function(){var t,n,r,i=this.options,s=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0}),i.minWidth&gt;i.width&amp;&amp;(i.width=i.minWidth),t=this.uiDialog.css({height:"auto",width:i.width}).outerHeight(),n=Math.max(0,i.minHeight-t),i.height==="auto"?e.support.minHeight?this.element.css({minHeight:n,height:"auto"}):(this.uiDialog.show(),r=this.element.css("height","auto").height(),s||this.uiDialog.hide(),this.element.height(Math.max(r,n))):this.element.height(Math.max(i.height-t,0)),this.uiDialog.is(":data(resizable)")&amp;&amp;this.uiDialog.resizable("option","minHeight",this._minHeight())}}),e.extend(e.ui.dialog,{uuid:0,maxZ:0,getTitleId:function(e){var t=e.attr("id");return t||(this.uuid+=1,t=this.uuid),"ui-dialog-title-"+t},overlay:function(t){this.$el=e.ui.dialog.overlay.create(t)}}),e.extend(e.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:e.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(e){return e+".dialog-overlay"}).join(" "),create:function(t){this.instances.length===0&amp;&amp;(setTimeout(function(){e.ui.dialog.overlay.instances.length&amp;&amp;e(document).bind(e.ui.dialog.overlay.events,function(t){if(e(t.target).zIndex()&lt;e.ui.dialog.overlay.maxZ)return!1})},1),e(window).bind("resize.dialog-overlay",e.ui.dialog.overlay.resize));var n=this.oldInstances.pop()||e("&lt;div&gt;").addClass("ui-widget-overlay");return e(document).bind("keydown.dialog-overlay",function(r){var i=e.ui.dialog.overlay.instances;i.length!==0&amp;&amp;i[i.length-1]===n&amp;&amp;t.options.closeOnEscape&amp;&amp;!r.isDefaultPrevented()&amp;&amp;r.keyCode&amp;&amp;r.keyCode===e.ui.keyCode.ESCAPE&amp;&amp;(t.close(r),r.preventDefault())}),n.appendTo(document.body).css({width:this.width(),height:this.height()}),e.fn.bgiframe&amp;&amp;n.bgiframe(),this.instances.push(n),n},destroy:function(t){var n=e.inArray(t,this.instances),r=0;n!==-1&amp;&amp;this.oldInstances.push(this.instances.splice(n,1)[0]),this.instances.length===0&amp;&amp;e([document,window]).unbind(".dialog-overlay"),t.height(0).width(0).remove(),e.each(this.instances,function(){r=Math.max(r,this.css("z-index"))}),this.maxZ=r},height:function(){var t,n;return e.browser.msie?(t=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),n=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight),t&lt;n?e(window).height()+"px":t+"px"):e(document).height()+"px"},width:function(){var t,n;return e.browser.msie?(t=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),n=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth),t&lt;n?e(window).width()+"px":t+"px"):e(document).width()+"px"},resize:function(){var t=e([]);e.each(e.ui.dialog.overlay.instances,function(){t=t.add(this)}),t.css({width:0,height:0}).css({width:e.ui.dialog.overlay.width(),height:e.ui.dialog.overlay.height()})}}),e.extend(e.ui.dialog.overlay.prototype,{destroy:function(){e.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);(function(e,t){var n=!1;e.widget("ui.menu",{version:"1.9.0",defaultElement:"&lt;ul&gt;",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content ui-corner-all").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}).bind("click"+this.eventNamespace,e.proxy(function(e){this.options.disabled&amp;&amp;e.preventDefault()},this)),this.options.disabled&amp;&amp;this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item &gt; a":function(e){e.preventDefault()},"click .ui-state-disabled &gt; a":function(e){e.preventDefault()},"click .ui-menu-item:has(a)":function(t){var r=e(t.target).closest(".ui-menu-item");!n&amp;&amp;r.not(".ui-state-disabled").length&amp;&amp;(n=!0,this.select(t),r.has(".ui-menu").length?this.expand(t):this.element.is(":focus")||(this.element.trigger("focus",[!0]),this.active&amp;&amp;this.active.parents(".ui-menu").length===1&amp;&amp;clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(t){var n=e(t.currentTarget);n.siblings().children(".ui-state-active").removeClass("ui-state-active"),this.focus(t,n)},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(e,t){var n=this.active||this.element.children(".ui-menu-item").eq(0);t||this.focus(e,n)},blur:function(t){this._delay(function(){e.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){e(t.target).closest(".ui-menu").length||this.collapseAll(t),n=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").andSelf().removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").children("a").removeUniqueId().removeClass("ui-corner-all ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var t=e(this);t.data("ui-menu-submenu-carat")&amp;&amp;t.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(t){function a(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&amp;")}var n,r,i,s,o,u=!0;switch(t.keyCode){case e.ui.keyCode.PAGE_UP:this.previousPage(t);break;case e.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case e.ui.keyCode.HOME:this._move("first","first",t);break;case e.ui.keyCode.END:this._move("last","last",t);break;case e.ui.keyCode.UP:this.previous(t);break;case e.ui.keyCode.DOWN:this.next(t);break;case e.ui.keyCode.LEFT:this.collapse(t);break;case e.ui.keyCode.RIGHT:this.active&amp;&amp;!this.active.is(".ui-state-disabled")&amp;&amp;this.expand(t);break;case e.ui.keyCode.ENTER:case e.ui.keyCode.SPACE:this._activate(t);break;case e.ui.keyCode.ESCAPE:this.collapse(t);break;default:u=!1,r=this.previousFilter||"",i=String.fromCharCode(t.keyCode),s=!1,clearTimeout(this.filterTimer),i===r?s=!0:i=r+i,o=new RegExp("^"+a(i),"i"),n=this.activeMenu.children(".ui-menu-item").filter(function(){return o.test(e(this).children("a").text())}),n=s&amp;&amp;n.index(this.active.next())!==-1?this.active.nextAll(".ui-menu-item"):n,n.length||(i=String.fromCharCode(t.keyCode),o=new RegExp("^"+a(i),"i"),n=this.activeMenu.children(".ui-menu-item").filter(function(){return o.test(e(this).children("a").text())})),n.length?(this.focus(t,n),n.length&gt;1?(this.previousFilter=i,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter):delete this.previousFilter}u&amp;&amp;t.preventDefault()},_activate:function(e){this.active.is(".ui-state-disabled")||(this.active.children("a[aria-haspopup='true']").length?this.expand(e):this.select(e))},refresh:function(){var t,n=this.options.icons.submenu,r=this.element.find(this.options.menus+":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-corner-all").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"});t=r.add(this.element),t.children(":not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","presentation").children("a").uniqueId().addClass("ui-corner-all").attr({tabIndex:-1,role:this._itemRole()}),t.children(":not(.ui-menu-item)").each(function(){var t=e(this);/[^\-â€”â€“\s]/.test(t.text())||t.addClass("ui-widget-content ui-menu-divider")}),t.children(".ui-state-disabled").attr("aria-disabled","true"),r.each(function(){var t=e(this),r=t.prev("a"),i=e("&lt;span&gt;").addClass("ui-menu-icon ui-icon "+n).data("ui-menu-submenu-carat",!0);r.attr("aria-haspopup","true").prepend(i),t.attr("aria-labelledby",r.attr("id"))}),this.active&amp;&amp;!e.contains(this.element[0],this.active[0])&amp;&amp;this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},focus:function(e,t){var n,r;this.blur(e,e&amp;&amp;e.type==="focus"),this._scrollIntoView(t),this.active=t.first(),r=this.active.children("a").addClass("ui-state-focus"),this.options.role&amp;&amp;this.element.attr("aria-activedescendant",r.attr("id")),this.active.parent().closest(".ui-menu-item").children("a:first").addClass("ui-state-active"),e&amp;&amp;e.type==="keydown"?this._close():this.timer=this._delay(function(){this._close()},this.delay),n=t.children(".ui-menu"),n.length&amp;&amp;/^mouse/.test(e.type)&amp;&amp;this._startOpening(n),this.activeMenu=t.parent(),this._trigger("focus",e,{item:t})},_scrollIntoView:function(t){var n,r,i,s,o,u;this._hasScroll()&amp;&amp;(n=parseFloat(e.css(this.activeMenu[0],"borderTopWidth"))||0,r=parseFloat(e.css(this.activeMenu[0],"paddingTop"))||0,i=t.offset().top-this.activeMenu.offset().top-n-r,s=this.activeMenu.scrollTop(),o=this.activeMenu.height(),u=t.height(),i&lt;0?this.activeMenu.scrollTop(s+i):i+u&gt;o&amp;&amp;this.activeMenu.scrollTop(s+i-o+u))},blur:function(e,t){t||clearTimeout(this.timer);if(!this.active)return;this.active.children("a").removeClass("ui-state-focus"),this.active=null,this._trigger("blur",e,{item:this.active})},_startOpening:function(e){clearTimeout(this.timer);if(e.attr("aria-hidden")!=="true")return;this.timer=this._delay(function(){this._close(),this._open(e)},this.delay)},_open:function(t){var n=e.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(n)},collapseAll:function(t,n){clearTimeout(this.timer),this.timer=this._delay(function(){var r=n?this.element:e(t&amp;&amp;t.target).closest(this.element.find(".ui-menu"));r.length||(r=this.element),this._close(r),this.blur(t),this.activeMenu=r},this.delay)},_close:function(e){e||(e=this.active?this.active.parent():this.element),e.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find("a.ui-state-active").removeClass("ui-state-active")},collapse:function(e){var t=this.active&amp;&amp;this.active.parent().closest(".ui-menu-item",this.element);t&amp;&amp;t.length&amp;&amp;(this._close(),this.focus(e,t))},expand:function(e){var t=this.active&amp;&amp;this.active.children(".ui-menu ").children(".ui-menu-item").first();t&amp;&amp;t.length&amp;&amp;(this._open(t.parent()),this._delay(function(){this.focus(e,t)}))},next:function(e){this._move("next","first",e)},previous:function(e){this._move("prev","last",e)},isFirstItem:function(){return this.active&amp;&amp;!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&amp;&amp;!this.active.nextAll(".ui-menu-item").length},_move:function(e,t,n){var r;this.active&amp;&amp;(e==="first"||e==="last"?r=this.active[e==="first"?"prevAll":"nextAll"](".ui-menu-item").eq(-1):r=this.active[e+"All"](".ui-menu-item").eq(0));if(!r||!r.length||!this.active)r=this.activeMenu.children(".ui-menu-item")[t]();this.focus(n,r)},nextPage:function(t){var n,r,i;if(!this.active){this.next(t);return}if(this.isLastItem())return;this._hasScroll()?(r=this.active.offset().top,i=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return n=e(this),n.offset().top-r-i&lt;0}),this.focus(t,n)):this.focus(t,this.activeMenu.children(".ui-menu-item")[this.active?"last":"first"]())},previousPage:function(t){var n,r,i;if(!this.active){this.next(t);return}if(this.isFirstItem())return;this._hasScroll()?(r=this.active.offset().top,i=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return n=e(this),n.offset().top-r+i&gt;0}),this.focus(t,n)):this.focus(t,this.activeMenu.children(".ui-menu-item").first())},_hasScroll:function(){return this.element.outerHeight()&lt;this.element.prop("scrollHeight")},select:function(t){this.active=this.active||e(t.target).closest(".ui-menu-item");var n={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(t,!0),this._trigger("select",t,n)}})})(jQuery);(function(e,t){e.widget("ui.progressbar",{version:"1.9.0",options:{value:0,max:100},min:0,_create:function(){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=e("&lt;div class='ui-progressbar-value ui-widget-header ui-corner-left'&gt;&lt;/div&gt;").appendTo(this.element),this.oldValue=this._value(),this._refreshValue()},_destroy:function(){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()},value:function(e){return e===t?this._value():(this._setOption("value",e),this)},_setOption:function(e,t){e==="value"&amp;&amp;(this.options.value=t,this._refreshValue(),this._value()===this.options.max&amp;&amp;this._trigger("complete")),this._super(e,t)},_value:function(){var e=this.options.value;return typeof e!="number"&amp;&amp;(e=0),Math.min(this.options.max,Math.max(this.min,e))},_percentage:function(){return 100*this._value()/this.options.max},_refreshValue:function(){var e=this.value(),t=this._percentage();this.oldValue!==e&amp;&amp;(this.oldValue=e,this._trigger("change")),this.valueDiv.toggle(e&gt;this.min).toggleClass("ui-corner-right",e===this.options.max).width(t.toFixed(0)+"%"),this.element.attr("aria-valuenow",e)}})})(jQuery);(function(e,t){var n=5;e.widget("ui.slider",e.ui.mouse,{version:"1.9.0",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null},_create:function(){var t,r=this.options,i=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),s="&lt;a class='ui-slider-handle ui-state-default ui-corner-all' href='#'&gt;&lt;/a&gt;",o=r.values&amp;&amp;r.values.length||1,u=[];this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"+(r.disabled?" ui-slider-disabled ui-disabled":"")),this.range=e([]),r.range&amp;&amp;(r.range===!0&amp;&amp;(r.values||(r.values=[this._valueMin(),this._valueMin()]),r.values.length&amp;&amp;r.values.length!==2&amp;&amp;(r.values=[r.values[0],r.values[0]])),this.range=e("&lt;div&gt;&lt;/div&gt;").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(r.range==="min"||r.range==="max"?" ui-slider-range-"+r.range:"")));for(t=i.length;t&lt;o;t++)u.push(s);this.handles=i.add(e(u.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.add(this.range).filter("a").click(function(e){e.preventDefault()}).mouseenter(function(){r.disabled||e(this).addClass("ui-state-hover")}).mouseleave(function(){e(this).removeClass("ui-state-hover")}).focus(function(){r.disabled?e(this).blur():(e(".ui-slider .ui-state-focus").removeClass("ui-state-focus"),e(this).addClass("ui-state-focus"))}).blur(function(){e(this).removeClass("ui-state-focus")}),this.handles.each(function(t){e(this).data("ui-slider-handle-index",t)}),this._on(this.handles,{keydown:function(t){var r,i,s,o,u=e(t.target).data("ui-slider-handle-index");switch(t.keyCode){case e.ui.keyCode.HOME:case e.ui.keyCode.END:case e.ui.keyCode.PAGE_UP:case e.ui.keyCode.PAGE_DOWN:case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:t.preventDefault();if(!this._keySliding){this._keySliding=!0,e(t.target).addClass("ui-state-active"),r=this._start(t,u);if(r===!1)return}}o=this.options.step,this.options.values&amp;&amp;this.options.values.length?i=s=this.values(u):i=s=this.value();switch(t.keyCode){case e.ui.keyCode.HOME:s=this._valueMin();break;case e.ui.keyCode.END:s=this._valueMax();break;case e.ui.keyCode.PAGE_UP:s=this._trimAlignValue(i+(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.PAGE_DOWN:s=this._trimAlignValue(i-(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:if(i===this._valueMax())return;s=this._trimAlignValue(i+o);break;case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(i===this._valueMin())return;s=this._trimAlignValue(i-o)}this._slide(t,u,s)},keyup:function(t){var n=e(t.target).data("ui-slider-handle-index");this._keySliding&amp;&amp;(this._keySliding=!1,this._stop(t,n),this._change(t,n),e(t.target).removeClass("ui-state-active"))}}),this._refreshValue(),this._animateOff=!1},_destroy:function(){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"),this._mouseDestroy()},_mouseCapture:function(t){var n,r,i,s,o,u,a,f,l=this,c=this.options;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),n={x:t.pageX,y:t.pageY},r=this._normValueFromMouse(n),i=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var n=Math.abs(r-l.values(t));i&gt;n&amp;&amp;(i=n,s=e(this),o=t)}),c.range===!0&amp;&amp;this.values(1)===c.min&amp;&amp;(o+=1,s=e(this.handles[o])),u=this._start(t,o),u===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,s.addClass("ui-state-active").focus(),a=s.offset(),f=!e(t.target).parents().andSelf().is(".ui-slider-handle"),this._clickOffset=f?{left:0,top:0}:{left:t.pageX-a.left-s.width()/2,top:t.pageY-a.top-s.height()/2-(parseInt(s.css("borderTopWidth"),10)||0)-(parseInt(s.css("borderBottomWidth"),10)||0)+(parseInt(s.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,r),this._animateOff=!0,!0))},_mouseStart:function(e){return!0},_mouseDrag:function(e){var t={x:e.pageX,y:e.pageY},n=this._normValueFromMouse(t);return this._slide(e,this._handleIndex,n),!1},_mouseStop:function(e){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(e,this._handleIndex),this._change(e,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(e){var t,n,r,i,s;return this.orientation==="horizontal"?(t=this.elementSize.width,n=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(t=this.elementSize.height,n=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),r=n/t,r&gt;1&amp;&amp;(r=1),r&lt;0&amp;&amp;(r=0),this.orientation==="vertical"&amp;&amp;(r=1-r),i=this._valueMax()-this._valueMin(),s=this._valueMin()+r*i,this._trimAlignValue(s)},_start:function(e,t){var n={handle:this.handles[t],value:this.value()};return this.options.values&amp;&amp;this.options.values.length&amp;&amp;(n.value=this.values(t),n.values=this.values()),this._trigger("start",e,n)},_slide:function(e,t,n){var r,i,s;this.options.values&amp;&amp;this.options.values.length?(r=this.values(t?0:1),this.options.values.length===2&amp;&amp;this.options.range===!0&amp;&amp;(t===0&amp;&amp;n&gt;r||t===1&amp;&amp;n&lt;r)&amp;&amp;(n=r),n!==this.values(t)&amp;&amp;(i=this.values(),i[t]=n,s=this._trigger("slide",e,{handle:this.handles[t],value:n,values:i}),r=this.values(t?0:1),s!==!1&amp;&amp;this.values(t,n,!0))):n!==this.value()&amp;&amp;(s=this._trigger("slide",e,{handle:this.handles[t],value:n}),s!==!1&amp;&amp;this.value(n))},_stop:function(e,t){var n={handle:this.handles[t],value:this.value()};this.options.values&amp;&amp;this.options.values.length&amp;&amp;(n.value=this.values(t),n.values=this.values()),this._trigger("stop",e,n)},_change:function(e,t){if(!this._keySliding&amp;&amp;!this._mouseSliding){var n={handle:this.handles[t],value:this.value()};this.options.values&amp;&amp;this.options.values.length&amp;&amp;(n.value=this.values(t),n.values=this.values()),this._trigger("change",e,n)}},value:function(e){if(arguments.length){this.options.value=this._trimAlignValue(e),this._refreshValue(),this._change(null,0);return}return this._value()},values:function(t,n){var r,i,s;if(arguments.length&gt;1){this.options.values[t]=this._trimAlignValue(n),this._refreshValue(),this._change(null,t);return}if(!arguments.length)return this._values();if(!e.isArray(arguments[0]))return this.options.values&amp;&amp;this.options.values.length?this._values(t):this.value();r=this.options.values,i=arguments[0];for(s=0;s&lt;r.length;s+=1)r[s]=this._trimAlignValue(i[s]),this._change(null,s);this._refreshValue()},_setOption:function(t,n){var r,i=0;e.isArray(this.options.values)&amp;&amp;(i=this.options.values.length),e.Widget.prototype._setOption.apply(this,arguments);switch(t){case"disabled":n?(this.handles.filter(".ui-state-focus").blur(),this.handles.removeClass("ui-state-hover"),this.handles.prop("disabled",!0),this.element.addClass("ui-disabled")):(this.handles.prop("disabled",!1),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=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":this._animateOff=!0,this._refreshValue();for(r=0;r&lt;i;r+=1)this._change(null,r);this._animateOff=!1}},_value:function(){var e=this.options.value;return e=this._trimAlignValue(e),e},_values:function(e){var t,n,r;if(arguments.length)return t=this.options.values[e],t=this._trimAlignValue(t),t;n=this.options.values.slice();for(r=0;r&lt;n.length;r+=1)n[r]=this._trimAlignValue(n[r]);return n},_trimAlignValue:function(e){if(e&lt;=this._valueMin())return this._valueMin();if(e&gt;=this._valueMax())return this._valueMax();var t=this.options.step&gt;0?this.options.step:1,n=(e-this._valueMin())%t,r=e-n;return Math.abs(n)*2&gt;=t&amp;&amp;(r+=n&gt;0?t:-t),parseFloat(r.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var t,n,r,i,s,o=this.options.range,u=this.options,a=this,f=this._animateOff?!1:u.animate,l={};this.options.values&amp;&amp;this.options.values.length?this.handles.each(function(r,i){n=(a.values(r)-a._valueMin())/(a._valueMax()-a._valueMin())*100,l[a.orientation==="horizontal"?"left":"bottom"]=n+"%",e(this).stop(1,1)[f?"animate":"css"](l,u.animate),a.options.range===!0&amp;&amp;(a.orientation==="horizontal"?(r===0&amp;&amp;a.range.stop(1,1)[f?"animate":"css"]({left:n+"%"},u.animate),r===1&amp;&amp;a.range[f?"animate":"css"]({width:n-t+"%"},{queue:!1,duration:u.animate})):(r===0&amp;&amp;a.range.stop(1,1)[f?"animate":"css"]({bottom:n+"%"},u.animate),r===1&amp;&amp;a.range[f?"animate":"css"]({height:n-t+"%"},{queue:!1,duration:u.animate}))),t=n}):(r=this.value(),i=this._valueMin(),s=this._valueMax(),n=s!==i?(r-i)/(s-i)*100:0,l[this.orientation==="horizontal"?"left":"bottom"]=n+"%",this.handle.stop(1,1)[f?"animate":"css"](l,u.animate),o==="min"&amp;&amp;this.orientation==="horizontal"&amp;&amp;this.range.stop(1,1)[f?"animate":"css"]({width:n+"%"},u.animate),o==="max"&amp;&amp;this.orientation==="horizontal"&amp;&amp;this.range[f?"animate":"css"]({width:100-n+"%"},{queue:!1,duration:u.animate}),o==="min"&amp;&amp;this.orientation==="vertical"&amp;&amp;this.range.stop(1,1)[f?"animate":"css"]({height:n+"%"},u.animate),o==="max"&amp;&amp;this.orientation==="vertical"&amp;&amp;this.range[f?"animate":"css"]({height:100-n+"%"},{queue:!1,duration:u.animate}))}})})(jQuery);(function(e){function t(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&amp;&amp;this._trigger("change")}}e.widget("ui.spinner",{version:"1.9.0",defaultElement:"&lt;input&gt;",widgetEventPrefix:"spin",options:{culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var t={},n=this.element;return e.each(["min","max","step"],function(e,r){var i=n.attr(r);i!==undefined&amp;&amp;i.length&amp;&amp;(t[r]=i)}),t},_events:{keydown:function(e){this._start(e)&amp;&amp;this._keydown(e)&amp;&amp;e.preventDefault()},keyup:"_stop",focus:function(){this.uiSpinner.addClass("ui-state-active"),this.previous=this.element.val()},blur:function(e){if(this.cancelBlur){delete this.cancelBlur;return}this._refresh(),this.uiSpinner.removeClass("ui-state-active"),this.previous!==this.element.val()&amp;&amp;this._trigger("change",e)},mousewheel:function(e,t){if(!t)return;if(!this.spinning&amp;&amp;!this._start(e))return!1;this._spin((t&gt;0?1:-1)*this.options.step,e),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&amp;&amp;this._stop(e)},100),e.preventDefault()},"mousedown .ui-spinner-button":function(t){function r(){var e=this.element[0]===this.document[0].activeElement;e||(this.element.focus(),this.previous=n,this._delay(function(){this.previous=n}))}var n;n=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),t.preventDefault(),r.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,r.call(this)});if(this._start(t)===!1)return;this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(t){if(!e(t.currentTarget).hasClass("ui-state-active"))return;if(this._start(t)===!1)return!1;this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseleave .ui-spinner-button":"_stop"},_draw:function(){var e=this.uiSpinner=this.element.addClass("ui-spinner-input").attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml());this._hoverable(e),this.element.attr("role","spinbutton"),this.buttons=e.find(".ui-spinner-button").attr("tabIndex",-1).button().removeClass("ui-corner-all"),this.buttons.height()&gt;Math.ceil(e.height()*.5)&amp;&amp;e.height()&gt;0&amp;&amp;e.height(e.height()),this.options.disabled&amp;&amp;this.disable()},_keydown:function(t){var n=this.options,r=e.ui.keyCode;switch(t.keyCode){case r.UP:return this._repeat(null,1,t),!0;case r.DOWN:return this._repeat(null,-1,t),!0;case r.PAGE_UP:return this._repeat(null,n.page,t),!0;case r.PAGE_DOWN:return this._repeat(null,-n.page,t),!0}return!1},_uiSpinnerHtml:function(){return"&lt;span class='ui-spinner ui-state-default ui-widget ui-widget-content ui-corner-all'&gt;&lt;/span&gt;"},_buttonHtml:function(){return"&lt;a class='ui-spinner-button ui-spinner-up ui-corner-tr'&gt;&lt;span class='ui-icon "+this.options.icons.up+"'&gt;&amp;#9650;&lt;/span&gt;"+"&lt;/a&gt;"+"&lt;a class='ui-spinner-button ui-spinner-down ui-corner-br'&gt;"+"&lt;span class='ui-icon "+this.options.icons.down+"'&gt;&amp;#9660;&lt;/span&gt;"+"&lt;/a&gt;"},_start:function(e){return!this.spinning&amp;&amp;this._trigger("start",e)===!1?!1:(this.counter||(this.counter=1),this.spinning=!0,!0)},_repeat:function(e,t,n){e=e||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,t,n)},e),this._spin(t*this.options.step,n)},_spin:function(e,t){var n=this.value()||0;this.counter||(this.counter=1),n=this._adjustValue(n+e*this._increment(this.counter));if(!this.spinning||this._trigger("spin",t,{value:n})!==!1)this._value(n),this.counter++},_increment:function(t){var n=this.options.incremental;return n?e.isFunction(n)?n(t):Math.floor(t*t*t/5e4-t*t/500+17*t/200+1):1},_precision:function(){var e=this._precisionOf(this.options.step);return this.options.min!==null&amp;&amp;(e=Math.max(e,this._precisionOf(this.options.min))),e},_precisionOf:function(e){var t=e.toString(),n=t.indexOf(".");return n===-1?0:t.length-n-1},_adjustValue:function(e){var t,n,r=this.options;return t=r.min!==null?r.min:0,n=e-t,n=Math.round(n/r.step)*r.step,e=t+n,e=parseFloat(e.toFixed(this._precision())),r.max!==null&amp;&amp;e&gt;r.max?r.max:r.min!==null&amp;&amp;e&lt;r.min?r.min:e},_stop:function(e){if(!this.spinning)return;clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",e)},_setOption:function(e,t){if(e==="culture"||e==="numberFormat"){var n=this._parse(this.element.val());this.options[e]=t,this.element.val(this._format(n));return}(e==="max"||e==="min"||e==="step")&amp;&amp;typeof t=="string"&amp;&amp;(t=this._parse(t)),this._super(e,t),e==="disabled"&amp;&amp;(t?(this.element.prop("disabled",!0),this.buttons.button("disable")):(this.element.prop("disabled",!1),this.buttons.button("enable")))},_setOptions:t(function(e){this._super(e),this._value(this.element.val())}),_parse:function(e){return typeof e=="string"&amp;&amp;e!==""&amp;&amp;(e=window.Globalize&amp;&amp;this.options.numberFormat?Globalize.parseFloat(e,10,this.options.culture):+e),e===""||isNaN(e)?null:e},_format:function(e){return e===""?"":window.Globalize&amp;&amp;this.options.numberFormat?Globalize.format(e,this.options.numberFormat,this.options.culture):e},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},_value:function(e,t){var n;e!==""&amp;&amp;(n=this._parse(e),n!==null&amp;&amp;(t||(n=this._adjustValue(n)),e=this._format(n))),this.element.val(e),this._refresh()},_destroy:function(){this.element.removeClass("ui-spinner-input").prop("disabled",!1).removeAttr("autocomplete").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:t(function(e){this._stepUp(e)}),_stepUp:function(e){this._spin((e||1)*this.options.step)},stepDown:t(function(e){this._stepDown(e)}),_stepDown:function(e){this._spin((e||1)*-this.options.step)},pageUp:t(function(e){this._stepUp((e||1)*this.options.page)}),pageDown:t(function(e){this._stepDown((e||1)*this.options.page)}),value:function(e){if(!arguments.length)return this._parse(this.element.val());t(this._value).call(this,e)},widget:function(){return this.uiSpinner}})})(jQuery);(function(e,t){function i(){return++n}function s(e){return e=e.cloneNode(!1),e.hash.length&gt;1&amp;&amp;e.href.replace(r,"")===location.href.replace(r,"")}var n=0,r=/#.*$/;e.widget("ui.tabs",{version:"1.9.0",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var t,n=this,r=this.options,i=r.active;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",r.collapsible).delegate(".ui-tabs-nav &gt; li","mousedown"+this.eventNamespace,function(t){e(this).is(".ui-state-disabled")&amp;&amp;t.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){e(this).closest("li").is(".ui-state-disabled")&amp;&amp;this.blur()}),this._processTabs();if(i===null){location.hash&amp;&amp;this.anchors.each(function(e,t){if(t.hash===location.hash)return i=e,!1}),i===null&amp;&amp;(i=this.tabs.filter(".ui-tabs-active").index());if(i===null||i===-1)i=this.tabs.length?0:!1}i!==!1&amp;&amp;(i=this.tabs.index(this.tabs.eq(i)),i===-1&amp;&amp;(i=r.collapsible?!1:0)),r.active=i,!r.collapsible&amp;&amp;r.active===!1&amp;&amp;this.anchors.length&amp;&amp;(r.active=0),e.isArray(r.disabled)&amp;&amp;(r.disabled=e.unique(r.disabled.concat(e.map(this.tabs.filter(".ui-state-disabled"),function(e){return n.tabs.index(e)}))).sort()),this.options.active!==!1&amp;&amp;this.anchors.length?this.active=this._findActive(this.options.active):this.active=e(),this._refresh(),this.active.length&amp;&amp;this.load(r.active)},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):e()}},_tabKeydown:function(t){var n=e(this.document[0].activeElement).closest("li"),r=this.tabs.index(n),i=!0;if(this._handlePageNav(t))return;switch(t.keyCode){case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:r++;break;case e.ui.keyCode.UP:case e.ui.keyCode.LEFT:i=!1,r--;break;case e.ui.keyCode.END:r=this.anchors.length-1;break;case e.ui.keyCode.HOME:r=0;break;case e.ui.keyCode.SPACE:t.preventDefault(),clearTimeout(this.activating),this._activate(r);return;case e.ui.keyCode.ENTER:t.preventDefault(),clearTimeout(this.activating),this._activate(r===this.options.active?!1:r);return;default:return}t.preventDefault(),clearTimeout(this.activating),r=this._focusNextTab(r,i),t.ctrlKey||(n.attr("aria-selected","false"),this.tabs.eq(r).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",r)},this.delay))},_panelKeydown:function(t){if(this._handlePageNav(t))return;t.ctrlKey&amp;&amp;t.keyCode===e.ui.keyCode.UP&amp;&amp;(t.preventDefault(),this.active.focus())},_handlePageNav:function(t){if(t.altKey&amp;&amp;t.keyCode===e.ui.keyCode.PAGE_UP)return this._activate(this._focusNextTab(this.options.active-1,!1)),!0;if(t.altKey&amp;&amp;t.keyCode===e.ui.keyCode.PAGE_DOWN)return this._activate(this._focusNextTab(this.options.active+1,!0)),!0},_findNextTab:function(t,n){function i(){return t&gt;r&amp;&amp;(t=0),t&lt;0&amp;&amp;(t=r),t}var r=this.tabs.length-1;while(e.inArray(i(),this.options.disabled)!==-1)t=n?t+1:t-1;return t},_focusNextTab:function(e,t){return e=this._findNextTab(e,t),this.tabs.eq(e).focus(),e},_setOption:function(e,t){if(e==="active"){this._activate(t);return}if(e==="disabled"){this._setupDisabled(t);return}this._super(e,t),e==="collapsible"&amp;&amp;(this.element.toggleClass("ui-tabs-collapsible",t),!t&amp;&amp;this.options.active===!1&amp;&amp;this._activate(0)),e==="event"&amp;&amp;this._setupEvents(t),e==="heightStyle"&amp;&amp;this._setupHeightStyle(t)},_tabId:function(e){return e.attr("aria-controls")||"ui-tabs-"+i()},_sanitizeSelector:function(e){return e?e.replace(/[!"$%&amp;'()*+,.\/:;&lt;=&gt;?@\[\]\^`{|}~]/g,"\\$&amp;"):""},refresh:function(){var t,n=this.options,r=this.tablist.children(":has(a[href])");n.disabled=e.map(r.filter(".ui-state-disabled"),function(e){return r.index(e)}),this._processTabs(),n.active===!1||!this.anchors.length?(n.active=!1,this.active=e()):this.active.length&amp;&amp;!e.contains(this.tablist[0],this.active[0])?this.tabs.length===n.disabled.length?(n.active=!1,this.active=e()):this._activate(this._findNextTab(Math.max(0,n.active-1),!1)):n.active=this.tabs.index(this.active),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var t=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("&gt; li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return e("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=e(),this.anchors.each(function(n,r){var i,o,u,a=e(r).uniqueId().attr("id"),f=e(r).closest("li"),l=f.attr("aria-controls");s(r)?(i=r.hash,o=t.element.find(t._sanitizeSelector(i))):(u=t._tabId(f),i="#"+u,o=t.element.find(i),o.length||(o=t._createPanel(u),o.insertAfter(t.panels[n-1]||t.tablist)),o.attr("aria-live","polite")),o.length&amp;&amp;(t.panels=t.panels.add(o)),l&amp;&amp;f.data("ui-tabs-aria-controls",l),f.attr({"aria-controls":i.substring(1),"aria-labelledby":a}),o.attr("aria-labelledby",a)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.element.find("ol,ul").eq(0)},_createPanel:function(t){return e("&lt;div&gt;").attr("id",t).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(t){e.isArray(t)&amp;&amp;(t.length?t.length===this.anchors.length&amp;&amp;(t=!0):t=!1);for(var n=0,r;r=this.tabs[n];n++)t===!0||e.inArray(n,t)!==-1?e(r).addClass("ui-state-disabled").attr("aria-disabled","true"):e(r).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=t},_setupEvents:function(t){var n={click:function(e){e.preventDefault()}};t&amp;&amp;e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,n),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(t){var n,r,i=this.element.parent();t==="fill"?(e.support.minHeight||(r=i.css("overflow"),i.css("overflow","hidden")),n=i.height(),this.element.siblings(":visible").each(function(){var t=e(this),r=t.css("position");if(r==="absolute"||r==="fixed")return;n-=t.outerHeight(!0)}),r&amp;&amp;i.css("overflow",r),this.element.children().not(this.panels).each(function(){n-=e(this).outerHeight(!0)}),this.panels.each(function(){e(this).height(Math.max(0,n-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):t==="auto"&amp;&amp;(n=0,this.panels.each(function(){n=Math.max(n,e(this).height("").height())}).height(n))},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i.closest("li"),o=s[0]===r[0],u=o&amp;&amp;n.collapsible,a=u?e():this._getPanelForTab(s),f=r.length?this._getPanelForTab(r):e(),l={oldTab:r,oldPanel:f,newTab:u?e():s,newPanel:a};t.preventDefault();if(s.hasClass("ui-state-disabled")||s.hasClass("ui-tabs-loading")||this.running||o&amp;&amp;!n.collapsible||this._trigger("beforeActivate",t,l)===!1)return;n.active=u?!1:this.tabs.index(s),this.active=o?e():s,this.xhr&amp;&amp;this.xhr.abort(),!f.length&amp;&amp;!a.length&amp;&amp;e.error("jQuery UI Tabs: Mismatching fragment identifier."),a.length&amp;&amp;this.load(this.tabs.index(s),t),this._toggle(t,l)},_toggle:function(t,n){function o(){r.running=!1,r._trigger("activate",t,n)}function u(){n.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),i.length&amp;&amp;r.options.show?r._show(i,r.options.show,o):(i.show(),o())}var r=this,i=n.newPanel,s=n.oldPanel;this.running=!0,s.length&amp;&amp;this.options.hide?this._hide(s,this.options.hide,function(){n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),u()}):(n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),s.hide(),u()),s.attr({"aria-expanded":"false","aria-hidden":"true"}),n.oldTab.attr("aria-selected","false"),i.length&amp;&amp;s.length?n.oldTab.attr("tabIndex",-1):i.length&amp;&amp;this.tabs.filter(function(){return e(this).attr("tabIndex")===0}).attr("tabIndex",-1),i.attr({"aria-expanded":"true","aria-hidden":"false"}),n.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(t){var n,r=this._findActive(t);if(r[0]===this.active[0])return;r.length||(r=this.active),n=r.find(".ui-tabs-anchor")[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop})},_findActive:function(t){return t===!1?e():this.tabs.eq(t)},_getIndex:function(e){return typeof e=="string"&amp;&amp;(e=this.anchors.index(this.anchors.filter("[href$='"+e+"']"))),e},_destroy:function(){this.xhr&amp;&amp;this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeData("href.tabs").removeData("load.tabs").removeUniqueId(),this.tabs.add(this.panels).each(function(){e.data(this,"ui-tabs-destroy")?e(this).remove():e(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var t=e(this),n=t.data("ui-tabs-aria-controls");n?t.attr("aria-controls",n):t.removeAttr("aria-controls")}),this.options.heightStyle!=="content"&amp;&amp;this.panels.css("height","")},enable:function(n){var r=this.options.disabled;if(r===!1)return;n===t?r=!1:(n=this._getIndex(n),e.isArray(r)?r=e.map(r,function(e){return e!==n?e:null}):r=e.map(this.tabs,function(e,t){return t!==n?t:null})),this._setupDisabled(r)},disable:function(n){var r=this.options.disabled;if(r===!0)return;if(n===t)r=!0;else{n=this._getIndex(n);if(e.inArray(n,r)!==-1)return;e.isArray(r)?r=e.merge([n],r).sort():r=[n]}this._setupDisabled(r)},load:function(t,n){t=this._getIndex(t);var r=this,i=this.tabs.eq(t),o=i.find(".ui-tabs-anchor"),u=this._getPanelForTab(i),a={tab:i,panel:u};if(s(o[0]))return;this.xhr=e.ajax(this._ajaxSettings(o,n,a)),this.xhr&amp;&amp;this.xhr.statusText!=="canceled"&amp;&amp;(i.addClass("ui-tabs-loading"),u.attr("aria-busy","true"),this.xhr.success(function(e){setTimeout(function(){u.html(e),r._trigger("load",n,a)},1)}).complete(function(e,t){setTimeout(function(){t==="abort"&amp;&amp;r.panels.stop(!1,!0),i.removeClass("ui-tabs-loading"),u.removeAttr("aria-busy"),e===r.xhr&amp;&amp;delete r.xhr},1)}))},_ajaxSettings:function(t,n,r){var i=this;return{url:t.attr("href"),beforeSend:function(t,s){return i._trigger("beforeLoad",n,e.extend({jqXHR:t,ajaxSettings:s},r))}}},_getPanelForTab:function(t){var n=e(t).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+n))}}),e.uiBackCompat!==!1&amp;&amp;(e.ui.tabs.prototype._ui=function(e,t){return{tab:e,panel:t,index:this.anchors.index(e)}},e.widget("ui.tabs",e.ui.tabs,{url:function(e,t){this.anchors.eq(e).attr("href",t)}}),e.widget("ui.tabs",e.ui.tabs,{options:{ajaxOptions:null,cache:!1},_create:function(){this._super();var t=this;this._on({tabsbeforeload:function(n,r){if(e.data(r.tab[0],"cache.tabs")){n.preventDefault();return}r.jqXHR.success(function(){t.options.cache&amp;&amp;e.data(r.tab[0],"cache.tabs",!0)})}})},_ajaxSettings:function(t,n,r){var i=this.options.ajaxOptions;return e.extend({},i,{error:function(e,t,n){try{i.error(e,t,r.tab.closest("li").index(),r.tab[0])}catch(n){}}},this._superApply(arguments))},_setOption:function(e,t){e==="cache"&amp;&amp;t===!1&amp;&amp;this.anchors.removeData("cache.tabs"),this._super(e,t)},_destroy:function(){this.anchors.removeData("cache.tabs"),this._super()},url:function(e,t){this.anchors.eq(e).removeData("cache.tabs"),this._superApply(arguments)}}),e.widget("ui.tabs",e.ui.tabs,{abort:function(){this.xhr&amp;&amp;this.xhr.abort()}}),e.widget("ui.tabs",e.ui.tabs,{options:{spinner:"&lt;em&gt;Loading&amp;#8230;&lt;/em&gt;"},_create:function(){this._super(),this._on({tabsbeforeload:function(e,t){if(e.target!==this.element[0]||!this.options.spinner)return;var n=t.tab.find("span"),r=n.html();n.html(this.options.spinner),t.jqXHR.complete(function(){n.html(r)})}})}}),e.widget("ui.tabs",e.ui.tabs,{options:{enable:null,disable:null},enable:function(t){var n=this.options,r;if(t&amp;&amp;n.disabled===!0||e.isArray(n.disabled)&amp;&amp;e.inArray(t,n.disabled)!==-1)r=!0;this._superApply(arguments),r&amp;&amp;this._trigger("enable",null,this._ui(this.anchors[t],this.panels[t]))},disable:function(t){var n=this.options,r;if(t&amp;&amp;n.disabled===!1||e.isArray(n.disabled)&amp;&amp;e.inArray(t,n.disabled)===-1)r=!0;this._superApply(arguments),r&amp;&amp;this._trigger("disable",null,this._ui(this.anchors[t],this.panels[t]))}}),e.widget("ui.tabs",e.ui.tabs,{options:{add:null,remove:null,tabTemplate:"&lt;li&gt;&lt;a href='#{href}'&gt;&lt;span&gt;#{label}&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;"},add:function(n,r,i){i===t&amp;&amp;(i=this.anchors.length);var s,o,u=this.options,a=e(u.tabTemplate.replace(/#\{href\}/g,n).replace(/#\{label\}/g,r)),f=n.indexOf("#")?this._tabId(a):n.replace("#","");return a.addClass("ui-state-default ui-corner-top").data("ui-tabs-destroy",!0),a.attr("aria-controls",f),s=i&gt;=this.tabs.length,o=this.element.find("#"+f),o.length||(o=this._createPanel(f),s?i&gt;0?o.insertAfter(this.panels.eq(-1)):o.appendTo(this.element):o.insertBefore(this.panels[i])),o.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").hide(),s?a.appendTo(this.tablist):a.insertBefore(this.tabs[i]),u.disabled=e.map(u.disabled,function(e){return e&gt;=i?++e:e}),this.refresh(),this.tabs.length===1&amp;&amp;u.active===!1&amp;&amp;this.option("active",0),this._trigger("add",null,this._ui(this.anchors[i],this.panels[i])),this},remove:function(t){t=this._getIndex(t);var n=this.options,r=this.tabs.eq(t).remove(),i=this._getPanelForTab(r).remove();return r.hasClass("ui-tabs-active")&amp;&amp;this.anchors.length&gt;2&amp;&amp;this._activate(t+(t+1&lt;this.anchors.length?1:-1)),n.disabled=e.map(e.grep(n.disabled,function(e){return e!==t}),function(e){return e&gt;=t?--e:e}),this.refresh(),this._trigger("remove",null,this._ui(r.find("a")[0],i[0])),this}}),e.widget("ui.tabs",e.ui.tabs,{length:function(){return this.anchors.length}}),e.widget("ui.tabs",e.ui.tabs,{options:{idPrefix:"ui-tabs-"},_tabId:function(t){var n=t.is("li")?t.find("a[href]"):t;return n=n[0],e(n).closest("li").attr("aria-controls")||n.title&amp;&amp;n.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF\-]/g,"")||this.options.idPrefix+i()}}),e.widget("ui.tabs",e.ui.tabs,{options:{panelTemplate:"&lt;div&gt;&lt;/div&gt;"},_createPanel:function(t){return e(this.options.panelTemplate).attr("id",t).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)}}),e.widget("ui.tabs",e.ui.tabs,{_create:function(){var e=this.options;e.active===null&amp;&amp;e.selected!==t&amp;&amp;(e.active=e.selected===-1?!1:e.selected),this._super(),e.selected=e.active,e.selected===!1&amp;&amp;(e.selected=-1)},_setOption:function(e,t){if(e!=="selected")return this._super(e,t);var n=this.options;this._super("active",t===-1?!1:t),n.selected=n.active,n.selected===!1&amp;&amp;(n.selected=-1)},_eventHandler:function(e){this._superApply(arguments),this.options.selected=this.options.active,this.options.selected===!1&amp;&amp;(this.options.selected=-1)}}),e.widget("ui.tabs",e.ui.tabs,{options:{show:null,select:null},_create:function(){this._super(),this.options.active!==!1&amp;&amp;this._trigger("show",null,this._ui(this.active.find(".ui-tabs-anchor")[0],this._getPanelForTab(this.active)[0]))},_trigger:function(e,t,n){var r=this._superApply(arguments);return r?(e==="beforeActivate"&amp;&amp;n.newTab.length?r=this._super("select",t,{tab:n.newTab.find(".ui-tabs-anchor")[0],panel:n.newPanel[0],index:n.newTab.closest("li").index()}):e==="activate"&amp;&amp;n.newTab.length&amp;&amp;(r=this._super("show",t,{tab:n.newTab.find(".ui-tabs-anchor")[0],panel:n.newPanel[0],index:n.newTab.closest("li").index()})),r):!1}}),e.widget("ui.tabs",e.ui.tabs,{select:function(e){e=this._getIndex(e);if(e===-1){if(!this.options.collapsible||this.options.selected===-1)return;e=this.options.selected}this.anchors.eq(e).trigger(this.options.event+this.eventNamespace)}}),function(){var t=0;e.widget("ui.tabs",e.ui.tabs,{options:{cookie:null},_create:function(){var e=this.options,t;e.active==null&amp;&amp;e.cookie&amp;&amp;(t=parseInt(this._cookie(),10),t===-1&amp;&amp;(t=!1),e.active=t),this._super()},_cookie:function(n){var r=[this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+ ++t)];return arguments.length&amp;&amp;(r.push(n===!1?-1:n),r.push(this.options.cookie)),e.cookie.apply(null,r)},_refresh:function(){this._super(),this.options.cookie&amp;&amp;this._cookie(this.options.active,this.options.cookie)},_eventHandler:function(e){this._superApply(arguments),this.options.cookie&amp;&amp;this._cookie(this.options.active,this.options.cookie)},_destroy:function(){this._super(),this.options.cookie&amp;&amp;this._cookie(null,this.options.cookie)}})}(),e.widget("ui.tabs",e.ui.tabs,{_trigger:function(t,n,r){var i=e.extend({},r);return t==="load"&amp;&amp;(i.panel=i.panel[0],i.tab=i.tab.find(".ui-tabs-anchor")[0]),this._super(t,n,i)}}),e.widget("ui.tabs",e.ui.tabs,{options:{fx:null},_getFx:function(){var t,n,r=this.options.fx;return r&amp;&amp;(e.isArray(r)?(t=r[0],n=r[1]):t=n=r),r?{show:n,hide:t}:null},_toggle:function(e,t){function o(){n.running=!1,n._trigger("activate",e,t)}function u(){t.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),r.length&amp;&amp;s.show?r.animate(s.show,s.show.duration,function(){o()}):(r.show(),o())}var n=this,r=t.newPanel,i=t.oldPanel,s=this._getFx();if(!s)return this._super(e,t);n.running=!0,i.length&amp;&amp;s.hide?i.animate(s.hide,s.hide.duration,function(){t.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),u()}):(t.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),i.hide(),u())}}))})(jQuery);(function(e){function n(t,n){var r=(t.attr("aria-describedby")||"").split(/\s+/);r.push(n),t.data("ui-tooltip-id",n).attr("aria-describedby",e.trim(r.join(" ")))}function r(t){var n=t.data("ui-tooltip-id"),r=(t.attr("aria-describedby")||"").split(/\s+/),i=e.inArray(n,r);i!==-1&amp;&amp;r.splice(i,1),t.removeData("ui-tooltip-id"),r=e.trim(r.join(" ")),r?t.attr("aria-describedby",r):t.removeAttr("aria-describedby")}var t=0;e.widget("ui.tooltip",{version:"1.9.0",options:{content:function(){return e(this).attr("title")},hide:!0,items:"[title]",position:{my:"left+15 center",at:"right center",collision:"flipfit flipfit"},show:!0,tooltipClass:null,track:!1,close:null,open:null},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={}},_setOption:function(t,n){var r=this;if(t==="disabled"){this[n?"_disable":"_enable"](),this.options[t]=n;return}this._super(t,n),t==="content"&amp;&amp;e.each(this.tooltips,function(e,t){r._updateContent(t)})},_disable:function(){var t=this;e.each(this.tooltips,function(n,r){var i=e.Event("blur");i.target=i.currentTarget=r[0],t.close(i,!0)}),this.element.find(this.options.items).andSelf().each(function(){var t=e(this);t.is("[title]")&amp;&amp;t.data("ui-tooltip-title",t.attr("title")).attr("title","")})},_enable:function(){this.element.find(this.options.items).andSelf().each(function(){var t=e(this);t.data("ui-tooltip-title")&amp;&amp;t.attr("title",t.data("ui-tooltip-title"))})},open:function(t){var n=e(t?t.target:this.element).closest(this.options.items);if(!n.length)return;if(this.options.track&amp;&amp;n.data("ui-tooltip-id")){this._find(n).position(e.extend({of:n},this.options.position)),this._off(this.document,"mousemove");return}n.attr("title")&amp;&amp;n.data("ui-tooltip-title",n.attr("title")),n.data("tooltip-open",!0),this._updateContent(n,t)},_updateContent:function(e,t){var n,r=this.options.content,i=this;if(typeof r=="string")return this._open(t,e,r);n=r.call(e[0],function(n){if(!e.data("tooltip-open"))return;i._delay(function(){this._open(t,e,n)})}),n&amp;&amp;this._open(t,e,n)},_open:function(t,r,i){function u(e){o.of=e,s.position(o)}var s,o;if(!i)return;s=this._find(r);if(s.length){s.find(".ui-tooltip-content").html(i);return}r.is("[title]")&amp;&amp;(t&amp;&amp;t.type==="mouseover"?r.attr("title",""):r.removeAttr("title")),s=this._tooltip(r),n(r,s.attr("id")),s.find(".ui-tooltip-content").html(i),this.options.track&amp;&amp;t&amp;&amp;/^mouse/.test(t.originalEvent.type)?(o=e.extend({},this.options.position),this._on(this.document,{mousemove:u}),u(t)):s.position(e.extend({of:r},this.options.position)),s.hide(),this._show(s,this.options.show),this._trigger("open",t,{tooltip:s}),this._on(r,{mouseleave:"close",focusout:"close",keyup:function(t){if(t.keyCode===e.ui.keyCode.ESCAPE){var n=e.Event(t);n.currentTarget=r[0],this.close(n,!0)}}})},close:function(t,n){var i=this,s=e(t?t.currentTarget:this.element),o=this._find(s);if(this.closing)return;if(!n&amp;&amp;t&amp;&amp;t.type!=="focusout"&amp;&amp;this.document[0].activeElement===s[0])return;s.data("ui-tooltip-title")&amp;&amp;s.attr("title",s.data("ui-tooltip-title")),r(s),o.stop(!0),this._hide(o,this.options.hide,function(){e(this).remove(),delete i.tooltips[this.id]}),s.removeData("tooltip-open"),this._off(s,"mouseleave focusout keyup"),this._off(this.document,"mousemove"),this.closing=!0,this._trigger("close",t,{tooltip:o}),this.closing=!1},_tooltip:function(n){var r="ui-tooltip-"+t++,i=e("&lt;div&gt;").attr({id:r,role:"tooltip"}).addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content "+(this.options.tooltipClass||""));return e("&lt;div&gt;").addClass("ui-tooltip-content").appendTo(i),i.appendTo(this.document[0].body),e.fn.bgiframe&amp;&amp;i.bgiframe(),this.tooltips[r]=n,i},_find:function(t){var n=t.data("ui-tooltip-id");return n?e("#"+n):e()},_destroy:function(){var t=this;e.each(this.tooltips,function(n,r){var i=e.Event("blur");i.target=i.currentTarget=r[0],t.close(i,!0),e("#"+n).remove(),r.data("ui-tooltip-title")&amp;&amp;(r.attr("title",r.data("ui-tooltip-title")),r.removeData("ui-tooltip-title"))})}})})(jQuery);jQuery.effects||function(e,t){var n=e.uiBackCompat!==!1,r="ui-effects-";e.effects={effect:{}},function(t,n){function p(e,t,n){var r=a[t.type]||{};return e==null?n||!t.def?null:t.def:(e=r.floor?~~e:parseFloat(e),isNaN(e)?t.def:r.mod?(e+r.mod)%r.mod:0&gt;e?0:r.max&lt;e?r.max:e)}function d(e){var n=o(),r=n._rgba=[];return e=e.toLowerCase(),h(s,function(t,i){var s,o=i.re.exec(e),a=o&amp;&amp;i.parse(o),f=i.space||"rgba";if(a)return s=n[f](a),n[u[f].cache]=s[u[f].cache],r=n._rgba=s._rgba,!1}),r.length?(r.join()==="0,0,0,0"&amp;&amp;t.extend(r,c.transparent),n):c[e]}function v(e,t,n){return n=(n+1)%1,n*6&lt;1?e+(t-e)*n*6:n*2&lt;1?t:n*3&lt;2?e+(t-e)*(2/3-n)*6:e}var r="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor".split(" "),i=/^([\-+])=\s*(\d+\.?\d*)/,s=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1],e[2],e[3],e[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1]*2.55,e[2]*2.55,e[3]*2.55,e[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(e){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(e){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(e){return[e[1],e[2]/100,e[3]/100,e[4]]}}],o=t.Color=function(e,n,r,i){return new t.Color.fn.parse(e,n,r,i)},u={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},a={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},f=o.support={},l=t("&lt;p&gt;")[0],c,h=t.each;l.style.cssText="background-color:rgba(1,1,1,.5)",f.rgba=l.style.backgroundColor.indexOf("rgba")&gt;-1,h(u,function(e,t){t.cache="_"+e,t.props.alpha={idx:3,type:"percent",def:1}}),o.fn=t.extend(o.prototype,{parse:function(r,i,s,a){if(r===n)return this._rgba=[null,null,null,null],this;if(r.jquery||r.nodeType)r=t(r).css(i),i=n;var f=this,l=t.type(r),v=this._rgba=[],m;i!==n&amp;&amp;(r=[r,i,s,a],l="array");if(l==="string")return this.parse(d(r)||c._default);if(l==="array")return h(u.rgba.props,function(e,t){v[t.idx]=p(r[t.idx],t)}),this;if(l==="object")return r instanceof o?h(u,function(e,t){r[t.cache]&amp;&amp;(f[t.cache]=r[t.cache].slice())}):h(u,function(t,n){var i=n.cache;h(n.props,function(e,t){if(!f[i]&amp;&amp;n.to){if(e==="alpha"||r[e]==null)return;f[i]=n.to(f._rgba)}f[i][t.idx]=p(r[e],t,!0)}),f[i]&amp;&amp;e.inArray(null,f[i].slice(0,3))&lt;0&amp;&amp;(f[i][3]=1,n.from&amp;&amp;(f._rgba=n.from(f[i])))}),this},is:function(e){var t=o(e),n=!0,r=this;return h(u,function(e,i){var s,o=t[i.cache];return o&amp;&amp;(s=r[i.cache]||i.to&amp;&amp;i.to(r._rgba)||[],h(i.props,function(e,t){if(o[t.idx]!=null)return n=o[t.idx]===s[t.idx],n})),n}),n},_space:function(){var e=[],t=this;return h(u,function(n,r){t[r.cache]&amp;&amp;e.push(n)}),e.pop()},transition:function(e,t){var n=o(e),r=n._space(),i=u[r],s=this.alpha()===0?o("transparent"):this,f=s[i.cache]||i.to(s._rgba),l=f.slice();return n=n[i.cache],h(i.props,function(e,r){var i=r.idx,s=f[i],o=n[i],u=a[r.type]||{};if(o===null)return;s===null?l[i]=o:(u.mod&amp;&amp;(o-s&gt;u.mod/2?s+=u.mod:s-o&gt;u.mod/2&amp;&amp;(s-=u.mod)),l[i]=p((o-s)*t+s,r))}),this[r](l)},blend:function(e){if(this._rgba[3]===1)return this;var n=this._rgba.slice(),r=n.pop(),i=o(e)._rgba;return o(t.map(n,function(e,t){return(1-r)*i[t]+r*e}))},toRgbaString:function(){var e="rgba(",n=t.map(this._rgba,function(e,t){return e==null?t&gt;2?1:0:e});return n[3]===1&amp;&amp;(n.pop(),e="rgb("),e+n.join()+")"},toHslaString:function(){var e="hsla(",n=t.map(this.hsla(),function(e,t){return e==null&amp;&amp;(e=t&gt;2?1:0),t&amp;&amp;t&lt;3&amp;&amp;(e=Math.round(e*100)+"%"),e});return n[3]===1&amp;&amp;(n.pop(),e="hsl("),e+n.join()+")"},toHexString:function(e){var n=this._rgba.slice(),r=n.pop();return e&amp;&amp;n.push(~~(r*255)),"#"+t.map(n,function(e,t){return e=(e||0).toString(16),e.length===1?"0"+e:e}).join("")},toString:function(){return this._rgba[3]===0?"transparent":this.toRgbaString()}}),o.fn.parse.prototype=o.fn,u.hsla.to=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/255,n=e[1]/255,r=e[2]/255,i=e[3],s=Math.max(t,n,r),o=Math.min(t,n,r),u=s-o,a=s+o,f=a*.5,l,c;return o===s?l=0:t===s?l=60*(n-r)/u+360:n===s?l=60*(r-t)/u+120:l=60*(t-n)/u+240,f===0||f===1?c=f:f&lt;=.5?c=u/a:c=u/(2-a),[Math.round(l)%360,c,f,i==null?1:i]},u.hsla.from=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/360,n=e[1],r=e[2],i=e[3],s=r&lt;=.5?r*(1+n):r+n-r*n,o=2*r-s,u,a,f;return[Math.round(v(o,s,t+1/3)*255),Math.round(v(o,s,t)*255),Math.round(v(o,s,t-1/3)*255),i]},h(u,function(e,r){var s=r.props,u=r.cache,a=r.to,f=r.from;o.fn[e]=function(e){a&amp;&amp;!this[u]&amp;&amp;(this[u]=a(this._rgba));if(e===n)return this[u].slice();var r,i=t.type(e),l=i==="array"||i==="object"?e:arguments,c=this[u].slice();return h(s,function(e,t){var n=l[i==="object"?e:t.idx];n==null&amp;&amp;(n=c[t.idx]),c[t.idx]=p(n,t)}),f?(r=o(f(c)),r[u]=c,r):o(c)},h(s,function(n,r){if(o.fn[n])return;o.fn[n]=function(s){var o=t.type(s),u=n==="alpha"?this._hsla?"hsla":"rgba":e,a=this[u](),f=a[r.idx],l;return o==="undefined"?f:(o==="function"&amp;&amp;(s=s.call(this,f),o=t.type(s)),s==null&amp;&amp;r.empty?this:(o==="string"&amp;&amp;(l=i.exec(s),l&amp;&amp;(s=f+parseFloat(l[2])*(l[1]==="+"?1:-1))),a[r.idx]=s,this[u](a)))}})}),h(r,function(e,n){t.cssHooks[n]={set:function(e,r){var i,s,u="";if(t.type(r)!=="string"||(i=d(r))){r=o(i||r);if(!f.rgba&amp;&amp;r._rgba[3]!==1){s=n==="backgroundColor"?e.parentNode:e;while((u===""||u==="transparent")&amp;&amp;s&amp;&amp;s.style)try{u=t.css(s,"backgroundColor"),s=s.parentNode}catch(a){}r=r.blend(u&amp;&amp;u!=="transparent"?u:"_default")}r=r.toRgbaString()}try{e.style[n]=r}catch(r){}}},t.fx.step[n]=function(e){e.colorInit||(e.start=o(e.elem,n),e.end=o(e.end),e.colorInit=!0),t.cssHooks[n].set(e.elem,e.start.transition(e.end,e.pos))}}),t.cssHooks.borderColor={expand:function(e){var t={};return h(["Top","Right","Bottom","Left"],function(n,r){t["border"+r+"Color"]=e}),t}},c=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(jQuery),function(){function i(){var t=this.ownerDocument.defaultView?this.ownerDocument.defaultView.getComputedStyle(this,null):this.currentStyle,n={},r,i,s;if(t&amp;&amp;t.length&amp;&amp;t[0]&amp;&amp;t[t[0]]){s=t.length;while(s--)r=t[s],typeof t[r]=="string"&amp;&amp;(n[e.camelCase(r)]=t[r])}else for(r in t)typeof t[r]=="string"&amp;&amp;(n[r]=t[r]);return n}function s(t,n){var i={},s,o;for(s in n)o=n[s],t[s]!==o&amp;&amp;!r[s]&amp;&amp;(e.fx.step[s]||!isNaN(parseFloat(o)))&amp;&amp;(i[s]=o);return i}var n=["add","remove","toggle"],r={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};e.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(t,n){e.fx.step[n]=function(e){if(e.end!=="none"&amp;&amp;!e.setAttr||e.pos===1&amp;&amp;!e.setAttr)jQuery.style(e.elem,n,e.end),e.setAttr=!0}}),e.effects.animateClass=function(t,r,o,u){var a=e.speed(r,o,u);return this.queue(function(){var r=e(this),o=r.attr("class")||"",u,f=a.children?r.find("*").andSelf():r;f=f.map(function(){var t=e(this);return{el:t,start:i.call(this)}}),u=function(){e.each(n,function(e,n){t[n]&amp;&amp;r[n+"Class"](t[n])})},u(),f=f.map(function(){return this.end=i.call(this.el[0]),this.diff=s(this.start,this.end),this}),r.attr("class",o),f=f.map(function(){var t=this,n=e.Deferred(),r=jQuery.extend({},a,{queue:!1,complete:function(){n.resolve(t)}});return this.el.animate(this.diff,r),n.promise()}),e.when.apply(e,f.get()).done(function(){u(),e.each(arguments,function(){var t=this.el;e.each(this.diff,function(e){t.css(e,"")})}),a.complete.call(r[0])})})},e.fn.extend({_addClass:e.fn.addClass,addClass:function(t,n,r,i){return n?e.effects.animateClass.call(this,{add:t},n,r,i):this._addClass(t)},_removeClass:e.fn.removeClass,removeClass:function(t,n,r,i){return n?e.effects.animateClass.call(this,{remove:t},n,r,i):this._removeClass(t)},_toggleClass:e.fn.toggleClass,toggleClass:function(n,r,i,s,o){return typeof r=="boolean"||r===t?i?e.effects.animateClass.call(this,r?{add:n}:{remove:n},i,s,o):this._toggleClass(n,r):e.effects.animateClass.call(this,{toggle:n},r,i,s)},switchClass:function(t,n,r,i,s){return e.effects.animateClass.call(this,{add:n,remove:t},r,i,s)}})}(),function(){function i(n,r,i,s){e.isPlainObject(n)&amp;&amp;(r=n,n=n.effect),n={effect:n},r===t&amp;&amp;(r={}),e.isFunction(r)&amp;&amp;(s=r,i=null,r={});if(typeof r=="number"||e.fx.speeds[r])s=i,i=r,r={};return e.isFunction(i)&amp;&amp;(s=i,i=null),r&amp;&amp;e.extend(n,r),i=i||r.duration,n.duration=e.fx.off?0:typeof i=="number"?i:i in e.fx.speeds?e.fx.speeds[i]:e.fx.speeds._default,n.complete=s||r.complete,n}function s(t){return!t||typeof t=="number"||e.fx.speeds[t]?!0:typeof t=="string"&amp;&amp;!e.effects.effect[t]?n&amp;&amp;e.effects[t]?!1:!0:!1}e.extend(e.effects,{version:"1.9.0",save:function(e,t){for(var n=0;n&lt;t.length;n++)t[n]!==null&amp;&amp;e.data(r+t[n],e[0].style[t[n]])},restore:function(e,n){var i,s;for(s=0;s&lt;n.length;s++)n[s]!==null&amp;&amp;(i=e.data(r+n[s]),i===t&amp;&amp;(i=""),e.css(n[s],i))},setMode:function(e,t){return t==="toggle"&amp;&amp;(t=e.is(":hidden")?"show":"hide"),t},getBaseline:function(e,t){var n,r;switch(e[0]){case"top":n=0;break;case"middle":n=.5;break;case"bottom":n=1;break;default:n=e[0]/t.height}switch(e[1]){case"left":r=0;break;case"center":r=.5;break;case"right":r=1;break;default:r=e[1]/t.width}return{x:r,y:n}},createWrapper:function(t){if(t.parent().is(".ui-effects-wrapper"))return t.parent();var n={width:t.outerWidth(!0),height:t.outerHeight(!0),"float":t.css("float")},r=e("&lt;div&gt;&lt;/div&gt;").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),i={width:t.width(),height:t.height()},s=document.activeElement;try{s.id}catch(o){s=document.body}return t.wrap(r),(t[0]===s||e.contains(t[0],s))&amp;&amp;e(s).focus(),r=t.parent(),t.css("position")==="static"?(r.css({position:"relative"}),t.css({position:"relative"})):(e.extend(n,{position:t.css("position"),zIndex:t.css("z-index")}),e.each(["top","left","bottom","right"],function(e,r){n[r]=t.css(r),isNaN(parseInt(n[r],10))&amp;&amp;(n[r]="auto")}),t.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),t.css(i),r.css(n).show()},removeWrapper:function(t){var n=document.activeElement;return t.parent().is(".ui-effects-wrapper")&amp;&amp;(t.parent().replaceWith(t),(t[0]===n||e.contains(t[0],n))&amp;&amp;e(n).focus()),t},setTransition:function(t,n,r,i){return i=i||{},e.each(n,function(e,n){var s=t.cssUnit(n);s[0]&gt;0&amp;&amp;(i[n]=s[0]*r+s[1])}),i}}),e.fn.extend({effect:function(t,r,s,o){function h(t){function s(){e.isFunction(r)&amp;&amp;r.call(n[0]),e.isFunction(t)&amp;&amp;t()}var n=e(this),r=u.complete,i=u.mode;(n.is(":hidden")?i==="hide":i==="show")?s():l.call(n[0],u,s)}var u=i.apply(this,arguments),a=u.mode,f=u.queue,l=e.effects.effect[u.effect],c=!l&amp;&amp;n&amp;&amp;e.effects[u.effect];return e.fx.off||!l&amp;&amp;!c?a?this[a](u.duration,u.complete):this.each(function(){u.complete&amp;&amp;u.complete.call(this)}):l?f===!1?this.each(h):this.queue(f||"fx",h):c.call(this,{options:u,duration:u.duration,callback:u.complete,mode:u.mode})},_show:e.fn.show,show:function(e){if(s(e))return this._show.apply(this,arguments);var t=i.apply(this,arguments);return t.mode="show",this.effect.call(this,t)},_hide:e.fn.hide,hide:function(e){if(s(e))return this._hide.apply(this,arguments);var t=i.apply(this,arguments);return t.mode="hide",this.effect.call(this,t)},__toggle:e.fn.toggle,toggle:function(t){if(s(t)||typeof t=="boolean"||e.isFunction(t))return this.__toggle.apply(this,arguments);var n=i.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)},cssUnit:function(t){var n=this.css(t),r=[];return e.each(["em","px","%","pt"],function(e,t){n.indexOf(t)&gt;0&amp;&amp;(r=[parseFloat(n),t])}),r}})}(),function(){var t={};e.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,n){t[n]=function(t){return Math.pow(t,e+2)}}),e.extend(t,{Sine:function(e){return 1-Math.cos(e*Math.PI/2)},Circ:function(e){return 1-Math.sqrt(1-e*e)},Elastic:function(e){return e===0||e===1?e:-Math.pow(2,8*(e-1))*Math.sin(((e-1)*80-7.5)*Math.PI/15)},Back:function(e){return e*e*(3*e-2)},Bounce:function(e){var t,n=4;while(e&lt;((t=Math.pow(2,--n))-1)/11);return 1/Math.pow(4,3-n)-7.5625*Math.pow((t*3-2)/22-e,2)}}),e.each(t,function(t,n){e.easing["easeIn"+t]=n,e.easing["easeOut"+t]=function(e){return 1-n(1-e)},e.easing["easeInOut"+t]=function(e){return e&lt;.5?n(e*2)/2:1-n(e*-2+2)/2}})}()}(jQuery);(function(e,t){var n=/up|down|vertical/,r=/up|left|vertical|horizontal/;e.effects.effect.blind=function(t,i){var s=e(this),o=["position","top","bottom","left","right","height","width"],u=e.effects.setMode(s,t.mode||"hide"),a=t.direction||"up",f=n.test(a),l=f?"height":"width",c=f?"top":"left",h=r.test(a),p={},d=u==="show",v,m,g;s.parent().is(".ui-effects-wrapper")?e.effects.save(s.parent(),o):e.effects.save(s,o),s.show(),v=e.effects.createWrapper(s).css({overflow:"hidden"}),m=v[l](),g=parseFloat(v.css(c))||0,p[l]=d?m:0,h||(s.css(f?"bottom":"right",0).css(f?"top":"left","auto").css({position:"absolute"}),p[c]=d?g:m+g),d&amp;&amp;(v.css(l,0),h||v.css(c,g+m)),v.animate(p,{duration:t.duration,easing:t.easing,queue:!1,complete:function(){u==="hide"&amp;&amp;s.hide(),e.effects.restore(s,o),e.effects.removeWrapper(s),i()}})}})(jQuery);(function(e,t){e.effects.effect.bounce=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"effect"),o=s==="hide",u=s==="show",a=t.direction||"up",f=t.distance,l=t.times||5,c=l*2+(u||o?1:0),h=t.duration/c,p=t.easing,d=a==="up"||a==="down"?"top":"left",v=a==="up"||a==="left",m,g,y,b=r.queue(),w=b.length;(u||o)&amp;&amp;i.push("opacity"),e.effects.save(r,i),r.show(),e.effects.createWrapper(r),f||(f=r[d==="top"?"outerHeight":"outerWidth"]()/3),u&amp;&amp;(y={opacity:1},y[d]=0,r.css("opacity",0).css(d,v?-f*2:f*2).animate(y,h,p)),o&amp;&amp;(f/=Math.pow(2,l-1)),y={},y[d]=0;for(m=0;m&lt;l;m++)g={},g[d]=(v?"-=":"+=")+f,r.animate(g,h,p).animate(y,h,p),f=o?f*2:f/2;o&amp;&amp;(g={opacity:0},g[d]=(v?"-=":"+=")+f,r.animate(g,h,p)),r.queue(function(){o&amp;&amp;r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}),w&gt;1&amp;&amp;b.splice.apply(b,[1,0].concat(b.splice(w,c+1))),r.dequeue()}})(jQuery);(function(e,t){e.effects.effect.clip=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=t.direction||"vertical",a=u==="vertical",f=a?"height":"width",l=a?"top":"left",c={},h,p,d;e.effects.save(r,i),r.show(),h=e.effects.createWrapper(r).css({overflow:"hidden"}),p=r[0].tagName==="IMG"?h:r,d=p[f](),o&amp;&amp;(p.css(f,0),p.css(l,d/2)),c[f]=o?d:0,c[l]=o?0:d/2,p.animate(c,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){o||r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}})(jQuery);(function(e,t){e.effects.effect.drop=function(t,n){var r=e(this),i=["position","top","bottom","left","right","opacity","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=t.direction||"left",a=u==="up"||u==="down"?"top":"left",f=u==="up"||u==="left"?"pos":"neg",l={opacity:o?1:0},c;e.effects.save(r,i),r.show(),e.effects.createWrapper(r),c=t.distance||r[a==="top"?"outerHeight":"outerWidth"](!0)/2,o&amp;&amp;r.css("opacity",0).css(a,f==="pos"?-c:c),l[a]=(o?f==="pos"?"+=":"-=":f==="pos"?"-=":"+=")+c,r.animate(l,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&amp;&amp;r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}})(jQuery);(function(e,t){e.effects.effect.explode=function(t,n){function y(){c.push(this),c.length===r*i&amp;&amp;b()}function b(){s.css({visibility:"visible"}),e(c).remove(),u||s.hide(),n()}var r=t.pieces?Math.round(Math.sqrt(t.pieces)):3,i=r,s=e(this),o=e.effects.setMode(s,t.mode||"hide"),u=o==="show",a=s.show().css("visibility","hidden").offset(),f=Math.ceil(s.outerWidth()/i),l=Math.ceil(s.outerHeight()/r),c=[],h,p,d,v,m,g;for(h=0;h&lt;r;h++){v=a.top+h*l,g=h-(r-1)/2;for(p=0;p&lt;i;p++)d=a.left+p*f,m=p-(i-1)/2,s.clone().appendTo("body").wrap("&lt;div&gt;&lt;/div&gt;").css({position:"absolute",visibility:"visible",left:-p*f,top:-h*l}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:f,height:l,left:d+(u?m*f:0),top:v+(u?g*l:0),opacity:u?0:1}).animate({left:d+(u?0:m*f),top:v+(u?0:g*l),opacity:u?1:0},t.duration||500,t.easing,y)}}})(jQuery);(function(e,t){e.effects.effect.fade=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"toggle");r.animate({opacity:i},{queue:!1,duration:t.duration,easing:t.easing,complete:n})}})(jQuery);(function(e,t){e.effects.effect.fold=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=s==="hide",a=t.size||15,f=/([0-9]+)%/.exec(a),l=!!t.horizFirst,c=o!==l,h=c?["width","height"]:["height","width"],p=t.duration/2,d,v,m={},g={};e.effects.save(r,i),r.show(),d=e.effects.createWrapper(r).css({overflow:"hidden"}),v=c?[d.width(),d.height()]:[d.height(),d.width()],f&amp;&amp;(a=parseInt(f[1],10)/100*v[u?0:1]),o&amp;&amp;d.css(l?{height:0,width:a}:{height:a,width:0}),m[h[0]]=o?v[0]:a,g[h[1]]=o?v[1]:0,d.animate(m,p,t.easing).animate(g,p,t.easing,function(){u&amp;&amp;r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()})}})(jQuery);(function(e,t){e.effects.effect.highlight=function(t,n){var r=e(this),i=["backgroundImage","backgroundColor","opacity"],s=e.effects.setMode(r,t.mode||"show"),o={backgroundColor:r.css("backgroundColor")};s==="hide"&amp;&amp;(o.opacity=0),e.effects.save(r,i),r.show().css({backgroundImage:"none",backgroundColor:t.color||"#ffff99"}).animate(o,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&amp;&amp;r.hide(),e.effects.restore(r,i),n()}})}})(jQuery);(function(e,t){e.effects.effect.pulsate=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"show"),s=i==="show",o=i==="hide",u=s||i==="hide",a=(t.times||5)*2+(u?1:0),f=t.duration/a,l=0,c=r.queue(),h=c.length,p;if(s||!r.is(":visible"))r.css("opacity",0).show(),l=1;for(p=1;p&lt;a;p++)r.animate({opacity:l},f,t.easing),l=1-l;r.animate({opacity:l},f,t.easing),r.queue(function(){o&amp;&amp;r.hide(),n()}),h&gt;1&amp;&amp;c.splice.apply(c,[1,0].concat(c.splice(h,a+1))),r.dequeue()}})(jQuery);(function(e,t){e.effects.effect.puff=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"hide"),s=i==="hide",o=parseInt(t.percent,10)||150,u=o/100,a={height:r.height(),width:r.width()};e.extend(t,{effect:"scale",queue:!1,fade:!0,mode:i,complete:n,percent:s?o:100,from:s?a:{height:a.height*u,width:a.width*u}}),r.effect(t)},e.effects.effect.scale=function(t,n){var r=e(this),i=e.extend(!0,{},t),s=e.effects.setMode(r,t.mode||"effect"),o=parseInt(t.percent,10)||(parseInt(t.percent,10)===0?0:s==="hide"?0:100),u=t.direction||"both",a=t.origin,f={height:r.height(),width:r.width(),outerHeight:r.outerHeight(),outerWidth:r.outerWidth()},l={y:u!=="horizontal"?o/100:1,x:u!=="vertical"?o/100:1};i.effect="size",i.queue=!1,i.complete=n,s!=="effect"&amp;&amp;(i.origin=a||["middle","center"],i.restore=!0),i.from=t.from||(s==="show"?{height:0,width:0}:f),i.to={height:f.height*l.y,width:f.width*l.x,outerHeight:f.outerHeight*l.y,outerWidth:f.outerWidth*l.x},i.fade&amp;&amp;(s==="show"&amp;&amp;(i.from.opacity=0,i.to.opacity=1),s==="hide"&amp;&amp;(i.from.opacity=1,i.to.opacity=0)),r.effect(i)},e.effects.effect.size=function(t,n){var r=e(this),i=["position","top","bottom","left","right","width","height","overflow","opacity"],s=["position","top","bottom","left","right","overflow","opacity"],o=["width","height","overflow"],u=["fontSize"],a=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],f=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],l=e.effects.setMode(r,t.mode||"effect"),c=t.restore||l!=="effect",h=t.scale||"both",p=t.origin||["middle","center"],d,v,m,g=r.css("position");l==="show"&amp;&amp;r.show(),d={height:r.height(),width:r.width(),outerHeight:r.outerHeight(),outerWidth:r.outerWidth()},r.from=t.from||d,r.to=t.to||d,m={from:{y:r.from.height/d.height,x:r.from.width/d.width},to:{y:r.to.height/d.height,x:r.to.width/d.width}};if(h==="box"||h==="both")m.from.y!==m.to.y&amp;&amp;(i=i.concat(a),r.from=e.effects.setTransition(r,a,m.from.y,r.from),r.to=e.effects.setTransition(r,a,m.to.y,r.to)),m.from.x!==m.to.x&amp;&amp;(i=i.concat(f),r.from=e.effects.setTransition(r,f,m.from.x,r.from),r.to=e.effects.setTransition(r,f,m.to.x,r.to));(h==="content"||h==="both")&amp;&amp;m.from.y!==m.to.y&amp;&amp;(i=i.concat(u),r.from=e.effects.setTransition(r,u,m.from.y,r.from),r.to=e.effects.setTransition(r,u,m.to.y,r.to)),e.effects.save(r,c?i:s),r.show(),e.effects.createWrapper(r),r.css("overflow","hidden").css(r.from),p&amp;&amp;(v=e.effects.getBaseline(p,d),r.from.top=(d.outerHeight-r.outerHeight())*v.y,r.from.left=(d.outerWidth-r.outerWidth())*v.x,r.to.top=(d.outerHeight-r.to.outerHeight)*v.y,r.to.left=(d.outerWidth-r.to.outerWidth)*v.x),r.css(r.from);if(h==="content"||h==="both")a=a.concat(["marginTop","marginBottom"]).concat(u),f=f.concat(["marginLeft","marginRight"]),o=i.concat(a).concat(f),r.find("*[width]").each(function(){var n=e(this),r={height:n.height(),width:n.width()};c&amp;&amp;e.effects.save(n,o),n.from={height:r.height*m.from.y,width:r.width*m.from.x},n.to={height:r.height*m.to.y,width:r.width*m.to.x},m.from.y!==m.to.y&amp;&amp;(n.from=e.effects.setTransition(n,a,m.from.y,n.from),n.to=e.effects.setTransition(n,a,m.to.y,n.to)),m.from.x!==m.to.x&amp;&amp;(n.from=e.effects.setTransition(n,f,m.from.x,n.from),n.to=e.effects.setTransition(n,f,m.to.x,n.to)),n.css(n.from),n.animate(n.to,t.duration,t.easing,function(){c&amp;&amp;e.effects.restore(n,o)})});r.animate(r.to,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){r.to.opacity===0&amp;&amp;r.css("opacity",r.from.opacity),l==="hide"&amp;&amp;r.hide(),e.effects.restore(r,c?i:s),c||(g==="static"?r.css({position:"relative",top:r.to.top,left:r.to.left}):e.each(["top","left"],function(e,t){r.css(t,function(t,n){var i=parseInt(n,10),s=e?r.to.left:r.to.top;return n==="auto"?s+"px":i+s+"px"})})),e.effects.removeWrapper(r),n()}})}})(jQuery);(function(e,t){e.effects.effect.shake=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"effect"),o=t.direction||"left",u=t.distance||20,a=t.times||3,f=a*2+1,l=Math.round(t.duration/f),c=o==="up"||o==="down"?"top":"left",h=o==="up"||o==="left",p={},d={},v={},m,g=r.queue(),y=g.length;e.effects.save(r,i),r.show(),e.effects.createWrapper(r),p[c]=(h?"-=":"+=")+u,d[c]=(h?"+=":"-=")+u*2,v[c]=(h?"-=":"+=")+u*2,r.animate(p,l,t.easing);for(m=1;m&lt;a;m++)r.animate(d,l,t.easing).animate(v,l,t.easing);r.animate(d,l,t.easing).animate(p,l/2,t.easing).queue(function(){s==="hide"&amp;&amp;r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}),y&gt;1&amp;&amp;g.splice.apply(g,[1,0].concat(g.splice(y,f+1))),r.dequeue()}})(jQuery);(function(e,t){e.effects.effect.slide=function(t,n){var r=e(this),i=["position","top","bottom","left","right","width","height"],s=e.effects.setMode(r,t.mode||"show"),o=s==="show",u=t.direction||"left",a=u==="up"||u==="down"?"top":"left",f=u==="up"||u==="left",l,c={};e.effects.save(r,i),r.show(),l=t.distance||r[a==="top"?"outerHeight":"outerWidth"](!0),e.effects.createWrapper(r).css({overflow:"hidden"}),o&amp;&amp;r.css(a,f?isNaN(l)?"-"+l:-l:l),c[a]=(o?f?"+=":"-=":f?"-=":"+=")+l,r.animate(c,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&amp;&amp;r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}})(jQuery);(function(e,t){e.effects.effect.transfer=function(t,n){var r=e(this),i=e(t.to),s=i.css("position")==="fixed",o=e("body"),u=s?o.scrollTop():0,a=s?o.scrollLeft():0,f=i.offset(),l={top:f.top-u,left:f.left-a,height:i.innerHeight(),width:i.innerWidth()},c=r.offset(),h=e('&lt;div class="ui-effects-transfer"&gt;&lt;/div&gt;').appendTo(document.body).addClass(t.className).css({top:c.top-u,left:c.left-a,height:r.innerHeight(),width:r.innerWidth(),position:s?"fixed":"absolute"}).animate(l,t.duration,t.easing,function(){h.remove(),n()})}})(jQuery);;
(function($){var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.toJSON=typeof JSON==='object'&amp;&amp;JSON.stringify?JSON.stringify:function(o){if(o===null){return'null';}
var type=typeof o;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,day=o.getUTCDate(),year=o.getUTCFullYear(),hours=o.getUTCHours(),minutes=o.getUTCMinutes(),seconds=o.getUTCSeconds(),milli=o.getUTCMilliseconds();if(month&lt;10){month='0'+month;}
if(day&lt;10){day='0'+day;}
if(hours&lt;10){hours='0'+hours;}
if(minutes&lt;10){minutes='0'+minutes;}
if(seconds&lt;10){seconds='0'+seconds;}
if(milli&lt;100){milli='0'+milli;}
if(milli&lt;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&lt;o.length;i++){ret.push($.toJSON(o[i])||'null');}
return'['+ret.join(',')+']';}
var name,val,pairs=[];for(var k in o){type=typeof k;if(type==='number'){name='"'+k+'"';}else if(type==='string'){name=$.quoteString(k);}else{continue;}
type=typeof o[k];if(type==='function'||type==='undefined'){continue;}
val=$.toJSON(o[k]);pairs.push(name+':'+val);}
return'{'+pairs.join(',')+'}';}};$.evalJSON=typeof JSON==='object'&amp;&amp;JSON.parse?JSON.parse:function(src){return eval('('+src+')');};$.secureEvalJSON=typeof JSON==='object'&amp;&amp;JSON.parse?JSON.parse:function(src){var filtered=src.replace(/\\["\\\/bfnrtu]/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').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+'"';};})(jQuery);;/*!
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function(g){var q={vertical:!1,rtl:!1,start:1,offset:1,size:null,scroll:3,visible:null,animation:"normal",easing:"swing",auto:0,wrap:null,initCallback:null,setupCallback:null,reloadCallback:null,itemLoadCallback:null,itemFirstInCallback:null,itemFirstOutCallback:null,itemLastInCallback:null,itemLastOutCallback:null,itemVisibleInCallback:null,itemVisibleOutCallback:null,animationStepCallback:null,buttonNextHTML:"&lt;div&gt;&lt;/div&gt;",buttonPrevHTML:"&lt;div&gt;&lt;/div&gt;",buttonNextEvent:"click",buttonPrevEvent:"click", buttonNextCallback:null,buttonPrevCallback:null,itemFallbackDimension:null},m=!1;g(window).bind("load.jcarousel",function(){m=!0});g.jcarousel=function(a,c){this.options=g.extend({},q,c||{});this.autoStopped=this.locked=!1;this.buttonPrevState=this.buttonNextState=this.buttonPrev=this.buttonNext=this.list=this.clip=this.container=null;if(!c||c.rtl===void 0)this.options.rtl=(g(a).attr("dir")||g("html").attr("dir")||"").toLowerCase()=="rtl";this.wh=!this.options.vertical?"width":"height";this.lt=!this.options.vertical? this.options.rtl?"right":"left":"top";for(var b="",d=a.className.split(" "),f=0;f&lt;d.length;f++)if(d[f].indexOf("jcarousel-skin")!=-1){g(a).removeClass(d[f]);b=d[f];break}a.nodeName.toUpperCase()=="UL"||a.nodeName.toUpperCase()=="OL"?(this.list=g(a),this.clip=this.list.parents(".jcarousel-clip"),this.container=this.list.parents(".jcarousel-container")):(this.container=g(a),this.list=this.container.find("ul,ol").eq(0),this.clip=this.container.find(".jcarousel-clip"));if(this.clip.size()===0)this.clip= this.list.wrap("&lt;div&gt;&lt;/div&gt;").parent();if(this.container.size()===0)this.container=this.clip.wrap("&lt;div&gt;&lt;/div&gt;").parent();b!==""&amp;&amp;this.container.parent()[0].className.indexOf("jcarousel-skin")==-1&amp;&amp;this.container.wrap('&lt;div class=" '+b+'"&gt;&lt;/div&gt;');this.buttonPrev=g(".jcarousel-prev",this.container);if(this.buttonPrev.size()===0&amp;&amp;this.options.buttonPrevHTML!==null)this.buttonPrev=g(this.options.buttonPrevHTML).appendTo(this.container);this.buttonPrev.addClass(this.className("jcarousel-prev"));this.buttonNext= g(".jcarousel-next",this.container);if(this.buttonNext.size()===0&amp;&amp;this.options.buttonNextHTML!==null)this.buttonNext=g(this.options.buttonNextHTML).appendTo(this.container);this.buttonNext.addClass(this.className("jcarousel-next"));this.clip.addClass(this.className("jcarousel-clip")).css({position:"relative"});this.list.addClass(this.className("jcarousel-list")).css({overflow:"hidden",position:"relative",top:0,margin:0,padding:0}).css(this.options.rtl?"right":"left",0);this.container.addClass(this.className("jcarousel-container")).css({position:"relative"}); !this.options.vertical&amp;&amp;this.options.rtl&amp;&amp;this.container.addClass("jcarousel-direction-rtl").attr("dir","rtl");var j=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible):null,b=this.list.children("li"),e=this;if(b.size()&gt;0){var h=0,i=this.options.offset;b.each(function(){e.format(this,i++);h+=e.dimension(this,j)});this.list.css(this.wh,h+100+"px");if(!c||c.size===void 0)this.options.size=b.size()}this.container.css("display","block");this.buttonNext.css("display","block");this.buttonPrev.css("display", "block");this.funcNext=function(){e.next()};this.funcPrev=function(){e.prev()};this.funcResize=function(){e.resizeTimer&amp;&amp;clearTimeout(e.resizeTimer);e.resizeTimer=setTimeout(function(){e.reload()},100)};this.options.initCallback!==null&amp;&amp;this.options.initCallback(this,"init");!m&amp;&amp;g.browser.safari?(this.buttons(!1,!1),g(window).bind("load.jcarousel",function(){e.setup()})):this.setup()};var f=g.jcarousel;f.fn=f.prototype={jcarousel:"0.2.8"};f.fn.extend=f.extend=g.extend;f.fn.extend({setup:function(){this.prevLast= this.prevFirst=this.last=this.first=null;this.animating=!1;this.tail=this.resizeTimer=this.timer=null;this.inTail=!1;if(!this.locked){this.list.css(this.lt,this.pos(this.options.offset)+"px");var a=this.pos(this.options.start,!0);this.prevFirst=this.prevLast=null;this.animate(a,!1);g(window).unbind("resize.jcarousel",this.funcResize).bind("resize.jcarousel",this.funcResize);this.options.setupCallback!==null&amp;&amp;this.options.setupCallback(this)}},reset:function(){this.list.empty();this.list.css(this.lt, "0px");this.list.css(this.wh,"10px");this.options.initCallback!==null&amp;&amp;this.options.initCallback(this,"reset");this.setup()},reload:function(){this.tail!==null&amp;&amp;this.inTail&amp;&amp;this.list.css(this.lt,f.intval(this.list.css(this.lt))+this.tail);this.tail=null;this.inTail=!1;this.options.reloadCallback!==null&amp;&amp;this.options.reloadCallback(this);if(this.options.visible!==null){var a=this,c=Math.ceil(this.clipping()/this.options.visible),b=0,d=0;this.list.children("li").each(function(f){b+=a.dimension(this, c);f+1&lt;a.first&amp;&amp;(d=b)});this.list.css(this.wh,b+"px");this.list.css(this.lt,-d+"px")}this.scroll(this.first,!1)},lock:function(){this.locked=!0;this.buttons()},unlock:function(){this.locked=!1;this.buttons()},size:function(a){if(a!==void 0)this.options.size=a,this.locked||this.buttons();return this.options.size},has:function(a,c){if(c===void 0||!c)c=a;if(this.options.size!==null&amp;&amp;c&gt;this.options.size)c=this.options.size;for(var b=a;b&lt;=c;b++){var d=this.get(b);if(!d.length||d.hasClass("jcarousel-item-placeholder"))return!1}return!0}, get:function(a){return g("&gt;.jcarousel-item-"+a,this.list)},add:function(a,c){var b=this.get(a),d=0,p=g(c);if(b.length===0)for(var j,e=f.intval(a),b=this.create(a);;){if(j=this.get(--e),e&lt;=0||j.length){e&lt;=0?this.list.prepend(b):j.after(b);break}}else d=this.dimension(b);p.get(0).nodeName.toUpperCase()=="LI"?(b.replaceWith(p),b=p):b.empty().append(c);this.format(b.removeClass(this.className("jcarousel-item-placeholder")),a);p=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible): null;d=this.dimension(b,p)-d;a&gt;0&amp;&amp;a&lt;this.first&amp;&amp;this.list.css(this.lt,f.intval(this.list.css(this.lt))-d+"px");this.list.css(this.wh,f.intval(this.list.css(this.wh))+d+"px");return b},remove:function(a){var c=this.get(a);if(c.length&amp;&amp;!(a&gt;=this.first&amp;&amp;a&lt;=this.last)){var b=this.dimension(c);a&lt;this.first&amp;&amp;this.list.css(this.lt,f.intval(this.list.css(this.lt))+b+"px");c.remove();this.list.css(this.wh,f.intval(this.list.css(this.wh))-b+"px")}},next:function(){this.tail!==null&amp;&amp;!this.inTail?this.scrollTail(!1): this.scroll((this.options.wrap=="both"||this.options.wrap=="last")&amp;&amp;this.options.size!==null&amp;&amp;this.last==this.options.size?1:this.first+this.options.scroll)},prev:function(){this.tail!==null&amp;&amp;this.inTail?this.scrollTail(!0):this.scroll((this.options.wrap=="both"||this.options.wrap=="first")&amp;&amp;this.options.size!==null&amp;&amp;this.first==1?this.options.size:this.first-this.options.scroll)},scrollTail:function(a){if(!this.locked&amp;&amp;!this.animating&amp;&amp;this.tail){this.pauseAuto();var c=f.intval(this.list.css(this.lt)), c=!a?c-this.tail:c+this.tail;this.inTail=!a;this.prevFirst=this.first;this.prevLast=this.last;this.animate(c)}},scroll:function(a,c){!this.locked&amp;&amp;!this.animating&amp;&amp;(this.pauseAuto(),this.animate(this.pos(a),c))},pos:function(a,c){var b=f.intval(this.list.css(this.lt));if(this.locked||this.animating)return b;this.options.wrap!="circular"&amp;&amp;(a=a&lt;1?1:this.options.size&amp;&amp;a&gt;this.options.size?this.options.size:a);for(var d=this.first&gt;a,g=this.options.wrap!="circular"&amp;&amp;this.first&lt;=1?1:this.first,j=d?this.get(g): this.get(this.last),e=d?g:g-1,h=null,i=0,k=!1,l=0;d?--e&gt;=a:++e&lt;a;){h=this.get(e);k=!h.length;if(h.length===0&amp;&amp;(h=this.create(e).addClass(this.className("jcarousel-item-placeholder")),j[d?"before":"after"](h),this.first!==null&amp;&amp;this.options.wrap=="circular"&amp;&amp;this.options.size!==null&amp;&amp;(e&lt;=0||e&gt;this.options.size)))j=this.get(this.index(e)),j.length&amp;&amp;(h=this.add(e,j.clone(!0)));j=h;l=this.dimension(h);k&amp;&amp;(i+=l);if(this.first!==null&amp;&amp;(this.options.wrap=="circular"||e&gt;=1&amp;&amp;(this.options.size===null||e&lt;= this.options.size)))b=d?b+l:b-l}for(var g=this.clipping(),m=[],o=0,n=0,j=this.get(a-1),e=a;++o;){h=this.get(e);k=!h.length;if(h.length===0){h=this.create(e).addClass(this.className("jcarousel-item-placeholder"));if(j.length===0)this.list.prepend(h);else j[d?"before":"after"](h);if(this.first!==null&amp;&amp;this.options.wrap=="circular"&amp;&amp;this.options.size!==null&amp;&amp;(e&lt;=0||e&gt;this.options.size))j=this.get(this.index(e)),j.length&amp;&amp;(h=this.add(e,j.clone(!0)))}j=h;l=this.dimension(h);if(l===0)throw Error("jCarousel: No width/height set for items. This will cause an infinite loop. Aborting..."); this.options.wrap!="circular"&amp;&amp;this.options.size!==null&amp;&amp;e&gt;this.options.size?m.push(h):k&amp;&amp;(i+=l);n+=l;if(n&gt;=g)break;e++}for(h=0;h&lt;m.length;h++)m[h].remove();i&gt;0&amp;&amp;(this.list.css(this.wh,this.dimension(this.list)+i+"px"),d&amp;&amp;(b-=i,this.list.css(this.lt,f.intval(this.list.css(this.lt))-i+"px")));i=a+o-1;if(this.options.wrap!="circular"&amp;&amp;this.options.size&amp;&amp;i&gt;this.options.size)i=this.options.size;if(e&gt;i){o=0;e=i;for(n=0;++o;){h=this.get(e--);if(!h.length)break;n+=this.dimension(h);if(n&gt;=g)break}}e=i-o+ 1;this.options.wrap!="circular"&amp;&amp;e&lt;1&amp;&amp;(e=1);if(this.inTail&amp;&amp;d)b+=this.tail,this.inTail=!1;this.tail=null;if(this.options.wrap!="circular"&amp;&amp;i==this.options.size&amp;&amp;i-o+1&gt;=1&amp;&amp;(d=f.intval(this.get(i).css(!this.options.vertical?"marginRight":"marginBottom")),n-d&gt;g))this.tail=n-g-d;if(c&amp;&amp;a===this.options.size&amp;&amp;this.tail)b-=this.tail,this.inTail=!0;for(;a-- &gt;e;)b+=this.dimension(this.get(a));this.prevFirst=this.first;this.prevLast=this.last;this.first=e;this.last=i;return b},animate:function(a,c){if(!this.locked&amp;&amp; !this.animating){this.animating=!0;var b=this,d=function(){b.animating=!1;a===0&amp;&amp;b.list.css(b.lt,0);!b.autoStopped&amp;&amp;(b.options.wrap=="circular"||b.options.wrap=="both"||b.options.wrap=="last"||b.options.size===null||b.last&lt;b.options.size||b.last==b.options.size&amp;&amp;b.tail!==null&amp;&amp;!b.inTail)&amp;&amp;b.startAuto();b.buttons();b.notify("onAfterAnimation");if(b.options.wrap=="circular"&amp;&amp;b.options.size!==null)for(var c=b.prevFirst;c&lt;=b.prevLast;c++)c!==null&amp;&amp;!(c&gt;=b.first&amp;&amp;c&lt;=b.last)&amp;&amp;(c&lt;1||c&gt;b.options.size)&amp;&amp;b.remove(c)}; this.notify("onBeforeAnimation");if(!this.options.animation||c===!1)this.list.css(this.lt,a+"px"),d();else{var f=!this.options.vertical?this.options.rtl?{right:a}:{left:a}:{top:a},d={duration:this.options.animation,easing:this.options.easing,complete:d};if(g.isFunction(this.options.animationStepCallback))d.step=this.options.animationStepCallback;this.list.animate(f,d)}}},startAuto:function(a){if(a!==void 0)this.options.auto=a;if(this.options.auto===0)return this.stopAuto();if(this.timer===null){this.autoStopped= !1;var c=this;this.timer=window.setTimeout(function(){c.next()},this.options.auto*1E3)}},stopAuto:function(){this.pauseAuto();this.autoStopped=!0},pauseAuto:function(){if(this.timer!==null)window.clearTimeout(this.timer),this.timer=null},buttons:function(a,c){if(a==null&amp;&amp;(a=!this.locked&amp;&amp;this.options.size!==0&amp;&amp;(this.options.wrap&amp;&amp;this.options.wrap!="first"||this.options.size===null||this.last&lt;this.options.size),!this.locked&amp;&amp;(!this.options.wrap||this.options.wrap=="first")&amp;&amp;this.options.size!==null&amp;&amp; this.last&gt;=this.options.size))a=this.tail!==null&amp;&amp;!this.inTail;if(c==null&amp;&amp;(c=!this.locked&amp;&amp;this.options.size!==0&amp;&amp;(this.options.wrap&amp;&amp;this.options.wrap!="last"||this.first&gt;1),!this.locked&amp;&amp;(!this.options.wrap||this.options.wrap=="last")&amp;&amp;this.options.size!==null&amp;&amp;this.first==1))c=this.tail!==null&amp;&amp;this.inTail;var b=this;this.buttonNext.size()&gt;0?(this.buttonNext.unbind(this.options.buttonNextEvent+".jcarousel",this.funcNext),a&amp;&amp;this.buttonNext.bind(this.options.buttonNextEvent+".jcarousel",this.funcNext), this.buttonNext[a?"removeClass":"addClass"](this.className("jcarousel-next-disabled")).attr("disabled",a?!1:!0),this.options.buttonNextCallback!==null&amp;&amp;this.buttonNext.data("jcarouselstate")!=a&amp;&amp;this.buttonNext.each(function(){b.options.buttonNextCallback(b,this,a)}).data("jcarouselstate",a)):this.options.buttonNextCallback!==null&amp;&amp;this.buttonNextState!=a&amp;&amp;this.options.buttonNextCallback(b,null,a);this.buttonPrev.size()&gt;0?(this.buttonPrev.unbind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev), c&amp;&amp;this.buttonPrev.bind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev),this.buttonPrev[c?"removeClass":"addClass"](this.className("jcarousel-prev-disabled")).attr("disabled",c?!1:!0),this.options.buttonPrevCallback!==null&amp;&amp;this.buttonPrev.data("jcarouselstate")!=c&amp;&amp;this.buttonPrev.each(function(){b.options.buttonPrevCallback(b,this,c)}).data("jcarouselstate",c)):this.options.buttonPrevCallback!==null&amp;&amp;this.buttonPrevState!=c&amp;&amp;this.options.buttonPrevCallback(b,null,c);this.buttonNextState= a;this.buttonPrevState=c},notify:function(a){var c=this.prevFirst===null?"init":this.prevFirst&lt;this.first?"next":"prev";this.callback("itemLoadCallback",a,c);this.prevFirst!==this.first&amp;&amp;(this.callback("itemFirstInCallback",a,c,this.first),this.callback("itemFirstOutCallback",a,c,this.prevFirst));this.prevLast!==this.last&amp;&amp;(this.callback("itemLastInCallback",a,c,this.last),this.callback("itemLastOutCallback",a,c,this.prevLast));this.callback("itemVisibleInCallback",a,c,this.first,this.last,this.prevFirst, this.prevLast);this.callback("itemVisibleOutCallback",a,c,this.prevFirst,this.prevLast,this.first,this.last)},callback:function(a,c,b,d,f,j,e){if(!(this.options[a]==null||typeof this.options[a]!="object"&amp;&amp;c!="onAfterAnimation")){var h=typeof this.options[a]=="object"?this.options[a][c]:this.options[a];if(g.isFunction(h)){var i=this;if(d===void 0)h(i,b,c);else if(f===void 0)this.get(d).each(function(){h(i,this,d,b,c)});else for(var a=function(a){i.get(a).each(function(){h(i,this,a,b,c)})},k=d;k&lt;=f;k++)k!== null&amp;&amp;!(k&gt;=j&amp;&amp;k&lt;=e)&amp;&amp;a(k)}}},create:function(a){return this.format("&lt;li&gt;&lt;/li&gt;",a)},format:function(a,c){for(var a=g(a),b=a.get(0).className.split(" "),d=0;d&lt;b.length;d++)b[d].indexOf("jcarousel-")!=-1&amp;&amp;a.removeClass(b[d]);a.addClass(this.className("jcarousel-item")).addClass(this.className("jcarousel-item-"+c)).css({"float":this.options.rtl?"right":"left","list-style":"none"}).attr("jcarouselindex",c);return a},className:function(a){return a+" "+a+(!this.options.vertical?"-horizontal":"-vertical")}, dimension:function(a,c){var b=g(a);if(c==null)return!this.options.vertical?b.outerWidth(!0)||f.intval(this.options.itemFallbackDimension):b.outerHeight(!0)||f.intval(this.options.itemFallbackDimension);else{var d=!this.options.vertical?c-f.intval(b.css("marginLeft"))-f.intval(b.css("marginRight")):c-f.intval(b.css("marginTop"))-f.intval(b.css("marginBottom"));g(b).css(this.wh,d+"px");return this.dimension(b)}},clipping:function(){return!this.options.vertical?this.clip[0].offsetWidth-f.intval(this.clip.css("borderLeftWidth"))- f.intval(this.clip.css("borderRightWidth")):this.clip[0].offsetHeight-f.intval(this.clip.css("borderTopWidth"))-f.intval(this.clip.css("borderBottomWidth"))},index:function(a,c){if(c==null)c=this.options.size;return Math.round(((a-1)/c-Math.floor((a-1)/c))*c)+1}});f.extend({defaults:function(a){return g.extend(q,a||{})},intval:function(a){a=parseInt(a,10);return isNaN(a)?0:a},windowLoaded:function(){m=!0}});g.fn.jcarousel=function(a){if(typeof a=="string"){var c=g(this).data("jcarousel"),b=Array.prototype.slice.call(arguments, 1);return c[a].apply(c,b)}else return this.each(function(){var b=g(this).data("jcarousel");b?(a&amp;&amp;g.extend(b.options,a),b.reload()):g(this).data("jcarousel",new f(this,a))})}})(jQuery);
;/*
 * SimpleModal 1.4.3 - jQuery Plugin
 * http://simplemodal.com/
 * Copyright (c) 2012 Eric Martin
 * Licensed under MIT and GPL
 * Date: Sat, Sep 8 2012 07:52:31 -0700
 */
(function(b){"function"===typeof define&amp;&amp;define.amd?define(["jquery"],b):b(jQuery)})(function(b){var j=[],l=b(document),m=b.browser.msie&amp;&amp;6===parseInt(b.browser.version)&amp;&amp;"object"!==typeof window.XMLHttpRequest,o=b.browser.msie&amp;&amp;7===parseInt(b.browser.version),n=null,k=b(window),h=[];b.modal=function(a,d){return b.modal.impl.init(a,d)};b.modal.close=function(){b.modal.impl.close()};b.modal.focus=function(a){b.modal.impl.focus(a)};b.modal.setContainerDimensions=function(){b.modal.impl.setContainerDimensions()};
b.modal.setPosition=function(){b.modal.impl.setPosition()};b.modal.update=function(a,d){b.modal.impl.update(a,d)};b.fn.modal=function(a){return b.modal.impl.init(this,a)};b.modal.defaults={appendTo:"body",focus:!0,opacity:50,overlayId:"simplemodal-overlay",overlayCss:{},containerId:"simplemodal-container",containerCss:{},dataId:"simplemodal-data",dataCss:{},minHeight:null,minWidth:null,maxHeight:null,maxWidth:null,autoResize:!1,autoPosition:!0,zIndex:1E3,close:!0,closeHTML:'&lt;a class="modalCloseImg" title="Close"&gt;&lt;/a&gt;',
closeClass:"simplemodal-close",escClose:!0,overlayClose:!1,fixed:!0,position:null,persist:!1,modal:!0,onOpen:null,onShow:null,onClose:null};b.modal.impl={d:{},init:function(a,d){if(this.d.data)return!1;n=b.browser.msie&amp;&amp;!b.support.boxModel;this.o=b.extend({},b.modal.defaults,d);this.zIndex=this.o.zIndex;this.occb=!1;if("object"===typeof a){if(a=a instanceof b?a:b(a),this.d.placeholder=!1,0&lt;a.parent().parent().size()&amp;&amp;(a.before(b("&lt;span&gt;&lt;/span&gt;").attr("id","simplemodal-placeholder").css({display:"none"})),
this.d.placeholder=!0,this.display=a.css("display"),!this.o.persist))this.d.orig=a.clone(!0)}else if("string"===typeof a||"number"===typeof a)a=b("&lt;div&gt;&lt;/div&gt;").html(a);else return alert("SimpleModal Error: Unsupported data type: "+typeof a),this;this.create(a);this.open();b.isFunction(this.o.onShow)&amp;&amp;this.o.onShow.apply(this,[this.d]);return this},create:function(a){this.getDimensions();if(this.o.modal&amp;&amp;m)this.d.iframe=b('&lt;iframe src="javascript:false;"&gt;&lt;/iframe&gt;').css(b.extend(this.o.iframeCss,
{display:"none",opacity:0,position:"fixed",height:h[0],width:h[1],zIndex:this.o.zIndex,top:0,left:0})).appendTo(this.o.appendTo);this.d.overlay=b("&lt;div&gt;&lt;/div&gt;").attr("id",this.o.overlayId).addClass("simplemodal-overlay").css(b.extend(this.o.overlayCss,{display:"none",opacity:this.o.opacity/100,height:this.o.modal?j[0]:0,width:this.o.modal?j[1]:0,position:"fixed",left:0,top:0,zIndex:this.o.zIndex+1})).appendTo(this.o.appendTo);this.d.container=b("&lt;div&gt;&lt;/div&gt;").attr("id",this.o.containerId).addClass("simplemodal-container").css(b.extend({position:this.o.fixed?
"fixed":"absolute"},this.o.containerCss,{display:"none",zIndex:this.o.zIndex+2})).append(this.o.close&amp;&amp;this.o.closeHTML?b(this.o.closeHTML).addClass(this.o.closeClass):"").appendTo(this.o.appendTo);this.d.wrap=b("&lt;div&gt;&lt;/div&gt;").attr("tabIndex",-1).addClass("simplemodal-wrap").css({height:"100%",outline:0,width:"100%"}).appendTo(this.d.container);this.d.data=a.attr("id",a.attr("id")||this.o.dataId).addClass("simplemodal-data").css(b.extend(this.o.dataCss,{display:"none"})).appendTo("body");this.setContainerDimensions();
this.d.data.appendTo(this.d.wrap);(m||n)&amp;&amp;this.fixIE()},bindEvents:function(){var a=this;b("."+a.o.closeClass).bind("click.simplemodal",function(b){b.preventDefault();a.close()});a.o.modal&amp;&amp;a.o.close&amp;&amp;a.o.overlayClose&amp;&amp;a.d.overlay.bind("click.simplemodal",function(b){b.preventDefault();a.close()});l.bind("keydown.simplemodal",function(b){a.o.modal&amp;&amp;9===b.keyCode?a.watchTab(b):a.o.close&amp;&amp;a.o.escClose&amp;&amp;27===b.keyCode&amp;&amp;(b.preventDefault(),a.close())});k.bind("resize.simplemodal orientationchange.simplemodal",
function(){a.getDimensions();a.o.autoResize?a.setContainerDimensions():a.o.autoPosition&amp;&amp;a.setPosition();m||n?a.fixIE():a.o.modal&amp;&amp;(a.d.iframe&amp;&amp;a.d.iframe.css({height:h[0],width:h[1]}),a.d.overlay.css({height:j[0],width:j[1]}))})},unbindEvents:function(){b("."+this.o.closeClass).unbind("click.simplemodal");l.unbind("keydown.simplemodal");k.unbind(".simplemodal");this.d.overlay.unbind("click.simplemodal")},fixIE:function(){var a=this.o.position;b.each([this.d.iframe||null,!this.o.modal?null:this.d.overlay,
"fixed"===this.d.container.css("position")?this.d.container:null],function(b,f){if(f){var g=f[0].style;g.position="absolute";if(2&gt;b)g.removeExpression("height"),g.removeExpression("width"),g.setExpression("height",'document.body.scrollHeight &gt; document.body.clientHeight ? document.body.scrollHeight : document.body.clientHeight + "px"'),g.setExpression("width",'document.body.scrollWidth &gt; document.body.clientWidth ? document.body.scrollWidth : document.body.clientWidth + "px"');else{var c,e;a&amp;&amp;a.constructor===
Array?(c=a[0]?"number"===typeof a[0]?a[0].toString():a[0].replace(/px/,""):f.css("top").replace(/px/,""),c=-1===c.indexOf("%")?c+' + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"':parseInt(c.replace(/%/,""))+' * ((document.documentElement.clientHeight || document.body.clientHeight) / 100) + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"',a[1]&amp;&amp;(e="number"===typeof a[1]?
a[1].toString():a[1].replace(/px/,""),e=-1===e.indexOf("%")?e+' + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"':parseInt(e.replace(/%/,""))+' * ((document.documentElement.clientWidth || document.body.clientWidth) / 100) + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"')):(c='(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"',
e='(document.documentElement.clientWidth || document.body.clientWidth) / 2 - (this.offsetWidth / 2) + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"');g.removeExpression("top");g.removeExpression("left");g.setExpression("top",c);g.setExpression("left",e)}}})},focus:function(a){var d=this,a=a&amp;&amp;-1!==b.inArray(a,["first","last"])?a:"first",f=b(":input:enabled:visible:"+a,d.d.wrap);setTimeout(function(){0&lt;f.length?f.focus():d.d.wrap.focus()},
10)},getDimensions:function(){var a="undefined"===typeof window.innerHeight?k.height():window.innerHeight;j=[l.height(),l.width()];h=[a,k.width()]},getVal:function(a,b){return a?"number"===typeof a?a:"auto"===a?0:0&lt;a.indexOf("%")?parseInt(a.replace(/%/,""))/100*("h"===b?h[0]:h[1]):parseInt(a.replace(/px/,"")):null},update:function(a,b){if(!this.d.data)return!1;this.d.origHeight=this.getVal(a,"h");this.d.origWidth=this.getVal(b,"w");this.d.data.hide();a&amp;&amp;this.d.container.css("height",a);b&amp;&amp;this.d.container.css("width",
b);this.setContainerDimensions();this.d.data.show();this.o.focus&amp;&amp;this.focus();this.unbindEvents();this.bindEvents()},setContainerDimensions:function(){var a=m||o,d=this.d.origHeight?this.d.origHeight:b.browser.opera?this.d.container.height():this.getVal(a?this.d.container[0].currentStyle.height:this.d.container.css("height"),"h"),a=this.d.origWidth?this.d.origWidth:b.browser.opera?this.d.container.width():this.getVal(a?this.d.container[0].currentStyle.width:this.d.container.css("width"),"w"),f=this.d.data.outerHeight(!0),
g=this.d.data.outerWidth(!0);this.d.origHeight=this.d.origHeight||d;this.d.origWidth=this.d.origWidth||a;var c=this.o.maxHeight?this.getVal(this.o.maxHeight,"h"):null,e=this.o.maxWidth?this.getVal(this.o.maxWidth,"w"):null,c=c&amp;&amp;c&lt;h[0]?c:h[0],e=e&amp;&amp;e&lt;h[1]?e:h[1],i=this.o.minHeight?this.getVal(this.o.minHeight,"h"):"auto",d=d?this.o.autoResize&amp;&amp;d&gt;c?c:d&lt;i?i:d:f?f&gt;c?c:this.o.minHeight&amp;&amp;"auto"!==i&amp;&amp;f&lt;i?i:f:i,c=this.o.minWidth?this.getVal(this.o.minWidth,"w"):"auto",a=a?this.o.autoResize&amp;&amp;a&gt;e?e:a&lt;c?c:a:
g?g&gt;e?e:this.o.minWidth&amp;&amp;"auto"!==c&amp;&amp;g&lt;c?c:g:c;this.d.container.css({height:d,width:a});this.d.wrap.css({overflow:f&gt;d||g&gt;a?"auto":"visible"});this.o.autoPosition&amp;&amp;this.setPosition()},setPosition:function(){var a,b;a=h[0]/2-this.d.container.outerHeight(!0)/2;b=h[1]/2-this.d.container.outerWidth(!0)/2;var f="fixed"!==this.d.container.css("position")?k.scrollTop():0;this.o.position&amp;&amp;"[object Array]"===Object.prototype.toString.call(this.o.position)?(a=f+(this.o.position[0]||a),b=this.o.position[1]||
b):a=f+a;this.d.container.css({left:b,top:a})},watchTab:function(a){if(0&lt;b(a.target).parents(".simplemodal-container").length){if(this.inputs=b(":input:enabled:visible:first, :input:enabled:visible:last",this.d.data[0]),!a.shiftKey&amp;&amp;a.target===this.inputs[this.inputs.length-1]||a.shiftKey&amp;&amp;a.target===this.inputs[0]||0===this.inputs.length)a.preventDefault(),this.focus(a.shiftKey?"last":"first")}else a.preventDefault(),this.focus()},open:function(){this.d.iframe&amp;&amp;this.d.iframe.show();b.isFunction(this.o.onOpen)?
this.o.onOpen.apply(this,[this.d]):(this.d.overlay.show(),this.d.container.show(),this.d.data.show());this.o.focus&amp;&amp;this.focus();this.bindEvents()},close:function(){if(!this.d.data)return!1;this.unbindEvents();if(b.isFunction(this.o.onClose)&amp;&amp;!this.occb)this.occb=!0,this.o.onClose.apply(this,[this.d]);else{if(this.d.placeholder){var a=b("#simplemodal-placeholder");this.o.persist?a.replaceWith(this.d.data.removeClass("simplemodal-data").css("display",this.display)):(this.d.data.hide().remove(),a.replaceWith(this.d.orig))}else this.d.data.hide().remove();
this.d.container.hide().remove();this.d.overlay.hide();this.d.iframe&amp;&amp;this.d.iframe.hide().remove();this.d.overlay.remove();this.d={}}}}});
;/*
 *
 * Copyright (c) 2006-2011 Sam Collett (http://www.texotela.co.uk)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * Version 1.3
 * Demo: http://www.texotela.co.uk/code/jquery/numeric/
 *
 */
(function($) {
/*
 * Allows only valid characters to be entered into input boxes.
 * Note: fixes value when pasting via Ctrl+V, but not when using the mouse to paste
  *      side-effect: Ctrl+A does not work, though you can still use the mouse to select (or double-click to select all)
 *
 * @name     numeric
 * @param    config      { decimal : "." , negative : true }
 * @param    callback     A function that runs if the number is not valid (fires onblur)
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @example  $(".numeric").numeric();
 * @example  $(".numeric").numeric(","); // use , as separater
 * @example  $(".numeric").numeric({ decimal : "," }); // use , as separator
 * @example  $(".numeric").numeric({ negative : false }); // do not allow negative values
 * @example  $(".numeric").numeric(null, callback); // use default values, pass on the 'callback' function
 *
 */
$.fn.numeric = function(config, callback)
{
	if(typeof config === 'boolean')
	{
		config = { decimal: config };
	}
	config = config || {};
	// if config.negative undefined, set to true (default is to allow negative numbers)
	if(typeof config.negative == "undefined") config.negative = true;
	// set decimal point
	var decimal = (config.decimal === false) ? "" : config.decimal || ".";
	// allow negatives
	var negative = (config.negative === true) ? true : false;
	// callback function
	var callback = typeof callback == "function" ? callback : function(){};
	// set data and methods
	return this.data("numeric.decimal", decimal).data("numeric.negative", negative).data("numeric.callback", callback).keypress($.fn.numeric.keypress).keyup($.fn.numeric.keyup).blur($.fn.numeric.blur);
}

$.fn.numeric.keypress = function(e)
{
	// get decimal character and determine if negatives are allowed
	var decimal = $.data(this, "numeric.decimal");
	var negative = $.data(this, "numeric.negative");
	// get the key that was pressed
	var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
	// allow enter/return key (only when in an input box)
	if(key == 13 &amp;&amp; this.nodeName.toLowerCase() == "input")
	{
		return true;
	}
	else if(key == 13)
	{
		return false;
	}
	var allow = false;
	// allow Ctrl+A
	if((e.ctrlKey &amp;&amp; key == 97 /* firefox */) || (e.ctrlKey &amp;&amp; key == 65) /* opera */) return true;
	// allow Ctrl+X (cut)
	if((e.ctrlKey &amp;&amp; key == 120 /* firefox */) || (e.ctrlKey &amp;&amp; key == 88) /* opera */) return true;
	// allow Ctrl+C (copy)
	if((e.ctrlKey &amp;&amp; key == 99 /* firefox */) || (e.ctrlKey &amp;&amp; key == 67) /* opera */) return true;
	// allow Ctrl+Z (undo)
	if((e.ctrlKey &amp;&amp; key == 122 /* firefox */) || (e.ctrlKey &amp;&amp; key == 90) /* opera */) return true;
	// allow or deny Ctrl+V (paste), Shift+Ins
	if((e.ctrlKey &amp;&amp; key == 118 /* firefox */) || (e.ctrlKey &amp;&amp; key == 86) /* opera */
	|| (e.shiftKey &amp;&amp; key == 45)) return true;
	// if a number was not pressed
	if(key &lt; 48 || key &gt; 57)
	{
		/* '-' only allowed at start and if negative numbers allowed */
		if(this.value.indexOf("-") != 0 &amp;&amp; negative &amp;&amp; key == 45 &amp;&amp; (this.value.length == 0 || ($.fn.getSelectionStart(this)) == 0)) return true;
		/* only one decimal separator allowed */
		if(decimal &amp;&amp; key == decimal.charCodeAt(0) &amp;&amp; this.value.indexOf(decimal) != -1)
		{
			allow = false;
		}
		// check for other keys that have special purposes
		if(
			key != 8 /* backspace */ &amp;&amp;
			key != 9 /* tab */ &amp;&amp;
			key != 13 /* enter */ &amp;&amp;
			key != 35 /* end */ &amp;&amp;
			key != 36 /* home */ &amp;&amp;
			key != 37 /* left */ &amp;&amp;
			key != 39 /* right */ &amp;&amp;
			key != 46 /* del */
		)
		{
			allow = false;
		}
		else
		{
			// for detecting special keys (listed above)
			// IE does not support 'charCode' and ignores them in keypress anyway
			if(typeof e.charCode != "undefined")
			{
				// special keys have 'keyCode' and 'which' the same (e.g. backspace)
				if(e.keyCode == e.which &amp;&amp; e.which != 0)
				{
					allow = true;
					// . and delete share the same code, don't allow . (will be set to true later if it is the decimal point)
					if(e.which == 46) allow = false;
				}
				// or keyCode != 0 and 'charCode'/'which' = 0
				else if(e.keyCode != 0 &amp;&amp; e.charCode == 0 &amp;&amp; e.which == 0)
				{
					allow = true;
				}
			}
		}
		// if key pressed is the decimal and it is not already in the field
		if(decimal &amp;&amp; key == decimal.charCodeAt(0))
		{
			if(this.value.indexOf(decimal) == -1)
			{
				allow = true;
			}
			else
			{
				allow = false;
			}
		}
	}
	else
	{
		allow = true;
	}
	return allow;
}

$.fn.numeric.keyup = function(e)
{
	var val = this.value;
	if(val.length &gt; 0)
	{
		// get carat (cursor) position
		var carat = $.fn.getSelectionStart(this);
		// get decimal character and determine if negatives are allowed
		var decimal = $.data(this, "numeric.decimal");
		var negative = $.data(this, "numeric.negative");
		
		// prepend a 0 if necessary
		if(decimal != "")
		{
			// find decimal point
			var dot = val.indexOf(decimal);
			// if dot at start, add 0 before
			if(dot == 0)
			{
				this.value = "0" + val;
			}
			// if dot at position 1, check if there is a - symbol before it
			if(dot == 1 &amp;&amp; val.charAt(0) == "-")
			{
				this.value = "-0" + val.substring(1);
			}
			val = this.value;
		}
		
		// if pasted in, only allow the following characters
		var validChars = [0,1,2,3,4,5,6,7,8,9,'-',decimal];
		// get length of the value (to loop through)
		var length = val.length;
		// loop backwards (to prevent going out of bounds)
		for(var i = length - 1; i &gt;= 0; i--)
		{
			var ch = val.charAt(i);
			// remove '-' if it is in the wrong place
			if(i != 0 &amp;&amp; ch == "-")
			{
				val = val.substring(0, i) + val.substring(i + 1);
			}
			// remove character if it is at the start, a '-' and negatives aren't allowed
			else if(i == 0 &amp;&amp; !negative &amp;&amp; ch == "-")
			{
				val = val.substring(1);
			}
			var validChar = false;
			// loop through validChars
			for(var j = 0; j &lt; validChars.length; j++)
			{
				// if it is valid, break out the loop
				if(ch == validChars[j])
				{
					validChar = true;
					break;
				}
			}
			// if not a valid character, or a space, remove
			if(!validChar || ch == " ")
			{
				val = val.substring(0, i) + val.substring(i + 1);
			}
		}
		// remove extra decimal characters
		var firstDecimal = val.indexOf(decimal);
		if(firstDecimal &gt; 0)
		{
			for(var i = length - 1; i &gt; firstDecimal; i--)
			{
				var ch = val.charAt(i);
				// remove decimal character
				if(ch == decimal)
				{
					val = val.substring(0, i) + val.substring(i + 1);
				}
			}
		}
		// set the value and prevent the cursor moving to the end
		this.value = val;
		$.fn.setSelection(this, carat);
	}
}

$.fn.numeric.blur = function()
{
	var decimal = $.data(this, "numeric.decimal");
	var callback = $.data(this, "numeric.callback");
	var val = this.value;
	if(val != "")
	{
		var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
		if(!re.exec(val))
		{
			callback.apply(this);
		}
	}
}

$.fn.removeNumeric = function()
{
	return this.data("numeric.decimal", null).data("numeric.negative", null).data("numeric.callback", null).unbind("keypress", $.fn.numeric.keypress).unbind("blur", $.fn.numeric.blur);
}

// Based on code from http://javascript.nwbox.com/cursor_position/ (Diego Perini &lt;dperini@nwbox.com&gt;)
$.fn.getSelectionStart = function(o)
{
	if (o.createTextRange)
	{
		var r = document.selection.createRange().duplicate();
		r.moveEnd('character', o.value.length);
		if (r.text == '') return o.value.length;
		return o.value.lastIndexOf(r.text);
	} else return o.selectionStart;
}

// set the selection, o is the object (input), p is the position ([start, end] or just start)
$.fn.setSelection = function(o, p)
{
	// if p is number, start and end are the same
	if(typeof p == "number") p = [p, p];
	// only set if p is an array of length 2
	if(p &amp;&amp; p.constructor == Array &amp;&amp; p.length == 2)
	{
		if (o.createTextRange)
		{
			var r = o.createTextRange();
			r.collapse(true);
			r.moveStart('character', p[0]);
			r.moveEnd('character', p[1]);
			r.select();
		}
		else if(o.setSelectionRange)
		{
			o.focus();
			o.setSelectionRange(p[0], p[1]);
		}
	}
}

})(jQuery);;/*
== malihu jquery custom scrollbar plugin == 
Version: 3.0.9 
Plugin URI: http://manos.malihu.gr/jquery-custom-content-scroller 
Author: malihu
Author URI: http://manos.malihu.gr
License: MIT License (MIT)
*/

/*
Copyright 2010 Manos Malihutsakis (email: manos@malihu.gr)

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.
*/

/*
The code below is fairly long, fully commented and should be normally used in development. 
For production, use either the minified jquery.mCustomScrollbar.min.js script or 
the production-ready jquery.mCustomScrollbar.concat.min.js which contains the plugin 
and dependencies (minified). 
*/

(function(factory){
	if(typeof module!=="undefined" &amp;&amp; module.exports){
		module.exports=factory;
	}else{
		factory(jQuery,window,document);
	}
}(function($){
(function(init){
	var _rjs=typeof define==="function" &amp;&amp; define.amd, /* RequireJS */
		_njs=typeof module !== "undefined" &amp;&amp; module.exports, /* NodeJS */
		_dlp=("https:"==document.location.protocol) ? "https:" : "http:", /* location protocol */
		_url="cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.12/jquery.mousewheel.min.js";
	if(!_rjs){
		if(_njs){
			require("jquery-mousewheel")($);
		}else{
			/* load jquery-mousewheel plugin (via CDN) if it's not present or not loaded via RequireJS 
			(works when mCustomScrollbar fn is called on window load) */
			$.event.special.mousewheel || $("head").append(decodeURI("%3Cscript src="+_dlp+"//"+_url+"%3E%3C/script%3E"));
		}
	}
	init();
}(function(){
	
	/* 
	----------------------------------------
	PLUGIN NAMESPACE, PREFIX, DEFAULT SELECTOR(S) 
	----------------------------------------
	*/
	
	var pluginNS="mCustomScrollbar",
		pluginPfx="mCS",
		defaultSelector=".mCustomScrollbar",
	
	
		
	
	
	/* 
	----------------------------------------
	DEFAULT OPTIONS 
	----------------------------------------
	*/
	
		defaults={
			/*
			set element/content width/height programmatically 
			values: boolean, pixels, percentage 
				option						default
				-------------------------------------
				setWidth					false
				setHeight					false
			*/
			/*
			set the initial css top property of content  
			values: string (e.g. "-100px", "10%" etc.)
			*/
			setTop:0,
			/*
			set the initial css left property of content  
			values: string (e.g. "-100px", "10%" etc.)
			*/
			setLeft:0,
			/* 
			scrollbar axis (vertical and/or horizontal scrollbars) 
			values (string): "y", "x", "yx"
			*/
			axis:"y",
			/*
			position of scrollbar relative to content  
			values (string): "inside", "outside" ("outside" requires elements with position:relative)
			*/
			scrollbarPosition:"inside",
			/*
			scrolling inertia
			values: integer (milliseconds)
			*/
			scrollInertia:950,
			/* 
			auto-adjust scrollbar dragger length
			values: boolean
			*/
			autoDraggerLength:true,
			/*
			auto-hide scrollbar when idle 
			values: boolean
				option						default
				-------------------------------------
				autoHideScrollbar			false
			*/
			/*
			auto-expands scrollbar on mouse-over and dragging
			values: boolean
				option						default
				-------------------------------------
				autoExpandScrollbar			false
			*/
			/*
			always show scrollbar, even when there's nothing to scroll 
			values: integer (0=disable, 1=always show dragger rail and buttons, 2=always show dragger rail, dragger and buttons), boolean
			*/
			alwaysShowScrollbar:0,
			/*
			scrolling always snaps to a multiple of this number in pixels
			values: integer
				option						default
				-------------------------------------
				snapAmount					null
			*/
			/*
			when snapping, snap with this number in pixels as an offset 
			values: integer
			*/
			snapOffset:0,
			/* 
			mouse-wheel scrolling
			*/
			mouseWheel:{
				/* 
				enable mouse-wheel scrolling
				values: boolean
				*/
				enable:true,
				/* 
				scrolling amount in pixels
				values: "auto", integer 
				*/
				scrollAmount:"auto",
				/* 
				mouse-wheel scrolling axis 
				the default scrolling direction when both vertical and horizontal scrollbars are present 
				values (string): "y", "x" 
				*/
				axis:"y",
				/* 
				prevent the default behaviour which automatically scrolls the parent element(s) when end of scrolling is reached 
				values: boolean
					option						default
					-------------------------------------
					preventDefault				null
				*/
				/*
				the reported mouse-wheel delta value. The number of lines (translated to pixels) one wheel notch scrolls.  
				values: "auto", integer 
				"auto" uses the default OS/browser value 
				*/
				deltaFactor:"auto",
				/*
				normalize mouse-wheel delta to -1 or 1 (disables mouse-wheel acceleration) 
				values: boolean
					option						default
					-------------------------------------
					normalizeDelta				null
				*/
				/*
				invert mouse-wheel scrolling direction 
				values: boolean
					option						default
					-------------------------------------
					invert						null
				*/
				/*
				the tags that disable mouse-wheel when cursor is over them
				*/
				disableOver:["select","option","keygen","datalist","textarea"]
			},
			/* 
			scrollbar buttons
			*/
			scrollButtons:{ 
				/*
				enable scrollbar buttons
				values: boolean
					option						default
					-------------------------------------
					enable						null
				*/
				/*
				scrollbar buttons scrolling type 
				values (string): "stepless", "stepped"
				*/
				scrollType:"stepless",
				/*
				scrolling amount in pixels
				values: "auto", integer 
				*/
				scrollAmount:"auto"
				/*
				tabindex of the scrollbar buttons
				values: false, integer
					option						default
					-------------------------------------
					tabindex					null
				*/
			},
			/* 
			keyboard scrolling
			*/
			keyboard:{ 
				/*
				enable scrolling via keyboard
				values: boolean
				*/
				enable:true,
				/*
				keyboard scrolling type 
				values (string): "stepless", "stepped"
				*/
				scrollType:"stepless",
				/*
				scrolling amount in pixels
				values: "auto", integer 
				*/
				scrollAmount:"auto"
			},
			/*
			enable content touch-swipe scrolling 
			values: boolean, integer, string (number)
			integer values define the axis-specific minimum amount required for scrolling momentum
			*/
			contentTouchScroll:25,
			/*
			advanced option parameters
			*/
			advanced:{
				/*
				auto-expand content horizontally (for "x" or "yx" axis) 
				values: boolean
					option						default
					-------------------------------------
					autoExpandHorizontalScroll	null
				*/
				/*
				auto-scroll to elements with focus
				*/
				autoScrollOnFocus:"input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']",
				/*
				auto-update scrollbars on content, element or viewport resize 
				should be true for fluid layouts/elements, adding/removing content dynamically, hiding/showing elements, content with images etc. 
				values: boolean
				*/
				updateOnContentResize:true,
				/*
				auto-update scrollbars each time each image inside the element is fully loaded 
				values: boolean
				*/
				updateOnImageLoad:true,
				/*
				auto-update scrollbars based on the amount and size changes of specific selectors 
				useful when you need to update the scrollbar(s) automatically, each time a type of element is added, removed or changes its size 
				values: boolean, string (e.g. "ul li" will auto-update scrollbars each time list-items inside the element are changed) 
				a value of true (boolean) will auto-update scrollbars each time any element is changed
					option						default
					-------------------------------------
					updateOnSelectorChange		null
				*/
				/*
				extra selectors that'll release scrollbar dragging upon mouseup, pointerup, touchend etc. (e.g. "selector-1, selector-2")
					option						default
					-------------------------------------
					releaseDraggableSelectors	null
				*/
				/*
				auto-update timeout 
				values: integer (milliseconds)
				*/
				autoUpdateTimeout:60
			},
			/* 
			scrollbar theme 
			values: string (see CSS/plugin URI for a list of ready-to-use themes)
			*/
			theme:"light",
			/*
			user defined callback functions
			*/
			callbacks:{
				/*
				Available callbacks: 
					callback					default
					-------------------------------------
					onInit						null
					onScrollStart				null
					onScroll					null
					onTotalScroll				null
					onTotalScrollBack			null
					whileScrolling				null
					onOverflowY					null
					onOverflowX					null
					onOverflowYNone				null
					onOverflowXNone				null
					onImageLoad					null
					onSelectorChange			null
					onUpdate					null
				*/
				onTotalScrollOffset:0,
				onTotalScrollBackOffset:0,
				alwaysTriggerOffsets:true
			}
			/*
			add scrollbar(s) on all elements matching the current selector, now and in the future 
			values: boolean, string 
			string values: "on" (enable), "once" (disable after first invocation), "off" (disable)
			liveSelector values: string (selector)
				option						default
				-------------------------------------
				live						false
				liveSelector				null
			*/
		},
	
	
	
	
	
	/* 
	----------------------------------------
	VARS, CONSTANTS 
	----------------------------------------
	*/
	
		totalInstances=0, /* plugin instances amount */
		liveTimers={}, /* live option timers */
		oldIE=(window.attachEvent &amp;&amp; !window.addEventListener) ? 1 : 0, /* detect IE &lt; 9 */
		touchActive=false,touchable, /* global touch vars (for touch and pointer events) */
		/* general plugin classes */
		classes=[
			"mCSB_dragger_onDrag","mCSB_scrollTools_onDrag","mCS_img_loaded","mCS_disabled","mCS_destroyed","mCS_no_scrollbar",
			"mCS-autoHide","mCS-dir-rtl","mCS_no_scrollbar_y","mCS_no_scrollbar_x","mCS_y_hidden","mCS_x_hidden","mCSB_draggerContainer",
			"mCSB_buttonUp","mCSB_buttonDown","mCSB_buttonLeft","mCSB_buttonRight"
		],
		
	
	
	
	
	/* 
	----------------------------------------
	METHODS 
	----------------------------------------
	*/
	
		methods={
			
			/* 
			plugin initialization method 
			creates the scrollbar(s), plugin data object and options
			----------------------------------------
			*/
			
			init:function(options){
				
				var options=$.extend(true,{},defaults,options),
					selector=_selector.call(this); /* validate selector */
				
				/* 
				if live option is enabled, monitor for elements matching the current selector and 
				apply scrollbar(s) when found (now and in the future) 
				*/
				if(options.live){
					var liveSelector=options.liveSelector || this.selector || defaultSelector, /* live selector(s) */
						$liveSelector=$(liveSelector); /* live selector(s) as jquery object */
					if(options.live==="off"){
						/* 
						disable live if requested 
						usage: $(selector).mCustomScrollbar({live:"off"}); 
						*/
						removeLiveTimers(liveSelector);
						return;
					}
					liveTimers[liveSelector]=setTimeout(function(){
						/* call mCustomScrollbar fn on live selector(s) every half-second */
						$liveSelector.mCustomScrollbar(options);
						if(options.live==="once" &amp;&amp; $liveSelector.length){
							/* disable live after first invocation */
							removeLiveTimers(liveSelector);
						}
					},500);
				}else{
					removeLiveTimers(liveSelector);
				}
				
				/* options backward compatibility (for versions &lt; 3.0.0) and normalization */
				options.setWidth=(options.set_width) ? options.set_width : options.setWidth;
				options.setHeight=(options.set_height) ? options.set_height : options.setHeight;
				options.axis=(options.horizontalScroll) ? "x" : _findAxis(options.axis);
				options.scrollInertia=options.scrollInertia&gt;0 &amp;&amp; options.scrollInertia&lt;17 ? 17 : options.scrollInertia;
				if(typeof options.mouseWheel!=="object" &amp;&amp;  options.mouseWheel==true){ /* old school mouseWheel option (non-object) */
					options.mouseWheel={enable:true,scrollAmount:"auto",axis:"y",preventDefault:false,deltaFactor:"auto",normalizeDelta:false,invert:false}
				}
				options.mouseWheel.scrollAmount=!options.mouseWheelPixels ? options.mouseWheel.scrollAmount : options.mouseWheelPixels;
				options.mouseWheel.normalizeDelta=!options.advanced.normalizeMouseWheelDelta ? options.mouseWheel.normalizeDelta : options.advanced.normalizeMouseWheelDelta;
				options.scrollButtons.scrollType=_findScrollButtonsType(options.scrollButtons.scrollType); 
				
				_theme(options); /* theme-specific options */
				
				/* plugin constructor */
				return $(selector).each(function(){
					
					var $this=$(this);
					
					if(!$this.data(pluginPfx)){ /* prevent multiple instantiations */
					
						/* store options and create objects in jquery data */
						$this.data(pluginPfx,{
							idx:++totalInstances, /* instance index */
							opt:options, /* options */
							scrollRatio:{y:null,x:null}, /* scrollbar to content ratio */
							overflowed:null, /* overflowed axis */
							contentReset:{y:null,x:null}, /* object to check when content resets */
							bindEvents:false, /* object to check if events are bound */
							tweenRunning:false, /* object to check if tween is running */
							sequential:{}, /* sequential scrolling object */
							langDir:$this.css("direction"), /* detect/store direction (ltr or rtl) */
							cbOffsets:null, /* object to check whether callback offsets always trigger */
							/* 
							object to check how scrolling events where last triggered 
							"internal" (default - triggered by this script), "external" (triggered by other scripts, e.g. via scrollTo method) 
							usage: object.data("mCS").trigger
							*/
							trigger:null
						});
						
						var d=$this.data(pluginPfx),o=d.opt,
							/* HTML data attributes */
							htmlDataAxis=$this.data("mcs-axis"),htmlDataSbPos=$this.data("mcs-scrollbar-position"),htmlDataTheme=$this.data("mcs-theme");
						 
						if(htmlDataAxis){o.axis=htmlDataAxis;} /* usage example: data-mcs-axis="y" */
						if(htmlDataSbPos){o.scrollbarPosition=htmlDataSbPos;} /* usage example: data-mcs-scrollbar-position="outside" */
						if(htmlDataTheme){ /* usage example: data-mcs-theme="minimal" */
							o.theme=htmlDataTheme;
							_theme(o); /* theme-specific options */
						}
						
						_pluginMarkup.call(this); /* add plugin markup */
						
						$("#mCSB_"+d.idx+"_container img:not(."+classes[2]+")").addClass(classes[2]); /* flag loaded images */
						
						methods.update.call(null,$this); /* call the update method */
					
					}
					
				});
				
			},
			/* ---------------------------------------- */
			
			
			
			/* 
			plugin update method 
			updates content and scrollbar(s) values, events and status 
			----------------------------------------
			usage: $(selector).mCustomScrollbar("update");
			*/
			
			update:function(el,cb){
				
				var selector=el || _selector.call(this); /* validate selector */
				
				return $(selector).each(function(){
					
					var $this=$(this);
					
					if($this.data(pluginPfx)){ /* check if plugin has initialized */
						
						var d=$this.data(pluginPfx),o=d.opt,
							mCSB_container=$("#mCSB_"+d.idx+"_container"),
							mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")];
						
						if(!mCSB_container.length){return;}
						
						if(d.tweenRunning){_stop($this);} /* stop any running tweens while updating */
						
						/* if element was disabled or destroyed, remove class(es) */
						if($this.hasClass(classes[3])){$this.removeClass(classes[3]);}
						if($this.hasClass(classes[4])){$this.removeClass(classes[4]);}
						
						_maxHeight.call(this); /* detect/set css max-height value */
						
						_expandContentHorizontally.call(this); /* expand content horizontally */
						
						if(o.axis!=="y" &amp;&amp; !o.advanced.autoExpandHorizontalScroll){
							mCSB_container.css("width",_contentWidth(mCSB_container.children()));
						}
						
						d.overflowed=_overflowed.call(this); /* determine if scrolling is required */
						
						_scrollbarVisibility.call(this); /* show/hide scrollbar(s) */
						
						/* auto-adjust scrollbar dragger length analogous to content */
						if(o.autoDraggerLength){_setDraggerLength.call(this);}
						
						_scrollRatio.call(this); /* calculate and store scrollbar to content ratio */
						
						_bindEvents.call(this); /* bind scrollbar events */
						
						/* reset scrolling position and/or events */
						var to=[Math.abs(mCSB_container[0].offsetTop),Math.abs(mCSB_container[0].offsetLeft)];
						if(o.axis!=="x"){ /* y/yx axis */
							if(!d.overflowed[0]){ /* y scrolling is not required */
								_resetContentPosition.call(this); /* reset content position */
								if(o.axis==="y"){
									_unbindEvents.call(this);
								}else if(o.axis==="yx" &amp;&amp; d.overflowed[1]){
									_scrollTo($this,to[1].toString(),{dir:"x",dur:0,overwrite:"none"});
								}
							}else if(mCSB_dragger[0].height()&gt;mCSB_dragger[0].parent().height()){
								_resetContentPosition.call(this); /* reset content position */
							}else{ /* y scrolling is required */
								_scrollTo($this,to[0].toString(),{dir:"y",dur:0,overwrite:"none"});
								d.contentReset.y=null;
							}
						}
						if(o.axis!=="y"){ /* x/yx axis */
							if(!d.overflowed[1]){ /* x scrolling is not required */
								_resetContentPosition.call(this); /* reset content position */
								if(o.axis==="x"){
									_unbindEvents.call(this);
								}else if(o.axis==="yx" &amp;&amp; d.overflowed[0]){
									_scrollTo($this,to[0].toString(),{dir:"y",dur:0,overwrite:"none"});
								}
							}else if(mCSB_dragger[1].width()&gt;mCSB_dragger[1].parent().width()){
								_resetContentPosition.call(this); /* reset content position */
							}else{ /* x scrolling is required */
								_scrollTo($this,to[1].toString(),{dir:"x",dur:0,overwrite:"none"});
								d.contentReset.x=null;
							}
						}
						
						/* callbacks: onImageLoad, onSelectorChange, onUpdate */
						if(cb &amp;&amp; d){
							if(cb===2 &amp;&amp; o.callbacks.onImageLoad &amp;&amp; typeof o.callbacks.onImageLoad==="function"){
								o.callbacks.onImageLoad.call(this);
							}else if(cb===3 &amp;&amp; o.callbacks.onSelectorChange &amp;&amp; typeof o.callbacks.onSelectorChange==="function"){
								o.callbacks.onSelectorChange.call(this);
							}else if(o.callbacks.onUpdate &amp;&amp; typeof o.callbacks.onUpdate==="function"){
								o.callbacks.onUpdate.call(this);
							}
						}
						
						_autoUpdate.call(this); /* initialize automatic updating (for dynamic content, fluid layouts etc.) */
						
					}
					
				});
				
			},
			/* ---------------------------------------- */
			
			
			
			/* 
			plugin scrollTo method 
			triggers a scrolling event to a specific value
			----------------------------------------
			usage: $(selector).mCustomScrollbar("scrollTo",value,options);
			*/
		
			scrollTo:function(val,options){
				
				/* prevent silly things like $(selector).mCustomScrollbar("scrollTo",undefined); */
				if(typeof val=="undefined" || val==null){return;}
				
				var selector=_selector.call(this); /* validate selector */
				
				return $(selector).each(function(){
					
					var $this=$(this);
					
					if($this.data(pluginPfx)){ /* check if plugin has initialized */
					
						var d=$this.data(pluginPfx),o=d.opt,
							/* method default options */
							methodDefaults={
								trigger:"external", /* method is by default triggered externally (e.g. from other scripts) */
								scrollInertia:o.scrollInertia, /* scrolling inertia (animation duration) */
								scrollEasing:"mcsEaseInOut", /* animation easing */
								moveDragger:false, /* move dragger instead of content */
								timeout:60, /* scroll-to delay */
								callbacks:true, /* enable/disable callbacks */
								onStart:true,
								onUpdate:true,
								onComplete:true
							},
							methodOptions=$.extend(true,{},methodDefaults,options),
							to=_arr.call(this,val),dur=methodOptions.scrollInertia&gt;0 &amp;&amp; methodOptions.scrollInertia&lt;17 ? 17 : methodOptions.scrollInertia;
						
						/* translate yx values to actual scroll-to positions */
						to[0]=_to.call(this,to[0],"y");
						to[1]=_to.call(this,to[1],"x");
						
						/* 
						check if scroll-to value moves the dragger instead of content. 
						Only pixel values apply on dragger (e.g. 100, "100px", "-=100" etc.) 
						*/
						if(methodOptions.moveDragger){
							to[0]*=d.scrollRatio.y;
							to[1]*=d.scrollRatio.x;
						}
						
						methodOptions.dur=dur;
						
						setTimeout(function(){ 
							/* do the scrolling */
							if(to[0]!==null &amp;&amp; typeof to[0]!=="undefined" &amp;&amp; o.axis!=="x" &amp;&amp; d.overflowed[0]){ /* scroll y */
								methodOptions.dir="y";
								methodOptions.overwrite="all";
								_scrollTo($this,to[0].toString(),methodOptions);
							}
							if(to[1]!==null &amp;&amp; typeof to[1]!=="undefined" &amp;&amp; o.axis!=="y" &amp;&amp; d.overflowed[1]){ /* scroll x */
								methodOptions.dir="x";
								methodOptions.overwrite="none";
								_scrollTo($this,to[1].toString(),methodOptions);
							}
						},methodOptions.timeout);
						
					}
					
				});
				
			},
			/* ---------------------------------------- */
			
			
			
			/*
			plugin stop method 
			stops scrolling animation
			----------------------------------------
			usage: $(selector).mCustomScrollbar("stop");
			*/
			stop:function(){
				
				var selector=_selector.call(this); /* validate selector */
				
				return $(selector).each(function(){
					
					var $this=$(this);
					
					if($this.data(pluginPfx)){ /* check if plugin has initialized */
										
						_stop($this);
					
					}
					
				});
				
			},
			/* ---------------------------------------- */
			
			
			
			/*
			plugin disable method 
			temporarily disables the scrollbar(s) 
			----------------------------------------
			usage: $(selector).mCustomScrollbar("disable",reset); 
			reset (boolean): resets content position to 0 
			*/
			disable:function(r){
				
				var selector=_selector.call(this); /* validate selector */
				
				return $(selector).each(function(){
					
					var $this=$(this);
					
					if($this.data(pluginPfx)){ /* check if plugin has initialized */
						
						var d=$this.data(pluginPfx);
						
						_autoUpdate.call(this,"remove"); /* remove automatic updating */
						
						_unbindEvents.call(this); /* unbind events */
						
						if(r){_resetContentPosition.call(this);} /* reset content position */
						
						_scrollbarVisibility.call(this,true); /* show/hide scrollbar(s) */
						
						$this.addClass(classes[3]); /* add disable class */
					
					}
					
				});
				
			},
			/* ---------------------------------------- */
			
			
			
			/*
			plugin destroy method 
			completely removes the scrollbar(s) and returns the element to its original state
			----------------------------------------
			usage: $(selector).mCustomScrollbar("destroy"); 
			*/
			destroy:function(){
				
				var selector=_selector.call(this); /* validate selector */
				
				return $(selector).each(function(){
					
					var $this=$(this);
					
					if($this.data(pluginPfx)){ /* check if plugin has initialized */
					
						var d=$this.data(pluginPfx),o=d.opt,
							mCustomScrollBox=$("#mCSB_"+d.idx),
							mCSB_container=$("#mCSB_"+d.idx+"_container"),
							scrollbar=$(".mCSB_"+d.idx+"_scrollbar");
					
						if(o.live){removeLiveTimers(o.liveSelector || $(selector).selector);} /* remove live timers */
						
						_autoUpdate.call(this,"remove"); /* remove automatic updating */
						
						_unbindEvents.call(this); /* unbind events */
						
						_resetContentPosition.call(this); /* reset content position */
						
						$this.removeData(pluginPfx); /* remove plugin data object */
						
						_delete(this,"mcs"); /* delete callbacks object */
						
						/* remove plugin markup */
						scrollbar.remove(); /* remove scrollbar(s) first (those can be either inside or outside plugin's inner wrapper) */
						mCSB_container.find("img."+classes[2]).removeClass(classes[2]); /* remove loaded images flag */
						mCustomScrollBox.replaceWith(mCSB_container.contents()); /* replace plugin's inner wrapper with the original content */
						/* remove plugin classes from the element and add destroy class */
						$this.removeClass(pluginNS+" _"+pluginPfx+"_"+d.idx+" "+classes[6]+" "+classes[7]+" "+classes[5]+" "+classes[3]).addClass(classes[4]);
					
					}
					
				});
				
			}
			/* ---------------------------------------- */
			
		},
	
	
	
	
		
	/* 
	----------------------------------------
	FUNCTIONS
	----------------------------------------
	*/
	
		/* validates selector (if selector is invalid or undefined uses the default one) */
		_selector=function(){
			return (typeof $(this)!=="object" || $(this).length&lt;1) ? defaultSelector : this;
		},
		/* -------------------- */
		
		
		/* changes options according to theme */
		_theme=function(obj){
			var fixedSizeScrollbarThemes=["rounded","rounded-dark","rounded-dots","rounded-dots-dark"],
				nonExpandedScrollbarThemes=["rounded-dots","rounded-dots-dark","3d","3d-dark","3d-thick","3d-thick-dark","inset","inset-dark","inset-2","inset-2-dark","inset-3","inset-3-dark"],
				disabledScrollButtonsThemes=["minimal","minimal-dark"],
				enabledAutoHideScrollbarThemes=["minimal","minimal-dark"],
				scrollbarPositionOutsideThemes=["minimal","minimal-dark"];
			obj.autoDraggerLength=$.inArray(obj.theme,fixedSizeScrollbarThemes) &gt; -1 ? false : obj.autoDraggerLength;
			obj.autoExpandScrollbar=$.inArray(obj.theme,nonExpandedScrollbarThemes) &gt; -1 ? false : obj.autoExpandScrollbar;
			obj.scrollButtons.enable=$.inArray(obj.theme,disabledScrollButtonsThemes) &gt; -1 ? false : obj.scrollButtons.enable;
			obj.autoHideScrollbar=$.inArray(obj.theme,enabledAutoHideScrollbarThemes) &gt; -1 ? true : obj.autoHideScrollbar;
			obj.scrollbarPosition=$.inArray(obj.theme,scrollbarPositionOutsideThemes) &gt; -1 ? "outside" : obj.scrollbarPosition;
		},
		/* -------------------- */
		
		
		/* live option timers removal */
		removeLiveTimers=function(selector){
			if(liveTimers[selector]){
				clearTimeout(liveTimers[selector]);
				_delete(liveTimers,selector);
			}
		},
		/* -------------------- */
		
		
		/* normalizes axis option to valid values: "y", "x", "yx" */
		_findAxis=function(val){
			return (val==="yx" || val==="xy" || val==="auto") ? "yx" : (val==="x" || val==="horizontal") ? "x" : "y";
		},
		/* -------------------- */
		
		
		/* normalizes scrollButtons.scrollType option to valid values: "stepless", "stepped" */
		_findScrollButtonsType=function(val){
			return (val==="stepped" || val==="pixels" || val==="step" || val==="click") ? "stepped" : "stepless";
		},
		/* -------------------- */
		
		
		/* generates plugin markup */
		_pluginMarkup=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				expandClass=o.autoExpandScrollbar ? " "+classes[1]+"_expand" : "",
				scrollbar=["&lt;div id='mCSB_"+d.idx+"_scrollbar_vertical' class='mCSB_scrollTools mCSB_"+d.idx+"_scrollbar mCS-"+o.theme+" mCSB_scrollTools_vertical"+expandClass+"'&gt;&lt;div class='"+classes[12]+"'&gt;&lt;div id='mCSB_"+d.idx+"_dragger_vertical' class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'&gt;&lt;div class='mCSB_dragger_bar' /&gt;&lt;/div&gt;&lt;div class='mCSB_draggerRail' /&gt;&lt;/div&gt;&lt;/div&gt;","&lt;div id='mCSB_"+d.idx+"_scrollbar_horizontal' class='mCSB_scrollTools mCSB_"+d.idx+"_scrollbar mCS-"+o.theme+" mCSB_scrollTools_horizontal"+expandClass+"'&gt;&lt;div class='"+classes[12]+"'&gt;&lt;div id='mCSB_"+d.idx+"_dragger_horizontal' class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'&gt;&lt;div class='mCSB_dragger_bar' /&gt;&lt;/div&gt;&lt;div class='mCSB_draggerRail' /&gt;&lt;/div&gt;&lt;/div&gt;"],
				wrapperClass=o.axis==="yx" ? "mCSB_vertical_horizontal" : o.axis==="x" ? "mCSB_horizontal" : "mCSB_vertical",
				scrollbars=o.axis==="yx" ? scrollbar[0]+scrollbar[1] : o.axis==="x" ? scrollbar[1] : scrollbar[0],
				contentWrapper=o.axis==="yx" ? "&lt;div id='mCSB_"+d.idx+"_container_wrapper' class='mCSB_container_wrapper' /&gt;" : "",
				autoHideClass=o.autoHideScrollbar ? " "+classes[6] : "",
				scrollbarDirClass=(o.axis!=="x" &amp;&amp; d.langDir==="rtl") ? " "+classes[7] : "";
			if(o.setWidth){$this.css("width",o.setWidth);} /* set element width */
			if(o.setHeight){$this.css("height",o.setHeight);} /* set element height */
			o.setLeft=(o.axis!=="y" &amp;&amp; d.langDir==="rtl") ? "989999px" : o.setLeft; /* adjust left position for rtl direction */
			$this.addClass(pluginNS+" _"+pluginPfx+"_"+d.idx+autoHideClass+scrollbarDirClass).wrapInner("&lt;div id='mCSB_"+d.idx+"' class='mCustomScrollBox mCS-"+o.theme+" "+wrapperClass+"'&gt;&lt;div id='mCSB_"+d.idx+"_container' class='mCSB_container' style='position:relative; top:"+o.setTop+"; left:"+o.setLeft+";' dir="+d.langDir+" /&gt;&lt;/div&gt;");
			var mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container");
			if(o.axis!=="y" &amp;&amp; !o.advanced.autoExpandHorizontalScroll){
				mCSB_container.css("width",_contentWidth(mCSB_container.children()));
			}
			if(o.scrollbarPosition==="outside"){
				if($this.css("position")==="static"){ /* requires elements with non-static position */
					$this.css("position","relative");
				}
				$this.css("overflow","visible");
				mCustomScrollBox.addClass("mCSB_outside").after(scrollbars);
			}else{
				mCustomScrollBox.addClass("mCSB_inside").append(scrollbars);
				mCSB_container.wrap(contentWrapper);
			}
			_scrollButtons.call(this); /* add scrollbar buttons */
			/* minimum dragger length */
			var mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")];
			mCSB_dragger[0].css("min-height",mCSB_dragger[0].height());
			mCSB_dragger[1].css("min-width",mCSB_dragger[1].width());
		},
		/* -------------------- */
		
		
		/* calculates content width */
		_contentWidth=function(el){
			return Math.max.apply(Math,el.map(function(){return $(this).outerWidth(true);}).get());
		},
		/* -------------------- */
		
		
		/* expands content horizontally */
		_expandContentHorizontally=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				mCSB_container=$("#mCSB_"+d.idx+"_container");
			if(o.advanced.autoExpandHorizontalScroll &amp;&amp; o.axis!=="y"){
				/* 
				wrap content with an infinite width div and set its position to absolute and width to auto. 
				Setting width to auto before calculating the actual width is important! 
				We must let the browser set the width as browser zoom values are impossible to calculate.
				*/
				mCSB_container.css({"position":"absolute","width":"auto"})
					.wrap("&lt;div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' /&gt;")
					.css({ /* set actual width, original position and un-wrap */
						/* 
						get the exact width (with decimals) and then round-up. 
						Using jquery outerWidth() will round the width value which will mess up with inner elements that have non-integer width
						*/
						"width":(Math.ceil(mCSB_container[0].getBoundingClientRect().right+0.4)-Math.floor(mCSB_container[0].getBoundingClientRect().left)),
						"position":"relative"
					}).unwrap();
			}
		},
		/* -------------------- */
		
		
		/* adds scrollbar buttons */
		_scrollButtons=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				mCSB_scrollTools=$(".mCSB_"+d.idx+"_scrollbar:first"),
				tabindex=!_isNumeric(o.scrollButtons.tabindex) ? "" : "tabindex='"+o.scrollButtons.tabindex+"'",
				btnHTML=[
					"&lt;a href='#' class='"+classes[13]+"' oncontextmenu='return false;' "+tabindex+" /&gt;",
					"&lt;a href='#' class='"+classes[14]+"' oncontextmenu='return false;' "+tabindex+" /&gt;",
					"&lt;a href='#' class='"+classes[15]+"' oncontextmenu='return false;' "+tabindex+" /&gt;",
					"&lt;a href='#' class='"+classes[16]+"' oncontextmenu='return false;' "+tabindex+" /&gt;"
				],
				btn=[(o.axis==="x" ? btnHTML[2] : btnHTML[0]),(o.axis==="x" ? btnHTML[3] : btnHTML[1]),btnHTML[2],btnHTML[3]];
			if(o.scrollButtons.enable){
				mCSB_scrollTools.prepend(btn[0]).append(btn[1]).next(".mCSB_scrollTools").prepend(btn[2]).append(btn[3]);
			}
		},
		/* -------------------- */
		
		
		/* detects/sets css max-height value */
		_maxHeight=function(){
			var $this=$(this),d=$this.data(pluginPfx),
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mh=$this.css("max-height") || "none",pct=mh.indexOf("%")!==-1,
				bs=$this.css("box-sizing");
			if(mh!=="none"){
				var val=pct ? $this.parent().height()*parseInt(mh)/100 : parseInt(mh);
				/* if element's css box-sizing is "border-box", subtract any paddings and/or borders from max-height value */
				if(bs==="border-box"){val-=(($this.innerHeight()-$this.height())+($this.outerHeight()-$this.innerHeight()));}
				mCustomScrollBox.css("max-height",Math.round(val));
			}
		},
		/* -------------------- */
		
		
		/* auto-adjusts scrollbar dragger length */
		_setDraggerLength=function(){
			var $this=$(this),d=$this.data(pluginPfx),
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")],
				ratio=[mCustomScrollBox.height()/mCSB_container.outerHeight(false),mCustomScrollBox.width()/mCSB_container.outerWidth(false)],
				l=[
					parseInt(mCSB_dragger[0].css("min-height")),Math.round(ratio[0]*mCSB_dragger[0].parent().height()),
					parseInt(mCSB_dragger[1].css("min-width")),Math.round(ratio[1]*mCSB_dragger[1].parent().width())
				],
				h=oldIE &amp;&amp; (l[1]&lt;l[0]) ? l[0] : l[1],w=oldIE &amp;&amp; (l[3]&lt;l[2]) ? l[2] : l[3];
			mCSB_dragger[0].css({
				"height":h,"max-height":(mCSB_dragger[0].parent().height()-10)
			}).find(".mCSB_dragger_bar").css({"line-height":l[0]+"px"});
			mCSB_dragger[1].css({
				"width":w,"max-width":(mCSB_dragger[1].parent().width()-10)
			});
		},
		/* -------------------- */
		
		
		/* calculates scrollbar to content ratio */
		_scrollRatio=function(){
			var $this=$(this),d=$this.data(pluginPfx),
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")],
				scrollAmount=[mCSB_container.outerHeight(false)-mCustomScrollBox.height(),mCSB_container.outerWidth(false)-mCustomScrollBox.width()],
				ratio=[
					scrollAmount[0]/(mCSB_dragger[0].parent().height()-mCSB_dragger[0].height()),
					scrollAmount[1]/(mCSB_dragger[1].parent().width()-mCSB_dragger[1].width())
				];
			d.scrollRatio={y:ratio[0],x:ratio[1]};
		},
		/* -------------------- */
		
		
		/* toggles scrolling classes */
		_onDragClasses=function(el,action,xpnd){
			var expandClass=xpnd ? classes[0]+"_expanded" : "",
				scrollbar=el.closest(".mCSB_scrollTools");
			if(action==="active"){
				el.toggleClass(classes[0]+" "+expandClass); scrollbar.toggleClass(classes[1]); 
				el[0]._draggable=el[0]._draggable ? 0 : 1;
			}else{
				if(!el[0]._draggable){
					if(action==="hide"){
						el.removeClass(classes[0]); scrollbar.removeClass(classes[1]);
					}else{
						el.addClass(classes[0]); scrollbar.addClass(classes[1]);
					}
				}
			}
		},
		/* -------------------- */
		
		
		/* checks if content overflows its container to determine if scrolling is required */
		_overflowed=function(){
			var $this=$(this),d=$this.data(pluginPfx),
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				contentHeight=d.overflowed==null ? mCSB_container.height() : mCSB_container.outerHeight(false),
				contentWidth=d.overflowed==null ? mCSB_container.width() : mCSB_container.outerWidth(false);
			return [contentHeight&gt;mCustomScrollBox.height(),contentWidth&gt;mCustomScrollBox.width()];
		},
		/* -------------------- */
		
		
		/* resets content position to 0 */
		_resetContentPosition=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")];
			_stop($this); /* stop any current scrolling before resetting */
			if((o.axis!=="x" &amp;&amp; !d.overflowed[0]) || (o.axis==="y" &amp;&amp; d.overflowed[0])){ /* reset y */
				mCSB_dragger[0].add(mCSB_container).css("top",0);
				_scrollTo($this,"_resetY");
			}
			if((o.axis!=="y" &amp;&amp; !d.overflowed[1]) || (o.axis==="x" &amp;&amp; d.overflowed[1])){ /* reset x */
				var cx=dx=0;
				if(d.langDir==="rtl"){ /* adjust left position for rtl direction */
					cx=mCustomScrollBox.width()-mCSB_container.outerWidth(false);
					dx=Math.abs(cx/d.scrollRatio.x);
				}
				mCSB_container.css("left",cx);
				mCSB_dragger[1].css("left",dx);
				_scrollTo($this,"_resetX");
			}
		},
		/* -------------------- */
		
		
		/* binds scrollbar events */
		_bindEvents=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt;
			if(!d.bindEvents){ /* check if events are already bound */
				_draggable.call(this);
				if(o.contentTouchScroll){_contentDraggable.call(this);}
				_selectable.call(this);
				if(o.mouseWheel.enable){ /* bind mousewheel fn when plugin is available */
					function _mwt(){
						mousewheelTimeout=setTimeout(function(){
							if(!$.event.special.mousewheel){
								_mwt();
							}else{
								clearTimeout(mousewheelTimeout);
								_mousewheel.call($this[0]);
							}
						},100);
					}
					var mousewheelTimeout;
					_mwt();
				}
				_draggerRail.call(this);
				_wrapperScroll.call(this);
				if(o.advanced.autoScrollOnFocus){_focus.call(this);}
				if(o.scrollButtons.enable){_buttons.call(this);}
				if(o.keyboard.enable){_keyboard.call(this);}
				d.bindEvents=true;
			}
		},
		/* -------------------- */
		
		
		/* unbinds scrollbar events */
		_unbindEvents=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				namespace=pluginPfx+"_"+d.idx,
				sb=".mCSB_"+d.idx+"_scrollbar",
				sel=$("#mCSB_"+d.idx+",#mCSB_"+d.idx+"_container,#mCSB_"+d.idx+"_container_wrapper,"+sb+" ."+classes[12]+",#mCSB_"+d.idx+"_dragger_vertical,#mCSB_"+d.idx+"_dragger_horizontal,"+sb+"&gt;a"),
				mCSB_container=$("#mCSB_"+d.idx+"_container");
			if(o.advanced.releaseDraggableSelectors){sel.add($(o.advanced.releaseDraggableSelectors));}
			if(d.bindEvents){ /* check if events are bound */
				/* unbind namespaced events from document/selectors */
				$(document).unbind("."+namespace);
				sel.each(function(){
					$(this).unbind("."+namespace);
				});
				/* clear and delete timeouts/objects */
				clearTimeout($this[0]._focusTimeout); _delete($this[0],"_focusTimeout");
				clearTimeout(d.sequential.step); _delete(d.sequential,"step");
				clearTimeout(mCSB_container[0].onCompleteTimeout); _delete(mCSB_container[0],"onCompleteTimeout");
				d.bindEvents=false;
			}
		},
		/* -------------------- */
		
		
		/* toggles scrollbar visibility */
		_scrollbarVisibility=function(disabled){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				contentWrapper=$("#mCSB_"+d.idx+"_container_wrapper"),
				content=contentWrapper.length ? contentWrapper : $("#mCSB_"+d.idx+"_container"),
				scrollbar=[$("#mCSB_"+d.idx+"_scrollbar_vertical"),$("#mCSB_"+d.idx+"_scrollbar_horizontal")],
				mCSB_dragger=[scrollbar[0].find(".mCSB_dragger"),scrollbar[1].find(".mCSB_dragger")];
			if(o.axis!=="x"){
				if(d.overflowed[0] &amp;&amp; !disabled){
					scrollbar[0].add(mCSB_dragger[0]).add(scrollbar[0].children("a")).css("display","block");
					content.removeClass(classes[8]+" "+classes[10]);
				}else{
					if(o.alwaysShowScrollbar){
						if(o.alwaysShowScrollbar!==2){mCSB_dragger[0].css("display","none");}
						content.removeClass(classes[10]);
					}else{
						scrollbar[0].css("display","none");
						content.addClass(classes[10]);
					}
					content.addClass(classes[8]);
				}
			}
			if(o.axis!=="y"){
				if(d.overflowed[1] &amp;&amp; !disabled){
					scrollbar[1].add(mCSB_dragger[1]).add(scrollbar[1].children("a")).css("display","block");
					content.removeClass(classes[9]+" "+classes[11]);
				}else{
					if(o.alwaysShowScrollbar){
						if(o.alwaysShowScrollbar!==2){mCSB_dragger[1].css("display","none");}
						content.removeClass(classes[11]);
					}else{
						scrollbar[1].css("display","none");
						content.addClass(classes[11]);
					}
					content.addClass(classes[9]);
				}
			}
			if(!d.overflowed[0] &amp;&amp; !d.overflowed[1]){
				$this.addClass(classes[5]);
			}else{
				$this.removeClass(classes[5]);
			}
		},
		/* -------------------- */
		
		
		/* returns input coordinates of pointer, touch and mouse events (relative to document) */
		_coordinates=function(e){
			var t=e.type;
			switch(t){
				case "pointerdown": case "MSPointerDown": case "pointermove": case "MSPointerMove": case "pointerup": case "MSPointerUp":
					return e.target.ownerDocument!==document ? [e.originalEvent.screenY,e.originalEvent.screenX,false] : [e.originalEvent.pageY,e.originalEvent.pageX,false];
					break;
				case "touchstart": case "touchmove": case "touchend":
					var touch=e.originalEvent.touches[0] || e.originalEvent.changedTouches[0],
						touches=e.originalEvent.touches.length || e.originalEvent.changedTouches.length;
					return e.target.ownerDocument!==document ? [touch.screenY,touch.screenX,touches&gt;1] : [touch.pageY,touch.pageX,touches&gt;1];
					break;
				default:
					return [e.pageY,e.pageX,false];
			}
		},
		/* -------------------- */
		
		
		/* 
		SCROLLBAR DRAG EVENTS
		scrolls content via scrollbar dragging 
		*/
		_draggable=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				namespace=pluginPfx+"_"+d.idx,
				draggerId=["mCSB_"+d.idx+"_dragger_vertical","mCSB_"+d.idx+"_dragger_horizontal"],
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				mCSB_dragger=$("#"+draggerId[0]+",#"+draggerId[1]),
				draggable,dragY,dragX,
				rds=o.advanced.releaseDraggableSelectors ? mCSB_dragger.add($(o.advanced.releaseDraggableSelectors)) : mCSB_dragger;
			mCSB_dragger.bind("mousedown."+namespace+" touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace,function(e){
				e.stopImmediatePropagation();
				e.preventDefault();
				if(!_mouseBtnLeft(e)){return;} /* left mouse button only */
				touchActive=true;
				if(oldIE){document.onselectstart=function(){return false;}} /* disable text selection for IE &lt; 9 */
				_iframe(false); /* enable scrollbar dragging over iframes by disabling their events */
				_stop($this);
				draggable=$(this);
				var offset=draggable.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left,
					h=draggable.height()+offset.top,w=draggable.width()+offset.left;
				if(y&lt;h &amp;&amp; y&gt;0 &amp;&amp; x&lt;w &amp;&amp; x&gt;0){
					dragY=y; 
					dragX=x;
				}
				_onDragClasses(draggable,"active",o.autoExpandScrollbar); 
			}).bind("touchmove."+namespace,function(e){
				e.stopImmediatePropagation();
				e.preventDefault();
				var offset=draggable.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left;
				_drag(dragY,dragX,y,x);
			});
			$(document).bind("mousemove."+namespace+" pointermove."+namespace+" MSPointerMove."+namespace,function(e){
				if(draggable){
					var offset=draggable.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left;
					if(dragY===y){return;} /* has it really moved? */
					_drag(dragY,dragX,y,x);
				}
			}).add(rds).bind("mouseup."+namespace+" touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace,function(e){
				if(draggable){
					_onDragClasses(draggable,"active",o.autoExpandScrollbar); 
					draggable=null;
				}
				touchActive=false;
				if(oldIE){document.onselectstart=null;} /* enable text selection for IE &lt; 9 */
				_iframe(true); /* enable iframes events */
			});
			function _iframe(evt){
				var el=mCSB_container.find("iframe");
				if(!el.length){return;} /* check if content contains iframes */
				var val=!evt ? "none" : "auto";
				el.css("pointer-events",val); /* for IE11, iframe's display property should not be "block" */
			}
			function _drag(dragY,dragX,y,x){
				mCSB_container[0].idleTimer=o.scrollInertia&lt;233 ? 250 : 0;
				if(draggable.attr("id")===draggerId[1]){
					var dir="x",to=((draggable[0].offsetLeft-dragX)+x)*d.scrollRatio.x;
				}else{
					var dir="y",to=((draggable[0].offsetTop-dragY)+y)*d.scrollRatio.y;
				}
				_scrollTo($this,to.toString(),{dir:dir,drag:true});
			}
		},
		/* -------------------- */
		
		
		/* 
		TOUCH SWIPE EVENTS
		scrolls content via touch swipe 
		Emulates the native touch-swipe scrolling with momentum found in iOS, Android and WP devices 
		*/
		_contentDraggable=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				namespace=pluginPfx+"_"+d.idx,
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")],
				dragY,dragX,touchStartY,touchStartX,touchMoveY=[],touchMoveX=[],startTime,runningTime,endTime,distance,speed,amount,
				durA=0,durB,overwrite=o.axis==="yx" ? "none" : "all",touchIntent=[],touchDrag,docDrag,
				iframe=mCSB_container.find("iframe"),
				events=[
					"touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace, //start
					"touchmove."+namespace+" pointermove."+namespace+" MSPointerMove."+namespace, //move
					"touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace //end
				];
			mCSB_container.bind(events[0],function(e){
				_onTouchstart(e);
			}).bind(events[1],function(e){
				_onTouchmove(e);
			});
			mCustomScrollBox.bind(events[0],function(e){
				_onTouchstart2(e);
			}).bind(events[2],function(e){
				_onTouchend(e);
			});
			if(iframe.length){
				iframe.each(function(){
					$(this).load(function(){
						/* bind events on accessible iframes */
						if(_canAccessIFrame(this)){
							$(this.contentDocument || this.contentWindow.document).bind(events[0],function(e){
								_onTouchstart(e);
								_onTouchstart2(e);
							}).bind(events[1],function(e){
								_onTouchmove(e);
							}).bind(events[2],function(e){
								_onTouchend(e);
							});
						}
					});
				});
			}
			function _onTouchstart(e){
				if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){touchable=0; return;}
				touchable=1; touchDrag=0; docDrag=0;
				$this.removeClass("mCS_touch_action");
				var offset=mCSB_container.offset();
				dragY=_coordinates(e)[0]-offset.top;
				dragX=_coordinates(e)[1]-offset.left;
				touchIntent=[_coordinates(e)[0],_coordinates(e)[1]];
			}
			function _onTouchmove(e){
				if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){return;}
				e.stopImmediatePropagation();
				if(docDrag &amp;&amp; !touchDrag){return;}
				runningTime=_getTime();
				var offset=mCustomScrollBox.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left,
					easing="mcsLinearOut";
				touchMoveY.push(y);
				touchMoveX.push(x);
				touchIntent[2]=Math.abs(_coordinates(e)[0]-touchIntent[0]); touchIntent[3]=Math.abs(_coordinates(e)[1]-touchIntent[1]);
				if(d.overflowed[0]){
					var limit=mCSB_dragger[0].parent().height()-mCSB_dragger[0].height(),
						prevent=((dragY-y)&gt;0 &amp;&amp; (y-dragY)&gt;-(limit*d.scrollRatio.y) &amp;&amp; (touchIntent[3]*2&lt;touchIntent[2] || o.axis==="yx"));
				}
				if(d.overflowed[1]){
					var limitX=mCSB_dragger[1].parent().width()-mCSB_dragger[1].width(),
						preventX=((dragX-x)&gt;0 &amp;&amp; (x-dragX)&gt;-(limitX*d.scrollRatio.x) &amp;&amp; (touchIntent[2]*2&lt;touchIntent[3] || o.axis==="yx"));
				}
				if(prevent || preventX){ /* prevent native document scrolling */
					e.preventDefault(); 
					touchDrag=1;
				}else{
					docDrag=1;
					$this.addClass("mCS_touch_action");
				}
				amount=o.axis==="yx" ? [(dragY-y),(dragX-x)] : o.axis==="x" ? [null,(dragX-x)] : [(dragY-y),null];
				mCSB_container[0].idleTimer=250;
				if(d.overflowed[0]){_drag(amount[0],durA,easing,"y","all",true);}
				if(d.overflowed[1]){_drag(amount[1],durA,easing,"x",overwrite,true);}
			}
			function _onTouchstart2(e){
				if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){touchable=0; return;}
				touchable=1;
				e.stopImmediatePropagation();
				_stop($this);
				startTime=_getTime();
				var offset=mCustomScrollBox.offset();
				touchStartY=_coordinates(e)[0]-offset.top;
				touchStartX=_coordinates(e)[1]-offset.left;
				touchMoveY=[]; touchMoveX=[];
			}
			function _onTouchend(e){
				if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){return;}
				e.stopImmediatePropagation();
				touchDrag=0; docDrag=0;
				endTime=_getTime();
				var offset=mCustomScrollBox.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left;
				if((endTime-runningTime)&gt;30){return;}
				speed=1000/(endTime-startTime);
				var easing="mcsEaseOut",slow=speed&lt;2.5,
					diff=slow ? [touchMoveY[touchMoveY.length-2],touchMoveX[touchMoveX.length-2]] : [0,0];
				distance=slow ? [(y-diff[0]),(x-diff[1])] : [y-touchStartY,x-touchStartX];
				var absDistance=[Math.abs(distance[0]),Math.abs(distance[1])];
				speed=slow ? [Math.abs(distance[0]/4),Math.abs(distance[1]/4)] : [speed,speed];
				var a=[
					Math.abs(mCSB_container[0].offsetTop)-(distance[0]*_m((absDistance[0]/speed[0]),speed[0])),
					Math.abs(mCSB_container[0].offsetLeft)-(distance[1]*_m((absDistance[1]/speed[1]),speed[1]))
				];
				amount=o.axis==="yx" ? [a[0],a[1]] : o.axis==="x" ? [null,a[1]] : [a[0],null];
				durB=[(absDistance[0]*4)+o.scrollInertia,(absDistance[1]*4)+o.scrollInertia];
				var md=parseInt(o.contentTouchScroll) || 0; /* absolute minimum distance required */
				amount[0]=absDistance[0]&gt;md ? amount[0] : 0;
				amount[1]=absDistance[1]&gt;md ? amount[1] : 0;
				if(d.overflowed[0]){_drag(amount[0],durB[0],easing,"y",overwrite,false);}
				if(d.overflowed[1]){_drag(amount[1],durB[1],easing,"x",overwrite,false);}
			}
			function _m(ds,s){
				var r=[s*1.5,s*2,s/1.5,s/2];
				if(ds&gt;90){
					return s&gt;4 ? r[0] : r[3];
				}else if(ds&gt;60){
					return s&gt;3 ? r[3] : r[2];
				}else if(ds&gt;30){
					return s&gt;8 ? r[1] : s&gt;6 ? r[0] : s&gt;4 ? s : r[2];
				}else{
					return s&gt;8 ? s : r[3];
				}
			}
			function _drag(amount,dur,easing,dir,overwrite,drag){
				if(!amount){return;}
				_scrollTo($this,amount.toString(),{dur:dur,scrollEasing:easing,dir:dir,overwrite:overwrite,drag:drag});
			}
		},
		/* -------------------- */
		
		
		/* 
		SELECT TEXT EVENTS 
		scrolls content when text is selected 
		*/
		_selectable=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,seq=d.sequential,
				namespace=pluginPfx+"_"+d.idx,
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent(),
				action;
			mCSB_container.bind("mousedown."+namespace,function(e){
				if(touchable){return;}
				if(!action){action=1; touchActive=true;}
			}).add(document).bind("mousemove."+namespace,function(e){
				if(!touchable &amp;&amp; action &amp;&amp; _sel()){
					var offset=mCSB_container.offset(),
						y=_coordinates(e)[0]-offset.top+mCSB_container[0].offsetTop,x=_coordinates(e)[1]-offset.left+mCSB_container[0].offsetLeft;
					if(y&gt;0 &amp;&amp; y&lt;wrapper.height() &amp;&amp; x&gt;0 &amp;&amp; x&lt;wrapper.width()){
						if(seq.step){_seq("off",null,"stepped");}
					}else{
						if(o.axis!=="x" &amp;&amp; d.overflowed[0]){
							if(y&lt;0){
								_seq("on",38);
							}else if(y&gt;wrapper.height()){
								_seq("on",40);
							}
						}
						if(o.axis!=="y" &amp;&amp; d.overflowed[1]){
							if(x&lt;0){
								_seq("on",37);
							}else if(x&gt;wrapper.width()){
								_seq("on",39);
							}
						}
					}
				}
			}).bind("mouseup."+namespace,function(e){
				if(touchable){return;}
				if(action){action=0; _seq("off",null);}
				touchActive=false;
			});
			function _sel(){
				return 	window.getSelection ? window.getSelection().toString() : 
						document.selection &amp;&amp; document.selection.type!="Control" ? document.selection.createRange().text : 0;
			}
			function _seq(a,c,s){
				seq.type=s &amp;&amp; action ? "stepped" : "stepless";
				seq.scrollAmount=10;
				_sequentialScroll($this,a,c,"mcsLinearOut",s ? 60 : null);
			}
		},
		/* -------------------- */
		
		
		/* 
		MOUSE WHEEL EVENT
		scrolls content via mouse-wheel 
		via mouse-wheel plugin (https://github.com/brandonaaron/jquery-mousewheel)
		*/
		_mousewheel=function(){
			if(!$(this).data(pluginPfx)){return;} /* Check if the scrollbar is ready to use mousewheel events (issue: #185) */
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				namespace=pluginPfx+"_"+d.idx,
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")],
				iframe=$("#mCSB_"+d.idx+"_container").find("iframe");
			if(iframe.length){
				iframe.each(function(){
					$(this).load(function(){
						/* bind events on accessible iframes */
						if(_canAccessIFrame(this)){
							$(this.contentDocument || this.contentWindow.document).bind("mousewheel."+namespace,function(e,delta){
								_onMousewheel(e,delta);
							});
						}
					});
				});
			}
			mCustomScrollBox.bind("mousewheel."+namespace,function(e,delta){
				_onMousewheel(e,delta);
			});
			function _onMousewheel(e,delta){
				_stop($this);
				if(_disableMousewheel($this,e.target)){return;} /* disables mouse-wheel when hovering specific elements */
				var deltaFactor=o.mouseWheel.deltaFactor!=="auto" ? parseInt(o.mouseWheel.deltaFactor) : (oldIE &amp;&amp; e.deltaFactor&lt;100) ? 100 : e.deltaFactor || 100;
				if(o.axis==="x" || o.mouseWheel.axis==="x"){
					var dir="x",
						px=[Math.round(deltaFactor*d.scrollRatio.x),parseInt(o.mouseWheel.scrollAmount)],
						amount=o.mouseWheel.scrollAmount!=="auto" ? px[1] : px[0]&gt;=mCustomScrollBox.width() ? mCustomScrollBox.width()*0.9 : px[0],
						contentPos=Math.abs($("#mCSB_"+d.idx+"_container")[0].offsetLeft),
						draggerPos=mCSB_dragger[1][0].offsetLeft,
						limit=mCSB_dragger[1].parent().width()-mCSB_dragger[1].width(),
						dlt=e.deltaX || e.deltaY || delta;
				}else{
					var dir="y",
						px=[Math.round(deltaFactor*d.scrollRatio.y),parseInt(o.mouseWheel.scrollAmount)],
						amount=o.mouseWheel.scrollAmount!=="auto" ? px[1] : px[0]&gt;=mCustomScrollBox.height() ? mCustomScrollBox.height()*0.9 : px[0],
						contentPos=Math.abs($("#mCSB_"+d.idx+"_container")[0].offsetTop),
						draggerPos=mCSB_dragger[0][0].offsetTop,
						limit=mCSB_dragger[0].parent().height()-mCSB_dragger[0].height(),
						dlt=e.deltaY || delta;
				}
				if((dir==="y" &amp;&amp; !d.overflowed[0]) || (dir==="x" &amp;&amp; !d.overflowed[1])){return;}
				if(o.mouseWheel.invert || e.webkitDirectionInvertedFromDevice){dlt=-dlt;}
				if(o.mouseWheel.normalizeDelta){dlt=dlt&lt;0 ? -1 : 1;}
				if((dlt&gt;0 &amp;&amp; draggerPos!==0) || (dlt&lt;0 &amp;&amp; draggerPos!==limit) || o.mouseWheel.preventDefault){
					e.stopImmediatePropagation();
					e.preventDefault();
				}
				_scrollTo($this,(contentPos-(dlt*amount)).toString(),{dir:dir});
			}
		},
		/* -------------------- */
		
		
		/* checks if iframe can be accessed */
		_canAccessIFrame=function(iframe){
			var html=null;
			try{
				var doc=iframe.contentDocument || iframe.contentWindow.document;
				html=doc.body.innerHTML;
			}catch(err){/* do nothing */}
			return(html!==null);
		},
		/* -------------------- */
		
		
		/* disables mouse-wheel when hovering specific elements like select, datalist etc. */
		_disableMousewheel=function(el,target){
			var tag=target.nodeName.toLowerCase(),
				tags=el.data(pluginPfx).opt.mouseWheel.disableOver,
				/* elements that require focus */
				focusTags=["select","textarea"];
			return $.inArray(tag,tags) &gt; -1 &amp;&amp; !($.inArray(tag,focusTags) &gt; -1 &amp;&amp; !$(target).is(":focus"));
		},
		/* -------------------- */
		
		
		/* 
		DRAGGER RAIL CLICK EVENT
		scrolls content via dragger rail 
		*/
		_draggerRail=function(){
			var $this=$(this),d=$this.data(pluginPfx),
				namespace=pluginPfx+"_"+d.idx,
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent(),
				mCSB_draggerContainer=$(".mCSB_"+d.idx+"_scrollbar ."+classes[12]);
			mCSB_draggerContainer.bind("touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace,function(e){
				touchActive=true;
			}).bind("touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace,function(e){
				touchActive=false;
			}).bind("click."+namespace,function(e){
				if($(e.target).hasClass(classes[12]) || $(e.target).hasClass("mCSB_draggerRail")){
					_stop($this);
					var el=$(this),mCSB_dragger=el.find(".mCSB_dragger");
					if(el.parent(".mCSB_scrollTools_horizontal").length&gt;0){
						if(!d.overflowed[1]){return;}
						var dir="x",
							clickDir=e.pageX&gt;mCSB_dragger.offset().left ? -1 : 1,
							to=Math.abs(mCSB_container[0].offsetLeft)-(clickDir*(wrapper.width()*0.9));
					}else{
						if(!d.overflowed[0]){return;}
						var dir="y",
							clickDir=e.pageY&gt;mCSB_dragger.offset().top ? -1 : 1,
							to=Math.abs(mCSB_container[0].offsetTop)-(clickDir*(wrapper.height()*0.9));
					}
					_scrollTo($this,to.toString(),{dir:dir,scrollEasing:"mcsEaseInOut"});
				}
			});
		},
		/* -------------------- */
		
		
		/* 
		FOCUS EVENT
		scrolls content via element focus (e.g. clicking an input, pressing TAB key etc.)
		*/
		_focus=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				namespace=pluginPfx+"_"+d.idx,
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent();
			mCSB_container.bind("focusin."+namespace,function(e){
				var el=$(document.activeElement),
					nested=mCSB_container.find(".mCustomScrollBox").length,
					dur=0;
				if(!el.is(o.advanced.autoScrollOnFocus)){return;}
				_stop($this);
				clearTimeout($this[0]._focusTimeout);
				$this[0]._focusTimer=nested ? (dur+17)*nested : 0;
				$this[0]._focusTimeout=setTimeout(function(){
					var	to=[_childPos(el)[0],_childPos(el)[1]],
						contentPos=[mCSB_container[0].offsetTop,mCSB_container[0].offsetLeft],
						isVisible=[
							(contentPos[0]+to[0]&gt;=0 &amp;&amp; contentPos[0]+to[0]&lt;wrapper.height()-el.outerHeight(false)),
							(contentPos[1]+to[1]&gt;=0 &amp;&amp; contentPos[0]+to[1]&lt;wrapper.width()-el.outerWidth(false))
						],
						overwrite=(o.axis==="yx" &amp;&amp; !isVisible[0] &amp;&amp; !isVisible[1]) ? "none" : "all";
					if(o.axis!=="x" &amp;&amp; !isVisible[0]){
						_scrollTo($this,to[0].toString(),{dir:"y",scrollEasing:"mcsEaseInOut",overwrite:overwrite,dur:dur});
					}
					if(o.axis!=="y" &amp;&amp; !isVisible[1]){
						_scrollTo($this,to[1].toString(),{dir:"x",scrollEasing:"mcsEaseInOut",overwrite:overwrite,dur:dur});
					}
				},$this[0]._focusTimer);
			});
		},
		/* -------------------- */
		
		
		/* sets content wrapper scrollTop/scrollLeft always to 0 */
		_wrapperScroll=function(){
			var $this=$(this),d=$this.data(pluginPfx),
				namespace=pluginPfx+"_"+d.idx,
				wrapper=$("#mCSB_"+d.idx+"_container").parent();
			wrapper.bind("scroll."+namespace,function(e){
				if(wrapper.scrollTop()!==0 || wrapper.scrollLeft()!==0){
					$(".mCSB_"+d.idx+"_scrollbar").css("visibility","hidden"); /* hide scrollbar(s) */
				}
			});
		},
		/* -------------------- */
		
		
		/* 
		BUTTONS EVENTS
		scrolls content via up, down, left and right buttons 
		*/
		_buttons=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,seq=d.sequential,
				namespace=pluginPfx+"_"+d.idx,
				sel=".mCSB_"+d.idx+"_scrollbar",
				btn=$(sel+"&gt;a");
			btn.bind("mousedown."+namespace+" touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace+" mouseup."+namespace+" touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace+" mouseout."+namespace+" pointerout."+namespace+" MSPointerOut."+namespace+" click."+namespace,function(e){
				e.preventDefault();
				if(!_mouseBtnLeft(e)){return;} /* left mouse button only */
				var btnClass=$(this).attr("class");
				seq.type=o.scrollButtons.scrollType;
				switch(e.type){
					case "mousedown": case "touchstart": case "pointerdown": case "MSPointerDown":
						if(seq.type==="stepped"){return;}
						touchActive=true;
						d.tweenRunning=false;
						_seq("on",btnClass);
						break;
					case "mouseup": case "touchend": case "pointerup": case "MSPointerUp":
					case "mouseout": case "pointerout": case "MSPointerOut":
						if(seq.type==="stepped"){return;}
						touchActive=false;
						if(seq.dir){_seq("off",btnClass);}
						break;
					case "click":
						if(seq.type!=="stepped" || d.tweenRunning){return;}
						_seq("on",btnClass);
						break;
				}
				function _seq(a,c){
					seq.scrollAmount=o.snapAmount || o.scrollButtons.scrollAmount;
					_sequentialScroll($this,a,c);
				}
			});
		},
		/* -------------------- */
		
		
		/* 
		KEYBOARD EVENTS
		scrolls content via keyboard 
		Keys: up arrow, down arrow, left arrow, right arrow, PgUp, PgDn, Home, End
		*/
		_keyboard=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,seq=d.sequential,
				namespace=pluginPfx+"_"+d.idx,
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent(),
				editables="input,textarea,select,datalist,keygen,[contenteditable='true']",
				iframe=mCSB_container.find("iframe"),
				events=["blur."+namespace+" keydown."+namespace+" keyup."+namespace];
			if(iframe.length){
				iframe.each(function(){
					$(this).load(function(){
						/* bind events on accessible iframes */
						if(_canAccessIFrame(this)){
							$(this.contentDocument || this.contentWindow.document).bind(events[0],function(e){
								_onKeyboard(e);
							});
						}
					});
				});
			}
			mCustomScrollBox.attr("tabindex","0").bind(events[0],function(e){
				_onKeyboard(e);
			});
			function _onKeyboard(e){
				switch(e.type){
					case "blur":
						if(d.tweenRunning &amp;&amp; seq.dir){_seq("off",null);}
						break;
					case "keydown": case "keyup":
						var code=e.keyCode ? e.keyCode : e.which,action="on";
						if((o.axis!=="x" &amp;&amp; (code===38 || code===40)) || (o.axis!=="y" &amp;&amp; (code===37 || code===39))){
							/* up (38), down (40), left (37), right (39) arrows */
							if(((code===38 || code===40) &amp;&amp; !d.overflowed[0]) || ((code===37 || code===39) &amp;&amp; !d.overflowed[1])){return;}
							if(e.type==="keyup"){action="off";}
							if(!$(document.activeElement).is(editables)){
								e.preventDefault();
								e.stopImmediatePropagation();
								_seq(action,code);
							}
						}else if(code===33 || code===34){
							/* PgUp (33), PgDn (34) */
							if(d.overflowed[0] || d.overflowed[1]){
								e.preventDefault();
								e.stopImmediatePropagation();
							}
							if(e.type==="keyup"){
								_stop($this);
								var keyboardDir=code===34 ? -1 : 1;
								if(o.axis==="x" || (o.axis==="yx" &amp;&amp; d.overflowed[1] &amp;&amp; !d.overflowed[0])){
									var dir="x",to=Math.abs(mCSB_container[0].offsetLeft)-(keyboardDir*(wrapper.width()*0.9));
								}else{
									var dir="y",to=Math.abs(mCSB_container[0].offsetTop)-(keyboardDir*(wrapper.height()*0.9));
								}
								_scrollTo($this,to.toString(),{dir:dir,scrollEasing:"mcsEaseInOut"});
							}
						}else if(code===35 || code===36){
							/* End (35), Home (36) */
							if(!$(document.activeElement).is(editables)){
								if(d.overflowed[0] || d.overflowed[1]){
									e.preventDefault();
									e.stopImmediatePropagation();
								}
								if(e.type==="keyup"){
									if(o.axis==="x" || (o.axis==="yx" &amp;&amp; d.overflowed[1] &amp;&amp; !d.overflowed[0])){
										var dir="x",to=code===35 ? Math.abs(wrapper.width()-mCSB_container.outerWidth(false)) : 0;
									}else{
										var dir="y",to=code===35 ? Math.abs(wrapper.height()-mCSB_container.outerHeight(false)) : 0;
									}
									_scrollTo($this,to.toString(),{dir:dir,scrollEasing:"mcsEaseInOut"});
								}
							}
						}
						break;
				}
				function _seq(a,c){
					seq.type=o.keyboard.scrollType;
					seq.scrollAmount=o.snapAmount || o.keyboard.scrollAmount;
					if(seq.type==="stepped" &amp;&amp; d.tweenRunning){return;}
					_sequentialScroll($this,a,c);
				}
			}
		},
		/* -------------------- */
		
		
		/* scrolls content sequentially (used when scrolling via buttons, keyboard arrows etc.) */
		_sequentialScroll=function(el,action,trigger,e,s){
			var d=el.data(pluginPfx),o=d.opt,seq=d.sequential,
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				once=seq.type==="stepped" ? true : false,
				steplessSpeed=o.scrollInertia &lt; 26 ? 26 : o.scrollInertia, /* 26/1.5=17 */
				steppedSpeed=o.scrollInertia &lt; 1 ? 17 : o.scrollInertia;
			switch(action){
				case "on":
					seq.dir=[
						(trigger===classes[16] || trigger===classes[15] || trigger===39 || trigger===37 ? "x" : "y"),
						(trigger===classes[13] || trigger===classes[15] || trigger===38 || trigger===37 ? -1 : 1)
					];
					_stop(el);
					if(_isNumeric(trigger) &amp;&amp; seq.type==="stepped"){return;}
					_on(once);
					break;
				case "off":
					_off();
					if(once || (d.tweenRunning &amp;&amp; seq.dir)){
						_on(true);
					}
					break;
			}
			/* starts sequence */
			function _on(once){
				var c=seq.type!=="stepped", /* continuous scrolling */
					t=s ? s : !once ? 1000/60 : c ? steplessSpeed/1.5 : steppedSpeed, /* timer */
					m=!once ? 2.5 : c ? 7.5 : 40, /* multiplier */
					contentPos=[Math.abs(mCSB_container[0].offsetTop),Math.abs(mCSB_container[0].offsetLeft)],
					ratio=[d.scrollRatio.y&gt;10 ? 10 : d.scrollRatio.y,d.scrollRatio.x&gt;10 ? 10 : d.scrollRatio.x],
					amount=seq.dir[0]==="x" ? contentPos[1]+(seq.dir[1]*(ratio[1]*m)) : contentPos[0]+(seq.dir[1]*(ratio[0]*m)),
					px=seq.dir[0]==="x" ? contentPos[1]+(seq.dir[1]*parseInt(seq.scrollAmount)) : contentPos[0]+(seq.dir[1]*parseInt(seq.scrollAmount)),
					to=seq.scrollAmount!=="auto" ? px : amount,
					easing=e ? e : !once ? "mcsLinear" : c ? "mcsLinearOut" : "mcsEaseInOut",
					onComplete=!once ? false : true;
				if(once &amp;&amp; t&lt;17){
					to=seq.dir[0]==="x" ? contentPos[1] : contentPos[0];
				}
				_scrollTo(el,to.toString(),{dir:seq.dir[0],scrollEasing:easing,dur:t,onComplete:onComplete});
				if(once){
					seq.dir=false;
					return;
				}
				clearTimeout(seq.step);
				seq.step=setTimeout(function(){
					_on();
				},t);
			}
			/* stops sequence */
			function _off(){
				clearTimeout(seq.step);
				_delete(seq,"step");
				_stop(el);
			}
		},
		/* -------------------- */
		
		
		/* returns a yx array from value */
		_arr=function(val){
			var o=$(this).data(pluginPfx).opt,vals=[];
			if(typeof val==="function"){val=val();} /* check if the value is a single anonymous function */
			/* check if value is object or array, its length and create an array with yx values */
			if(!(val instanceof Array)){ /* object value (e.g. {y:"100",x:"100"}, 100 etc.) */
				vals[0]=val.y ? val.y : val.x || o.axis==="x" ? null : val;
				vals[1]=val.x ? val.x : val.y || o.axis==="y" ? null : val;
			}else{ /* array value (e.g. [100,100]) */
				vals=val.length&gt;1 ? [val[0],val[1]] : o.axis==="x" ? [null,val[0]] : [val[0],null];
			}
			/* check if array values are anonymous functions */
			if(typeof vals[0]==="function"){vals[0]=vals[0]();}
			if(typeof vals[1]==="function"){vals[1]=vals[1]();}
			return vals;
		},
		/* -------------------- */
		
		
		/* translates values (e.g. "top", 100, "100px", "#id") to actual scroll-to positions */
		_to=function(val,dir){
			if(val==null || typeof val=="undefined"){return;}
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent(),
				t=typeof val;
			if(!dir){dir=o.axis==="x" ? "x" : "y";}
			var contentLength=dir==="x" ? mCSB_container.outerWidth(false) : mCSB_container.outerHeight(false),
				contentPos=dir==="x" ? mCSB_container[0].offsetLeft : mCSB_container[0].offsetTop,
				cssProp=dir==="x" ? "left" : "top";
			switch(t){
				case "function": /* this currently is not used. Consider removing it */
					return val();
					break;
				case "object": /* js/jquery object */
					var obj=val.jquery ? val : $(val);
					if(!obj.length){return;}
					return dir==="x" ? _childPos(obj)[1] : _childPos(obj)[0];
					break;
				case "string": case "number":
					if(_isNumeric(val)){ /* numeric value */
						return Math.abs(val);
					}else if(val.indexOf("%")!==-1){ /* percentage value */
						return Math.abs(contentLength*parseInt(val)/100);
					}else if(val.indexOf("-=")!==-1){ /* decrease value */
						return Math.abs(contentPos-parseInt(val.split("-=")[1]));
					}else if(val.indexOf("+=")!==-1){ /* inrease value */
						var p=(contentPos+parseInt(val.split("+=")[1]));
						return p&gt;=0 ? 0 : Math.abs(p);
					}else if(val.indexOf("px")!==-1 &amp;&amp; _isNumeric(val.split("px")[0])){ /* pixels string value (e.g. "100px") */
						return Math.abs(val.split("px")[0]);
					}else{
						if(val==="top" || val==="left"){ /* special strings */
							return 0;
						}else if(val==="bottom"){
							return Math.abs(wrapper.height()-mCSB_container.outerHeight(false));
						}else if(val==="right"){
							return Math.abs(wrapper.width()-mCSB_container.outerWidth(false));
						}else if(val==="first" || val==="last"){
							var obj=mCSB_container.find(":"+val);
							return dir==="x" ? _childPos(obj)[1] : _childPos(obj)[0];
						}else{
							if($(val).length){ /* jquery selector */
								return dir==="x" ? _childPos($(val))[1] : _childPos($(val))[0];
							}else{ /* other values (e.g. "100em") */
								mCSB_container.css(cssProp,val);
								methods.update.call(null,$this[0]);
								return;
							}
						}
					}
					break;
			}
		},
		/* -------------------- */
		
		
		/* calls the update method automatically */
		_autoUpdate=function(rem){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				mCSB_container=$("#mCSB_"+d.idx+"_container");
			if(rem){
				/* 
				removes autoUpdate timer 
				usage: _autoUpdate.call(this,"remove");
				*/
				clearTimeout(mCSB_container[0].autoUpdate);
				_delete(mCSB_container[0],"autoUpdate");
				return;
			}
			var	wrapper=mCSB_container.parent(),
				scrollbar=[$("#mCSB_"+d.idx+"_scrollbar_vertical"),$("#mCSB_"+d.idx+"_scrollbar_horizontal")],
				scrollbarSize=function(){return [
					scrollbar[0].is(":visible") ? scrollbar[0].outerHeight(true) : 0, /* returns y-scrollbar height */
					scrollbar[1].is(":visible") ? scrollbar[1].outerWidth(true) : 0 /* returns x-scrollbar width */
				]},
				oldSelSize=sizesSum(),newSelSize,
				os=[mCSB_container.outerHeight(false),mCSB_container.outerWidth(false),wrapper.height(),wrapper.width(),scrollbarSize()[0],scrollbarSize()[1]],ns,
				oldImgsLen=imgSum(),newImgsLen;
			upd();
			function upd(){
				clearTimeout(mCSB_container[0].autoUpdate);
				if($this.parents("html").length===0){
					/* check element in dom tree */
					$this=null;
					return;
				}
				mCSB_container[0].autoUpdate=setTimeout(function(){
					/* update on specific selector(s) length and size change */
					if(o.advanced.updateOnSelectorChange){
						newSelSize=sizesSum();
						if(newSelSize!==oldSelSize){
							doUpd(3);
							oldSelSize=newSelSize;
							return;
						}
					}
					/* update on main element and scrollbar size changes */
					if(o.advanced.updateOnContentResize){
						ns=[mCSB_container.outerHeight(false),mCSB_container.outerWidth(false),wrapper.height(),wrapper.width(),scrollbarSize()[0],scrollbarSize()[1]];
						if(ns[0]!==os[0] || ns[1]!==os[1] || ns[2]!==os[2] || ns[3]!==os[3] || ns[4]!==os[4] || ns[5]!==os[5]){
							doUpd(ns[0]!==os[0] || ns[1]!==os[1]);
							os=ns;
						}
					}
					/* update on image load */
					if(o.advanced.updateOnImageLoad){
						newImgsLen=imgSum();
						if(newImgsLen!==oldImgsLen){
							mCSB_container.find("img").each(function(){
								imgLoader(this);
							});
							oldImgsLen=newImgsLen;
						}
					}
					if(o.advanced.updateOnSelectorChange || o.advanced.updateOnContentResize || o.advanced.updateOnImageLoad){upd();}
				},o.advanced.autoUpdateTimeout);
			}
			/* returns images amount */
			function imgSum(){
				var total=0
				if(o.advanced.updateOnImageLoad){total=mCSB_container.find("img").length;}
				return total;
			}
			/* a tiny image loader */
			function imgLoader(el){
				if($(el).hasClass(classes[2])){doUpd(); return;}
				var img=new Image();
				function createDelegate(contextObject,delegateMethod){
					return function(){return delegateMethod.apply(contextObject,arguments);}
				}
				function imgOnLoad(){
					this.onload=null;
					$(el).addClass(classes[2]);
					doUpd(2);
				}
				img.onload=createDelegate(img,imgOnLoad);
				img.src=el.src;
			}
			/* returns the total height and width sum of all elements matching the selector */
			function sizesSum(){
				if(o.advanced.updateOnSelectorChange===true){o.advanced.updateOnSelectorChange="*";}
				var total=0,sel=mCSB_container.find(o.advanced.updateOnSelectorChange);
				if(o.advanced.updateOnSelectorChange &amp;&amp; sel.length&gt;0){sel.each(function(){total+=$(this).height()+$(this).width();});}
				return total;
			}
			/* calls the update method */
			function doUpd(cb){
				clearTimeout(mCSB_container[0].autoUpdate); 
				methods.update.call(null,$this[0],cb);
			}
		},
		/* -------------------- */
		
		
		/* snaps scrolling to a multiple of a pixels number */
		_snapAmount=function(to,amount,offset){
			return (Math.round(to/amount)*amount-offset); 
		},
		/* -------------------- */
		
		
		/* stops content and scrollbar animations */
		_stop=function(el){
			var d=el.data(pluginPfx),
				sel=$("#mCSB_"+d.idx+"_container,#mCSB_"+d.idx+"_container_wrapper,#mCSB_"+d.idx+"_dragger_vertical,#mCSB_"+d.idx+"_dragger_horizontal");
			sel.each(function(){
				_stopTween.call(this);
			});
		},
		/* -------------------- */
		
		
		/* 
		ANIMATES CONTENT 
		This is where the actual scrolling happens
		*/
		_scrollTo=function(el,to,options){
			var d=el.data(pluginPfx),o=d.opt,
				defaults={
					trigger:"internal",
					dir:"y",
					scrollEasing:"mcsEaseOut",
					drag:false,
					dur:o.scrollInertia,
					overwrite:"all",
					callbacks:true,
					onStart:true,
					onUpdate:true,
					onComplete:true
				},
				options=$.extend(defaults,options),
				dur=[options.dur,(options.drag ? 0 : options.dur)],
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent(),
				totalScrollOffsets=o.callbacks.onTotalScrollOffset ? _arr.call(el,o.callbacks.onTotalScrollOffset) : [0,0],
				totalScrollBackOffsets=o.callbacks.onTotalScrollBackOffset ? _arr.call(el,o.callbacks.onTotalScrollBackOffset) : [0,0];
			d.trigger=options.trigger;
			if(wrapper.scrollTop()!==0 || wrapper.scrollLeft()!==0){ /* always reset scrollTop/Left */
				$(".mCSB_"+d.idx+"_scrollbar").css("visibility","visible");
				wrapper.scrollTop(0).scrollLeft(0);
			}
			if(to==="_resetY" &amp;&amp; !d.contentReset.y){
				/* callbacks: onOverflowYNone */
				if(_cb("onOverflowYNone")){o.callbacks.onOverflowYNone.call(el[0]);}
				d.contentReset.y=1;
			}
			if(to==="_resetX" &amp;&amp; !d.contentReset.x){
				/* callbacks: onOverflowXNone */
				if(_cb("onOverflowXNone")){o.callbacks.onOverflowXNone.call(el[0]);}
				d.contentReset.x=1;
			}
			if(to==="_resetY" || to==="_resetX"){return;}
			if((d.contentReset.y || !el[0].mcs) &amp;&amp; d.overflowed[0]){
				/* callbacks: onOverflowY */
				if(_cb("onOverflowY")){o.callbacks.onOverflowY.call(el[0]);}
				d.contentReset.x=null;
			}
			if((d.contentReset.x || !el[0].mcs) &amp;&amp; d.overflowed[1]){
				/* callbacks: onOverflowX */
				if(_cb("onOverflowX")){o.callbacks.onOverflowX.call(el[0]);}
				d.contentReset.x=null;
			}
			if(o.snapAmount){to=_snapAmount(to,o.snapAmount,o.snapOffset);} /* scrolling snapping */
			switch(options.dir){
				case "x":
					var mCSB_dragger=$("#mCSB_"+d.idx+"_dragger_horizontal"),
						property="left",
						contentPos=mCSB_container[0].offsetLeft,
						limit=[
							mCustomScrollBox.width()-mCSB_container.outerWidth(false),
							mCSB_dragger.parent().width()-mCSB_dragger.width()
						],
						scrollTo=[to,to===0 ? 0 : (to/d.scrollRatio.x)],
						tso=totalScrollOffsets[1],
						tsbo=totalScrollBackOffsets[1],
						totalScrollOffset=tso&gt;0 ? tso/d.scrollRatio.x : 0,
						totalScrollBackOffset=tsbo&gt;0 ? tsbo/d.scrollRatio.x : 0;
					break;
				case "y":
					var mCSB_dragger=$("#mCSB_"+d.idx+"_dragger_vertical"),
						property="top",
						contentPos=mCSB_container[0].offsetTop,
						limit=[
							mCustomScrollBox.height()-mCSB_container.outerHeight(false),
							mCSB_dragger.parent().height()-mCSB_dragger.height()
						],
						scrollTo=[to,to===0 ? 0 : (to/d.scrollRatio.y)],
						tso=totalScrollOffsets[0],
						tsbo=totalScrollBackOffsets[0],
						totalScrollOffset=tso&gt;0 ? tso/d.scrollRatio.y : 0,
						totalScrollBackOffset=tsbo&gt;0 ? tsbo/d.scrollRatio.y : 0;
					break;
			}
			if(scrollTo[1]&lt;0 || (scrollTo[0]===0 &amp;&amp; scrollTo[1]===0)){
				scrollTo=[0,0];
			}else if(scrollTo[1]&gt;=limit[1]){
				scrollTo=[limit[0],limit[1]];
			}else{
				scrollTo[0]=-scrollTo[0];
			}
			if(!el[0].mcs){
				_mcs();  /* init mcs object (once) to make it available before callbacks */
				if(_cb("onInit")){o.callbacks.onInit.call(el[0]);} /* callbacks: onInit */
			}
			clearTimeout(mCSB_container[0].onCompleteTimeout);
			if(!d.tweenRunning &amp;&amp; ((contentPos===0 &amp;&amp; scrollTo[0]&gt;=0) || (contentPos===limit[0] &amp;&amp; scrollTo[0]&lt;=limit[0]))){return;}
			_tweenTo(mCSB_dragger[0],property,Math.round(scrollTo[1]),dur[1],options.scrollEasing);
			_tweenTo(mCSB_container[0],property,Math.round(scrollTo[0]),dur[0],options.scrollEasing,options.overwrite,{
				onStart:function(){
					if(options.callbacks &amp;&amp; options.onStart &amp;&amp; !d.tweenRunning){
						/* callbacks: onScrollStart */
						if(_cb("onScrollStart")){_mcs(); o.callbacks.onScrollStart.call(el[0]);}
						d.tweenRunning=true;
						_onDragClasses(mCSB_dragger);
						d.cbOffsets=_cbOffsets();
					}
				},onUpdate:function(){
					if(options.callbacks &amp;&amp; options.onUpdate){
						/* callbacks: whileScrolling */
						if(_cb("whileScrolling")){_mcs(); o.callbacks.whileScrolling.call(el[0]);}
					}
				},onComplete:function(){
					if(options.callbacks &amp;&amp; options.onComplete){
						if(o.axis==="yx"){clearTimeout(mCSB_container[0].onCompleteTimeout);}
						var t=mCSB_container[0].idleTimer || 0;
						mCSB_container[0].onCompleteTimeout=setTimeout(function(){
							/* callbacks: onScroll, onTotalScroll, onTotalScrollBack */
							if(_cb("onScroll")){_mcs(); o.callbacks.onScroll.call(el[0]);}
							if(_cb("onTotalScroll") &amp;&amp; scrollTo[1]&gt;=limit[1]-totalScrollOffset &amp;&amp; d.cbOffsets[0]){_mcs(); o.callbacks.onTotalScroll.call(el[0]);}
							if(_cb("onTotalScrollBack") &amp;&amp; scrollTo[1]&lt;=totalScrollBackOffset &amp;&amp; d.cbOffsets[1]){_mcs(); o.callbacks.onTotalScrollBack.call(el[0]);}
							d.tweenRunning=false;
							mCSB_container[0].idleTimer=0;
							_onDragClasses(mCSB_dragger,"hide");
						},t);
					}
				}
			});
			/* checks if callback function exists */
			function _cb(cb){
				return d &amp;&amp; o.callbacks[cb] &amp;&amp; typeof o.callbacks[cb]==="function";
			}
			/* checks whether callback offsets always trigger */
			function _cbOffsets(){
				return [o.callbacks.alwaysTriggerOffsets || contentPos&gt;=limit[0]+tso,o.callbacks.alwaysTriggerOffsets || contentPos&lt;=-tsbo];
			}
			/* 
			populates object with useful values for the user 
			values: 
				content: this.mcs.content
				content top position: this.mcs.top 
				content left position: this.mcs.left 
				dragger top position: this.mcs.draggerTop 
				dragger left position: this.mcs.draggerLeft 
				scrolling y percentage: this.mcs.topPct 
				scrolling x percentage: this.mcs.leftPct 
				scrolling direction: this.mcs.direction
			*/
			function _mcs(){
				var cp=[mCSB_container[0].offsetTop,mCSB_container[0].offsetLeft], /* content position */
					dp=[mCSB_dragger[0].offsetTop,mCSB_dragger[0].offsetLeft], /* dragger position */
					cl=[mCSB_container.outerHeight(false),mCSB_container.outerWidth(false)], /* content length */
					pl=[mCustomScrollBox.height(),mCustomScrollBox.width()]; /* content parent length */
				el[0].mcs={
					content:mCSB_container, /* original content wrapper as jquery object */
					top:cp[0],left:cp[1],draggerTop:dp[0],draggerLeft:dp[1],
					topPct:Math.round((100*Math.abs(cp[0]))/(Math.abs(cl[0])-pl[0])),leftPct:Math.round((100*Math.abs(cp[1]))/(Math.abs(cl[1])-pl[1])),
					direction:options.dir
				};
				/* 
				this refers to the original element containing the scrollbar(s)
				usage: this.mcs.top, this.mcs.leftPct etc. 
				*/
			}
		},
		/* -------------------- */
		
		
		/* 
		CUSTOM JAVASCRIPT ANIMATION TWEEN 
		Lighter and faster than jquery animate() and css transitions 
		Animates top/left properties and includes easings 
		*/
		_tweenTo=function(el,prop,to,duration,easing,overwrite,callbacks){
			if(!el._mTween){el._mTween={top:{},left:{}};}
			var callbacks=callbacks || {},
				onStart=callbacks.onStart || function(){},onUpdate=callbacks.onUpdate || function(){},onComplete=callbacks.onComplete || function(){},
				startTime=_getTime(),_delay,progress=0,from=el.offsetTop,elStyle=el.style,_request,tobj=el._mTween[prop];
			if(prop==="left"){from=el.offsetLeft;}
			var diff=to-from;
			tobj.stop=0;
			if(overwrite!=="none"){_cancelTween();}
			_startTween();
			function _step(){
				if(tobj.stop){return;}
				if(!progress){onStart.call();}
				progress=_getTime()-startTime;
				_tween();
				if(progress&gt;=tobj.time){
					tobj.time=(progress&gt;tobj.time) ? progress+_delay-(progress-tobj.time) : progress+_delay-1;
					if(tobj.time&lt;progress+1){tobj.time=progress+1;}
				}
				if(tobj.time&lt;duration){tobj.id=_request(_step);}else{onComplete.call();}
			}
			function _tween(){
				if(duration&gt;0){
					tobj.currVal=_ease(tobj.time,from,diff,duration,easing);
					elStyle[prop]=Math.round(tobj.currVal)+"px";
				}else{
					elStyle[prop]=to+"px";
				}
				onUpdate.call();
			}
			function _startTween(){
				_delay=1000/60;
				tobj.time=progress+_delay;
				_request=(!window.requestAnimationFrame) ? function(f){_tween(); return setTimeout(f,0.01);} : window.requestAnimationFrame;
				tobj.id=_request(_step);
			}
			function _cancelTween(){
				if(tobj.id==null){return;}
				if(!window.requestAnimationFrame){clearTimeout(tobj.id);
				}else{window.cancelAnimationFrame(tobj.id);}
				tobj.id=null;
			}
			function _ease(t,b,c,d,type){
				switch(type){
					case "linear": case "mcsLinear":
						return c*t/d + b;
						break;
					case "mcsLinearOut":
						t/=d; t--; return c * Math.sqrt(1 - t*t) + b;
						break;
					case "easeInOutSmooth":
						t/=d/2;
						if(t&lt;1) return c/2*t*t + b;
						t--;
						return -c/2 * (t*(t-2) - 1) + b;
						break;
					case "easeInOutStrong":
						t/=d/2;
						if(t&lt;1) return c/2 * Math.pow( 2, 10 * (t - 1) ) + b;
						t--;
						return c/2 * ( -Math.pow( 2, -10 * t) + 2 ) + b;
						break;
					case "easeInOut": case "mcsEaseInOut":
						t/=d/2;
						if(t&lt;1) return c/2*t*t*t + b;
						t-=2;
						return c/2*(t*t*t + 2) + b;
						break;
					case "easeOutSmooth":
						t/=d; t--;
						return -c * (t*t*t*t - 1) + b;
						break;
					case "easeOutStrong":
						return c * ( -Math.pow( 2, -10 * t/d ) + 1 ) + b;
						break;
					case "easeOut": case "mcsEaseOut": default:
						var ts=(t/=d)*t,tc=ts*t;
						return b+c*(0.499999999999997*tc*ts + -2.5*ts*ts + 5.5*tc + -6.5*ts + 4*t);
				}
			}
		},
		/* -------------------- */
		
		
		/* returns current time */
		_getTime=function(){
			if(window.performance &amp;&amp; window.performance.now){
				return window.performance.now();
			}else{
				if(window.performance &amp;&amp; window.performance.webkitNow){
					return window.performance.webkitNow();
				}else{
					if(Date.now){return Date.now();}else{return new Date().getTime();}
				}
			}
		},
		/* -------------------- */
		
		
		/* stops a tween */
		_stopTween=function(){
			var el=this;
			if(!el._mTween){el._mTween={top:{},left:{}};}
			var props=["top","left"];
			for(var i=0; i&lt;props.length; i++){
				var prop=props[i];
				if(el._mTween[prop].id){
					if(!window.requestAnimationFrame){clearTimeout(el._mTween[prop].id);
					}else{window.cancelAnimationFrame(el._mTween[prop].id);}
					el._mTween[prop].id=null;
					el._mTween[prop].stop=1;
				}
			}
		},
		/* -------------------- */
		
		
		/* deletes a property (avoiding the exception thrown by IE) */
		_delete=function(c,m){
			try{delete c[m];}catch(e){c[m]=null;}
		},
		/* -------------------- */
		
		
		/* detects left mouse button */
		_mouseBtnLeft=function(e){
			return !(e.which &amp;&amp; e.which!==1);
		},
		/* -------------------- */
		
		
		/* detects if pointer type event is touch */
		_pointerTouch=function(e){
			var t=e.originalEvent.pointerType;
			return !(t &amp;&amp; t!=="touch" &amp;&amp; t!==2);
		},
		/* -------------------- */
		
		
		/* checks if value is numeric */
		_isNumeric=function(val){
			return !isNaN(parseFloat(val)) &amp;&amp; isFinite(val);
		},
		/* -------------------- */
		
		
		/* returns element position according to content */
		_childPos=function(el){
			var p=el.parents(".mCSB_container");
			return [el.offset().top-p.offset().top,el.offset().left-p.offset().left];
		};
		/* -------------------- */
		
	
	
	
	
	/* 
	----------------------------------------
	PLUGIN SETUP 
	----------------------------------------
	*/
	
	/* plugin constructor functions */
	$.fn[pluginNS]=function(method){ /* usage: $(selector).mCustomScrollbar(); */
		if(methods[method]){
			return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
		}else if(typeof method==="object" || !method){
			return methods.init.apply(this,arguments);
		}else{
			$.error("Method "+method+" does not exist");
		}
	};
	$[pluginNS]=function(method){ /* usage: $.mCustomScrollbar(); */
		if(methods[method]){
			return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
		}else if(typeof method==="object" || !method){
			return methods.init.apply(this,arguments);
		}else{
			$.error("Method "+method+" does not exist");
		}
	};
	
	/* 
	allow setting plugin default options. 
	usage: $.mCustomScrollbar.defaults.scrollInertia=500; 
	to apply any changed default options on default selectors (below), use inside document ready fn 
	e.g.: $(document).ready(function(){ $.mCustomScrollbar.defaults.scrollInertia=500; });
	*/
	$[pluginNS].defaults=defaults;
	
	/* 
	add window object (window.mCustomScrollbar) 
	usage: if(window.mCustomScrollbar){console.log("custom scrollbar plugin loaded");}
	*/
	window[pluginNS]=true;
	
	$(window).load(function(){
		
		$(defaultSelector)[pluginNS](); /* add scrollbars automatically on default selector */
		
		/* extend jQuery expressions */
		$.extend($.expr[":"],{
			/* checks if element is within scrollable viewport */
			mcsInView:$.expr[":"].mcsInView || function(el){
				var $el=$(el),content=$el.parents(".mCSB_container"),wrapper,cPos;
				if(!content.length){return;}
				wrapper=content.parent();
				cPos=[content[0].offsetTop,content[0].offsetLeft];
				return 	cPos[0]+_childPos($el)[0]&gt;=0 &amp;&amp; cPos[0]+_childPos($el)[0]&lt;wrapper.height()-$el.outerHeight(false) &amp;&amp; 
						cPos[1]+_childPos($el)[1]&gt;=0 &amp;&amp; cPos[1]+_childPos($el)[1]&lt;wrapper.width()-$el.outerWidth(false);
			},
			/* checks if element is overflowed having visible scrollbar(s) */
			mcsOverflow:$.expr[":"].mcsOverflow || function(el){
				var d=$(el).data(pluginPfx);
				if(!d){return;}
				return d.overflowed[0] || d.overflowed[1];
			}
		});
	
	});

}))}));;/*!
 * hoverIntent v1.8.3 // 2014.08.11 // jQuery v1.9.1+
 * http://cherne.net/brian/resources/jquery.hoverIntent.html
 *
 * You may use hoverIntent under the terms of the MIT license. Basically that
 * means you are free to use hoverIntent as long as this header is left intact.
 * Copyright 2007, 2014 Brian Cherne
 */
 
/* hoverIntent is similar to jQuery's built-in "hover" method except that
 * instead of firing the handlerIn function immediately, hoverIntent checks
 * to see if the user's mouse has slowed down (beneath the sensitivity
 * threshold) before firing the event. The handlerOut function is only
 * called after a matching handlerIn.
 *
 * // basic usage ... just like .hover()
 * .hoverIntent( handlerIn, handlerOut )
 * .hoverIntent( handlerInOut )
 *
 * // basic usage ... with event delegation!
 * .hoverIntent( handlerIn, handlerOut, selector )
 * .hoverIntent( handlerInOut, selector )
 *
 * // using a basic configuration object
 * .hoverIntent( config )
 *
 * @param  handlerIn   function OR configuration object
 * @param  handlerOut  function OR selector for delegation OR undefined
 * @param  selector    selector OR undefined
 * @author Brian Cherne &lt;brian(at)cherne(dot)net&gt;
 */
(function($) {
    $.fn.hoverIntent = function(handlerIn,handlerOut,selector) {

        // default configuration values
        var cfg = {
            interval: 100,
            sensitivity: 6,
            timeout: 0
        };

        if ( typeof handlerIn === "object" ) {
            cfg = $.extend(cfg, handlerIn );
        } else if ($.isFunction(handlerOut)) {
            cfg = $.extend(cfg, { over: handlerIn, out: handlerOut, selector: selector } );
        } else {
            cfg = $.extend(cfg, { over: handlerIn, out: handlerIn, selector: handlerOut } );
        }

        // instantiate variables
        // cX, cY = current X and Y position of mouse, updated by mousemove event
        // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
        var cX, cY, pX, pY;

        // A private function for getting mouse position
        var track = function(ev) {
            cX = ev.pageX;
            cY = ev.pageY;
        };

        // A private function for comparing current and previous mouse position
        var compare = function(ev,ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            // compare mouse positions to see if they've crossed the threshold
            if ( Math.sqrt( (pX-cX)*(pX-cX) + (pY-cY)*(pY-cY) ) &lt; cfg.sensitivity ) {
                $(ob).off("mousemove.hoverIntent",track);
                // set hoverIntent state to true (so mouseOut can be called)
                ob.hoverIntent_s = true;
                return cfg.over.apply(ob,[ev]);
            } else {
                // set previous coordinates for next time
                pX = cX; pY = cY;
                // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
                ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
            }
        };

        // A private function for delaying the mouseOut function
        var delay = function(ev,ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            ob.hoverIntent_s = false;
            return cfg.out.apply(ob,[ev]);
        };

        // A private function for handling mouse 'hovering'
        var handleHover = function(e) {
            // copy objects to be passed into t (required for event object to be passed in IE)
            var ev = $.extend({},e);
            var ob = this;

            // cancel hoverIntent timer if it exists
            if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

            // if e.type === "mouseenter"
            if (e.type === "mouseenter") {
                // set "previous" X and Y position based on initial entry point
                pX = ev.pageX; pY = ev.pageY;
                // update "current" X and Y position based on mousemove
                $(ob).on("mousemove.hoverIntent",track);
                // start polling interval (self-calling timeout) to compare mouse coordinates over time
                if (!ob.hoverIntent_s) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

                // else e.type == "mouseleave"
            } else {
                // unbind expensive mousemove event
                $(ob).off("mousemove.hoverIntent",track);
                // if hoverIntent state is true, then call the mouseOut function after the specified delay
                if (ob.hoverIntent_s) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
            }
        };

        // listen for mouseenter and mouseleave
        return this.on({'mouseenter.hoverIntent':handleHover,'mouseleave.hoverIntent':handleHover}, cfg.selector);
    };
})(jQuery);
;var CupSell = {
	Generator: {
		defaultProduct: null,
		defaultProductURL: null,

		confirmDialog: function(header, message, callback) {

			if ($('#generatorInIframe').val() == 1) {
				var position = [500];
			} else {
				var position = false;
			}

			$('#confirmDialog &gt; h4').html(header);
			$('#confirmDialog &gt; p').html(message);
			$('#confirmDialog').modal({
				onOpen: function (dialog) {
					dialog.overlay.fadeIn(150, function () {
						dialog.container.show();
						dialog.data.show();
					});
				},
				onShow: function (dialog) {
					$('.ok', dialog.data[0]).click(function () {
						if ($.isFunction(callback)) {
							callback.apply();
						}
						$.modal.close();
					});
				},
				escClose: true,
				overlayClose: true,
				position: position
			});
		},

		errorDialog: function(header, message) {

			if ($('#generatorInIframe').val() == 1) {
				var position = [500];
			} else {
				var position = false;
			}

			$('#errorDialog &gt; h4').html(header);
			$('#errorDialog &gt; p').html(message);
			$('#errorDialog').modal({
				onOpen: function (dialog) {
					dialog.overlay.fadeIn(150, function () {
						dialog.container.show();
						dialog.data.show();
					});
				},
				escClose: true,
				overlayClose: true,
				position: position
			});
		},

		messageDialog: function(header, message) {

			if ($('#generatorInIframe').val() == 1) {
				var position = [500];
			} else {
				var position = false;
			}

			$('#messageDialog &gt; h4').html(header);
			$('#messageDialog &gt; p').html(message);
			$('#messageDialog').modal({
				onOpen: function (dialog) {
					dialog.overlay.fadeIn(150, function () {
						dialog.container.show();
						dialog.data.show();
					});
				},
				escClose: true,
				overlayClose: true,
				position: position
			});
		},

		refreshBasketItems: function () {
			$.ajax({
				url: '/generator-ajax/index',
				type: 'post',
				data: {'mod': 'basket', 'act': 'refresh'},
				dataType: 'json',

				success: function(response) {
					CupSell.Generator.redrawBasketItems(response[0].basket, response[0].dropdown, response[0].currency);
				}
			});
		},

		redrawBasketItems: function (basketData, dropdownData, currency) {
			var counter = 0;
			var price = 0;

                        $.each(basketData, function (k, v) {
				counter++;
				price += v.price;
			});
			$('#cart_product_count').html(counter);
			$('#cart_product_sum').html(number_format(price, currency.decimal_places, ',', '') + ' ' + currency.suffix);
			$('#shopping_cart_dropdown').html(dropdownData);
		}
	}
};


// Init generator application
(function() {
	$(document).ready(function () {

		//relocate in case of no canvas object
		var isSupported = !!window.CanvasRenderingContext2D;

		if(!isSupported) {

			var txt = '&lt;div class="nosupport-info"&gt;&lt;p&gt;Niestety, Twoja przeglÄ…darka jest zbyt stara, aby nasz generator dziaÅ‚aÅ‚ na niej poprawnie.&lt;/p&gt;';
			txt += '&lt;p&gt;Uruchom generator w nowoczesnej przeglÄ…darce (np. &lt;a href="https://www.google.com/intl/pl/chrome/browser/"&gt;Chrome&lt;/a&gt; lub &lt;a href="http://www.mozilla.org/pl/firefox/fx/"&gt;Firefox&lt;/a&gt;)&lt;/p&gt;&lt;/div&gt;';

			$('#generator').html(txt);
			return;
		}


		// Init storage, ttl = 7days
		CupSell.Generator.StorageManager.init('CupSell.Generator', $('#generator').data('version'), 604800);

		// Init shopping section
		CupSell.Generator.Basket.init($('#price &gt; span'), $('#quantity'));

		$('.dialog .button.cancel').on('click', function () {
			$.modal.close();
		});

		//Set default product
		CupSell.Generator.defaultProduct = $('#generator').data('defaultproduct')
			? $('#generator').data('defaultproduct')
			: parseInt($('#products ol li:first-child a').attr('rel'));
		CupSell.Generator.defaultProductURL = $('#generator').data('defaultproducturl');

		// Load small basket items
		CupSell.Generator.refreshBasketItems();

	});
})();;CupSell.Generator.Basket = (function () {

    var _productPrice = 0,
            _quantity = 1,
            _printPrices = {},
            _selectedSize = undefined,
            _selectedSex = undefined,
            _commission = undefined,
            _commissionType = undefined,
            _priceField = undefined,
            _quantityField = undefined;


    /**
     * Reset product shopping options
     */
    function _reset()
    {
        _productPrice = 0;
        _quantity = 1;
        _quantityField.val(1);
        _printPrices = {};
        _selectedSize = undefined;
        _selectedSex = undefined;
    }


    /**
     * Calculate product price
     *
     * @return Float
     */
    function _calculatePrice()
    {
        var price = _productPrice;

        $.each(CupSell.Generator.Canvas.getPrints(), function (key, value) {
            if (typeof (_printPrices[value]) != 'undefined') {
                price += _printPrices[value];
            }
        });

        switch (_commissionType) {
            case 0:
                {
                    price += _commission;
                }
                break;

            case 1:
                {
                    price += price * (_commission / 100);
                }
                break;
        }


        return (price * _quantity).toFixed(2).replace('.', ',');
    }


    /**
     * Display shopping option dialog
     */
    function _shoppingOptionDialog() {

        if ($('#generatorInIframe').val() == 1) {
            var position = [500];
        } else {
            var position = false;
        }

        $('#shoppingOptionGenerator').modal({
            onOpen: function (dialog) {
                dialog.overlay.fadeIn(150, function () {
                    dialog.container.show();
                    dialog.data.show();
                });
            },
            escClose: true,
            overlayClose: true,
            position: position
        });
    }


    /**
     * Display size chooser dialog
     *
     * @param function callback Function to apply after ok
     */
    function _sizeOptionDialog(callback) {

        if ($('#generatorInIframe').val() == 1) {
            var position = [500];
        } else {
            var position = false;
        }

        $('#chooseSizeDialog').modal({
            onOpen: function (dialog) {
                dialog.overlay.fadeIn(150, function () {
                    dialog.container.show();
                    dialog.data.show();
                });
            },
            onShow: function (dialog) {
                $('.ok', dialog.data[0]).click(function (event) {
                    if (!$(event.currentTarget).hasClass('disabled')) {
                        $.modal.close();
                        if ($.isFunction(callback)) {
                            callback.apply();
                        }
                    }
                });
            },
            escClose: true,
            overlayClose: true,
            position: position
        });
    }


    /**
     * Init basket
     *
     * @param DOMelement priceField
     * @param DOMelement quantityField
     */
    function _init(priceField, quantityField) {
        _priceField = priceField;
        _quantityField = quantityField;

        _quantityField.numeric(false);
        _quantityField.on('blur', function (event) {
            if (_quantityField.val() &lt; 1) {
                _quantityField.val(1);
            }
            CupSell.Generator.Basket.setQuantity(_quantityField.val());
            CupSell.Generator.Basket.updatePrice();
        });

        _commission = typeof ($('#mval').val()) !== 'undefined' ? parseFloat($('#mval').val().replace(',', '.')) : 0;
        _commissionType = parseInt($('#mtype').val());

        $('#csBasketOptionContinue').click(function (event) {
            CupSell.Generator.Canvas.generate(CupSell.Generator.Canvas.generateBasketItem, [false]);
            $.modal.close();
        });

        $('#csBasketOptionFinish').click(function (event) {
            CupSell.Generator.Canvas.generate(CupSell.Generator.Canvas.generateBasketItem, [true]);
            $.modal.close();
        });

        $("#quantitySelector &gt; span.dec").on('click', function (event) {
            event.stopPropagation();
            if (CupSell.Generator.Basket.getQuantity() &gt; 1) {
                CupSell.Generator.Basket.setQuantity(
                        CupSell.Generator.Basket.getQuantity() - 1
                        );
                CupSell.Generator.Basket.updatePrice();
                _quantityField.val(CupSell.Generator.Basket.getQuantity());
            }
        });

        $("#quantitySelector &gt; span.inc").on('click', function (event) {
            event.stopPropagation();
            CupSell.Generator.Basket.setQuantity(
                    CupSell.Generator.Basket.getQuantity() + 1
                    );
            CupSell.Generator.Basket.updatePrice();
            _quantityField.val(CupSell.Generator.Basket.getQuantity());
        });

        $("#shopBox").on('submit', function (event) {
            event.stopPropagation();
            event.preventDefault();
        });
    }

    /**
     * Export interface
     */
    return {
        /**
         * Select product size
         *
         * @param Integer size
         */
        setSelectedSize: function (size)
        {
            _selectedSize = size;
        },
        /**
         * Get selected product size
         *
         * @return Integer
         */
        getSelectedSize: function ()
        {
            return _selectedSize;
        },
        /**
         * Select product sex
         *
         * @param Integer sex
         */
        setSelectedSex: function (sex)
        {
            _selectedSex = sex;
        },
        /**
         * Select product sex
         *
         * @param Integer sex
         */
        setCommision: function (commission)
        {
            _commission = commission;
        },
        /**
         * Get selected product sex
         *
         * @return Integer
         */
        getSelectedSex: function ()
        {
            return _selectedSex;
        },
        /**
         * Set product quantity
         *
         * @param Integer quantity
         */
        setQuantity: function (quantity)
        {
            _quantity = parseInt(quantity);
        },
        /**
         * Get product quantity
         *
         * @return Integer
         */
        getQuantity: function ()
        {
            return _quantity;
        },
        /**
         * Set product price
         *
         * @param Float price
         */
        setProductPrice: function (price)
        {
            _productPrice = price;
        },
        /**
         * Get product price
         *
         * @param Float
         */
        getProductPrice: function ()
        {
            return _productPrice;
        },
        /**
         * Set product price for each view
         *
         * @param Object prices
         */
        setProductPrintPrices: function (prices)
        {
            _printPrices = prices
        },
        /**
         * Get print price for product view
         *
         *  @param Integer viewId
         *  @retyrn Float
         */
        getProductPrintPrice: function (viewId)
        {
            return _printPrices[viewId];
        },
        /**
         * Update price field
         */
        updatePrice: function ()
        {
            _priceField.html(_calculatePrice());
        },
        /**
         * Clear options
         *
         * @see _reset()
         */
        clear: _reset,
        /**
         * Calculate product price
         *
         * @see _calculatePrice()
         */
        calculatePrice: _calculatePrice,
        /**
         * Display shopping option dialog
         *
         * @see _shoppingOptionDialog()
         */
        shoppingOptionDialog: _shoppingOptionDialog,
        /**
         * Display size option dialog
         *
         * @see _sizeOptionDialog()
         */
        sizeOptionDialog: _sizeOptionDialog,
        /**
         * Initialize shopping basket options
         *
         * @see _init()
         */
        init: _init
    };

})();;/**
 * Editor
 *
 */
CupSell.Generator.Editor = (function()
{
//TODO: na razie jest obsÅ‚ugiwany przy zaÅ‚oÅ¼eniu, Å¼e jest window.getSelection() - a co jeÅ›li nie ma ?
	var _editor = undefined,
		_hasFocus = false,
		_range = undefined,
		_offset = undefined,
		_productColor = '#FFFFFF',
		_isCtrlDown = false,
		_isPaste = false;

	$(document).ready(function()
	{
		_editor = $('#txtEditor').attr('contentEditable', true);
		
		_loadFonts();


		/**
		 * Editor onMouseUp event
		 * If Editor text content is empty prepare span chunk
		 *
		 * @param Event event
		 */
		_editor.mouseup(function(event)
		{
			var selection = undefined,
				txtColor = undefined; //_colorToHex(_editor.css('backgroundColor')) == '#000000' ? '#FFFFFF' : '#000000';
			
			if(CupSell.Generator.Views.getFontColor()) {
				txtColor = CupSell.Generator.Views.getFontColor();
			} else {
				txtColor = _getBackgroundColor() == '#000000' ? '#FFFFFF' : '#000000';
			}
			
			if(window.getSelection) {
				if(_getHTML() == '') {
					_editor.html('&lt;span style="font-family: ' + $('#font')[0].value + '; font-size: ' + $('#size')[0].value + 'px; color: ' + txtColor + ';"&gt;&amp;nbsp;&lt;/span&gt;');
	
					// set cursor inside span
					selection = window.getSelection();
					_range = document.createRange();
					_range.setStart(document.getElementById("txtEditor").childNodes[0], 0);
					_range.collapse(true);
					selection.removeAllRanges();
					selection.addRange(_range);
					_offset = _range.startOffset;
					
				} else {
					selection = window.getSelection();
					_range = selection.getRangeAt(0);
	
					if(selection.anchorNode.parentElement.tagName.toUpperCase() == 'SPAN' &amp;&amp; selection.anchorNode.parentElement.innerHTML == '&amp;nbsp;') {
						_range.setStart(_range.startContainer, 0);
						_range.collapse(true);
						selection.removeAllRanges();
						selection.addRange(_range);
					}
					
					_offset = _range.startOffset;
				}
			}

			if(selection.anchorNode.parentElement.tagName.toUpperCase() == 'SPAN') {
				_setFontAndSize($(selection.anchorNode.parentElement).css('fontFamily'), $(selection.anchorNode.parentElement).css('fontSize'));
			}


			_hasFocus = true;
		});
		
		
		_editor.keydown(function(event)
		{
			if(event.which == 17) {
				_isCtrlDown = true;
			}
			
			if(event.which == 86 &amp;&amp; _isCtrlDown) {
				_isPaste = true;
			}
		});


		/**
		 * Editor onKeyUp Event
		 * Passes current editor text to selected canvas object
		 *
		 * @param Event event
		 */
		_editor.keyup(function(event)
		{
			var activeBoxId = CupSell.Generator.Canvas.getActiveBoxId(),
				html = undefined,
				span = undefined,
				fragments = undefined,
				selection = undefined,
				range = undefined,
				htmlChunk = undefined,
				boxHtml = undefined,
				boxHtmlChunk = undefined,
				boxWidth = undefined,
				boxHeight = undefined,
				boxLineWidth = undefined,
				boxLineOffset = undefined,
				txtColor = undefined;
			
				if(CupSell.Generator.Views.getFontColor()) {
					txtColor = CupSell.Generator.Views.getFontColor();
				} else {
					txtColor = _getBackgroundColor() == '#000000' ? '#FFFFFF' : '#000000';
				}
			
			//FF when selected all text (ctrl + A) and deleted
			if(_editor.html() == '&lt;br&gt;') {

				_editor.html('&lt;span style="font-family: ' + $('#font')[0].value + '; font-size: ' + $('#size')[0].value + 'px; color: ' + txtColor + ';"&gt;&amp;nbsp;&lt;/span&gt;');

				// set cursor inside span
				if(window.getSelection) {
					selection = window.getSelection();
					range = document.createRange();
					range.setStart(document.getElementById("txtEditor").childNodes[0], 0);
					range.collapse(true);
					selection.removeAllRanges();
					selection.addRange(range);
				}
			}
			
//TODO: jedna metoda, ktÃ³ra zwrÃ³ci wszytkie propsy zwiÄ…zane z tekstem w paczce			
			if(activeBoxId) {
				boxWidth = CupSell.Generator.Canvas.getProperty(activeBoxId, 'width');
				boxHeight = CupSell.Generator.Canvas.getProperty(activeBoxId, 'height');
				boxHtml = CupSell.Generator.Canvas.getProperty(activeBoxId, 'html');
				boxHtmlChunk = CupSell.Generator.Canvas.getProperty(activeBoxId, 'htmlChunk');
				boxLineWidth = CupSell.Generator.Canvas.getProperty(activeBoxId, 'lineWidth');
				boxLineOffset = CupSell.Generator.Canvas.getProperty(activeBoxId, 'lineOffset');
			}
			
			if(event.which == 17) {
				_isCtrlDown = false;
			}
			
			if(event.which == 86 &amp;&amp; _isPaste) {
				_isPaste = false;
				_editor.html('&lt;span style="font-family: ' + $('#font')[0].value + '; font-size: ' + $('#size')[0].value + 'px; color: ' + txtColor + ';"&gt;' + _editor.text() + '&lt;/span&gt;')
			}
			
			// if ENTER pressed we need to split current span into chunks surrounding breaks
			if(event.which == 13) {
				if(window.getSelection) {

					html = $(this).html();

					//some browsers (chrome) wraps text after enter into span and div
					if(html.indexOf('&lt;div&gt;') != -1) {
						html = html.replace(/&lt;div&gt;(.*)&lt;\/div&gt;/, '&lt;br id="heartbreaker"&gt;$1');
						html = html.replace(/&lt;font[^&gt;]*&gt;&lt;br&gt;&lt;\/font&gt;/, '&lt;br&gt;');
						html = html.replace(/&lt;span([^&gt;]*)&gt;&lt;br&gt;&lt;\/span&gt;/, '&lt;span$1&gt;&amp;nbsp;&lt;\/span&gt;');
						$(this).html(html);

						// set cursor inside new span
						
						if(document.getElementById('heartbreaker')) {
							selection = window.getSelection();
							range = document.createRange();
	
							range.setStartAfter(document.getElementById('heartbreaker'));
							range.collapse(true);
							selection.removeAllRanges();
							selection.addRange(range);
	
							document.getElementById('heartbreaker').removeAttribute('id');
						}

					//some (IE, opera) wraps all chunks into span and p
					} else if(html.indexOf('&lt;p&gt;') != -1) {
						selection = window.getSelection();
						
						if(selection.anchorNode.nodeName.toUpperCase() == 'SPAN') {
							selection.anchorNode.setAttribute('id', 'csfocus');
						} else if(selection.anchorNode.parentNode.nodeName.toUpperCase() == 'SPAN') {
							selection.anchorNode.parentNode.setAttribute('id', 'csfocus');
						}

						$(this).html($(this).html().replace(/&lt;p&gt;(.*?)(&lt;\/p&gt;)/g, '$1&lt;br&gt;'));

						// set cursor inside new span
						if(document.getElementById('csfocus')) {
							range = document.createRange();
							range.setStart(document.getElementById("csfocus"), 0);
							range.collapse(true);
							selection.removeAllRanges();
							selection.addRange(range);
	
							document.getElementById('csfocus').removeAttribute('id');
						}
	
					// some (firefox) inserts only &lt;br&gt;
					} else {
						selection = window.getSelection();
						span = selection.anchorNode;
						
						var length = 0;
						var node = undefined;
						
						if(span.nodeName.toUpperCase() == 'SPAN') {
							for(var i = 0; i &lt; span.childNodes.length; i++) {
								if(span.childNodes[i].nodeName.toUpperCase() == 'BR') {
									if(_offset == length) {
										if(span.childNodes[i + 1] &amp;&amp; span.childNodes[i + 1].nodeName.toUpperCase() == 'BR') {
											node = document.createElement('br');
											span.parentNode.insertBefore(node, span);
											
											node = document.createElement('span');
											node.setAttribute('style', span.attributes.style.value);
											node.setAttribute('id', 'csfocus');
											length++;
										} else {
											node = document.createElement('br');
										}
									} else {
										node = document.createElement('br');
									}
								} else {
									node = document.createElement('span');
									node.setAttribute('style', span.attributes.style.value);
									
									if(_offset == length) {
										node.setAttribute('id', 'csfocus');
									}
									
									var content = document.createTextNode(span.childNodes[i].textContent);
									length += span.childNodes[i].textContent.length;

									node.appendChild(content);
								}
								
								span.parentNode.insertBefore(node, span);
							}
							
							span.parentNode.removeChild(span);
						}
						
						if(document.getElementById('csfocus')) {
							range = document.createRange();
							range.setStart(document.getElementById('csfocus'), 0);
							range.collapse(true);
							selection.removeAllRanges();
							selection.addRange(range);
	
							document.getElementById('csfocus').removeAttribute('id');
						}
					}
				}
			} else {
				selection = window.getSelection();
				range = selection.getRangeAt(0);

				if(selection.anchorNode.parentElement.tagName.toUpperCase() == 'SPAN') {
					if(selection.anchorNode.parentElement.innerHTML == '&amp;nbsp;') {
						selection.anchorNode.parentElement.innerHTML = '';
						range.setStart(range.startContainer, 0);
						range.collapse(true);
						selection.removeAllRanges();
						selection.addRange(range);
						
//					} else if(/.{1}(&amp;nbsp;){1}$/.test(selection.anchorNode.parentElement.innerHTML)) {
//						var offset = range.startOffset;
//						selection.anchorNode.parentElement.innerHTML = selection.anchorNode.parentElement.innerHTML.replace('&amp;nbsp;', '');
//						range.setStart(range.startContainer, offset - 1);
//						range.collapse(true);
//						selection.removeAllRanges();
//						selection.addRange(range);
					}
				}
		
				if(selection.anchorNode.parentNode.nodeName.toUpperCase() == 'DIV') {

					if(selection.anchorNode.nodeName.toUpperCase() != 'DIV') {
	
						var node = document.createElement('span');
						node.setAttribute('style', 'font-family: ' + $('#font')[0].value + '; font-size: ' + $('#size')[0].value + 'px; color: ' + txtColor + ';');
						node.setAttribute('id', 'csfocus');
						
						var content = document.createTextNode(selection.anchorNode.textContent);

						node.appendChild(content);
						
						selection.anchorNode.parentNode.insertBefore(node, selection.anchorNode);
						selection.anchorNode.parentNode.removeChild(selection.anchorNode);
		
						if(document.getElementById('csfocus')) {
							range = document.createRange();
							range.setStart(document.getElementById('csfocus'), 1);
							range.collapse(true);
							selection.removeAllRanges();
							selection.addRange(range);
							
							document.getElementById('csfocus').removeAttribute('id');
						}
					}
				}
			}
			
			_offset = window.getSelection().getRangeAt(0).startOffset;

			if(activeBoxId) {
				if(boxHtml != $(this).html()) {
					
					htmlChunk = _getSpanChunks();
				
					CupSell.Generator.Canvas.setProperty(activeBoxId, 'htmlChunk', htmlChunk, true);
					CupSell.Generator.Canvas.setProperty(activeBoxId, 'html', $(this).html());
					
					if(!_isEmpty()) {
						CupSell.Generator.Canvas.setUnReDoProps(activeBoxId, {
							start: {
								width: boxWidth, 
								height: boxHeight, 
								html: boxHtml, 
								htmlChunk: boxHtmlChunk,
								lineWidth: boxLineWidth,
								lineOffset: boxLineOffset
							}, 
							end: {
								width: CupSell.Generator.Canvas.getProperty(activeBoxId, 'width'),
								height: CupSell.Generator.Canvas.getProperty(activeBoxId, 'height'),
								html: _editor.html(),
								htmlChunk: htmlChunk,
								lineWidth: CupSell.Generator.Canvas.getProperty(activeBoxId, 'lineWidth'),
								lineOffset: CupSell.Generator.Canvas.getProperty(activeBoxId, 'lineOffset')
							}
						});
					}
				}
			}
		});

		
		/**
		 * Editor onFocus Event
		 *
		 * @param Event event
		 */
		_editor.focus(function(event)
		{
			var activeBoxId = CupSell.Generator.Canvas.getActiveBoxId();
			
			if(!activeBoxId &amp;&amp; _editor.html().indexOf('&gt;Wpisz tekst&lt;/span&gt;') != -1) {
				_editor.html('');
			}
		});
		


		/**
		 * Editor onBlur Event
		 * If Editor is empty remove active text box
		 *
		 * @param Event event
		 */
		_editor.blur(function(event)
		{
			var activeBoxId = CupSell.Generator.Canvas.getActiveBoxId();

			if(activeBoxId &amp;&amp; $('#' + activeBoxId).hasClass('txtBox')) {
				if(_isEmpty()) {
					CupSell.Generator.Canvas.removeBox(activeBoxId);
				}
			}
		});


		/**
		 * Add text button onClick Event
		 * Creates new TextBox
		 */
		$('#addTxt').click(function()
		{
			if(_editor[0].textContent.replace(/\s/g, '') == '') {
				return;
			}
			
			if(_editor.children('span').length == 1) {
				_editor.html($.trim(_editor.html().replace(/\s&lt;br&gt;/, '').replace('&amp;nbsp;', '')));
			}

			CupSell.Generator.Canvas.createTxtBox(_editor.css('textAlign'));
		});


		/**
		 * Text reset button onClick Event
		 * Resets text of selected text object to initial values
		 */
		$('#txtreset').click(function()
		{
			var activeBoxId = CupSell.Generator.Canvas.getActiveBoxId(),
				boxWidth = undefined,
				boxHeight = undefined,
				boxLineWidth = undefined,
				boxLineOffset = undefined,
				boxHtml = undefined,
				boxHtmlChunk = undefined;

			if(activeBoxId &amp;&amp; $('#' + activeBoxId).hasClass('txtBox')) {
				CupSell.Generator.confirmDialog(
					translation.editPrint, translation.removeEditPrint, function() 
					{
						boxWidth = CupSell.Generator.Canvas.getProperty(activeBoxId, 'width');
						boxHeight = CupSell.Generator.Canvas.getProperty(activeBoxId, 'height');
						boxLineWidth = CupSell.Generator.Canvas.getProperty(activeBoxId, 'lineWidth');
						boxLineOffset = CupSell.Generator.Canvas.getProperty(activeBoxId, 'lineOffset');
						boxHtml = CupSell.Generator.Canvas.getProperty(activeBoxId, 'html');
						boxHtmlChunk = CupSell.Generator.Canvas.getProperty(activeBoxId, 'htmlChunk');
						
						CupSell.Generator.Canvas.resetTxt(activeBoxId);
						
						CupSell.Generator.Canvas.setUnReDoProps(activeBoxId, {
							start: {
								width: boxWidth, 
								height: boxHeight, 
								html: boxHtml, 
								htmlChunk: boxHtmlChunk,
								lineWidth: boxLineWidth,
								lineOffset: boxLineOffset
							}, 
							end: {
								width: CupSell.Generator.Canvas.getProperty(activeBoxId, 'width'),
								height: CupSell.Generator.Canvas.getProperty(activeBoxId, 'height'),
								html: CupSell.Generator.Canvas.getProperty(activeBoxId, 'html'),
								htmlChunk: CupSell.Generator.Canvas.getProperty(activeBoxId, 'htmlChunk'),
								lineWidth: CupSell.Generator.Canvas.getProperty(activeBoxId, 'lineWidth'),
								lineOffset: CupSell.Generator.Canvas.getProperty(activeBoxId, 'lineOffset')
							}
						});
						
						_setAlign('left');
//						$('#txtreset').attr('disabled', true);
					}
				);
			} else {
				
				var txtColor = undefined;
				
				if(CupSell.Generator.Views.getFontColor()) {
					txtColor = CupSell.Generator.Views.getFontColor();
				} else {
					txtColor = _getBackgroundColor() == '#000000' ? '#FFFFFF' : '#000000';
				}
				
				CupSell.Generator.confirmDialog(
				translation.editPrint, translation.removeEditPrint, function() 
				{
					_editor.html('&lt;span style="font-family: ' + $('#font')[0].value + '; font-size: ' + $('#size')[0].value + 'px; color: ' + txtColor + ';"&gt;' + _getText() + '&lt;/span&gt;');
					_setAlign('left');
				});
			}
		});

	
		/**
		 * Font family select onChange Event
		 * Changes font family of text selection
		 */
		$('#font').change(function()
		{
			var selection = undefined,
				activeBoxId = CupSell.Generator.Canvas.getActiveBoxId();
			
			if(_hasFocus) {
				if(window.getSelection) {
					selection = window.getSelection();
					selection.removeAllRanges();
					selection.addRange(_range);
				}
				
				if(activeBoxId) {
					if(_range.toString()) {
						_onFormat('fontName', this.value);
					} else {
						_setStyle('font-family', this.value);
					}
				} else {
					if(_range.toString()) {
						_onFormat('fontName', this.value);
					} else {
						_setStyle('font-family', this.value);
					}
				}
			} else {
				_setStyle('font-family', this.value);
			}
		});
		
		
		$('#font').mouseenter(function()
		{
			var selection = undefined;
			
			if(_hasFocus) {
				if(window.getSelection) {
					selection = window.getSelection();
					_range = selection.getRangeAt(0);
				}
			}
		});


		/**
		 * Font size select onChange Event
		 * Changes font size of text selection
		 */
		$('#size').change(function()
		{
			var selection = undefined,
				activeBoxId = CupSell.Generator.Canvas.getActiveBoxId();
			
			if(_hasFocus) {
				if(window.getSelection) {
					selection = window.getSelection();
					selection.removeAllRanges();
					selection.addRange(_range);
				}
				
				if(activeBoxId) {
					if(_range.toString()) {
						_onFormat('fontSize', this.value);
					} else {
						_setStyle('font-size', this.value);
					}
				} else {
					if(_range.toString()) {
						_onFormat('fontSize', this.value);
					} else {
						_setStyle('font-size', this.value);
					}
				}

				_onFormat('fontSize', this.value);
			} else {
				_setStyle('font-size', this.value);
			}
		});
		
		
		$('#size').mouseenter(function()
		{
			var selection = undefined;
			
			if(_hasFocus) {
				if(window.getSelection) {
					selection = window.getSelection();
					_range = selection.getRangeAt(0);
				}
			}
		});
		
		
		$('#bold').click(function(event)
		{
			var activeBoxId = CupSell.Generator.Canvas.getActiveBoxId();
			
			if(_hasFocus) {
				if(activeBoxId) {
					if(_range.toString()) {
						_onFormat(event.target.id);
					} else {
						_setStyle('font-weight', event.target.id);
					}
				} else {
					if(_range.toString()) {
						_onFormat(event.target.id);
					} else {
						_setStyle('font-weight', event.target.id);
					}
				}
			} else {
				_setStyle('font-weight', event.target.id);
			}
		});

		$('#italic').click(function(event)
		{
		
			var activeBoxId = CupSell.Generator.Canvas.getActiveBoxId();
			
			if(_hasFocus) {
				if(activeBoxId) {
					if(_range.toString()) {
						_onFormat(event.target.id);
					} else {
						_setStyle('font-style', event.target.id);
					}
				} else {
					if(_range.toString()) {
						_onFormat(event.target.id);
					} else {
						_setStyle('font-style', event.target.id);
					}
				}
			} else {
				_setStyle('font-style', event.target.id);
			}
		});


		$('#colorBox').click(function(event)
		{
			var activeBoxId = CupSell.Generator.Canvas.getActiveBoxId();
			
			if(event.target.nodeName.toUpperCase() == 'BUTTON' &amp;&amp; $(event.target).parent().attr('id') !== 'custom_color') {
				if(_hasFocus) {
					if(activeBoxId) {
						if(_range.toString()) {
							_onFormat('foreColor', $(event.target).css('backgroundColor'));
						} else {
							_setStyle('color', $(event.target).css('backgroundColor'));
						}
					} else {
						if(_range.toString()) {
							_onFormat('foreColor', $(event.target).css('backgroundColor'));
						} else {
							_setStyle('color', $(event.target).css('backgroundColor'));
						}
					}
				} else {
					_setStyle('color', $(event.target).css('backgroundColor'));
				}
			}
		});
                
                $('#colorPicker').farbtastic(function(color){
                    $('#colorPickerBox [name="color_picked"]').val(color).css('background-color', color);
                });
                $('#colorPickerBox [name="color_picked"]').keyup(function(){
                    $(this).css('background-color', $(this).val());
                });
                $('#confirm_color').click(function(){
                    _setStyle('color', $('#colorPickerBox [name="color_picked"]').val());
                    $('#colorPickerBox')[0].style.display = '';
                    $('#formatBox, #addTxt, #txtreset').show();
                });
                $('#custom_color button').click(function(){
                    $('#formatBox, #addTxt, #txtreset').hide();
                    $('#colorPickerBox')[0].style.display = 'inline-block';
                });

		/**
		 * Align buttons onClick Event
		 * Changes text alignment
		 */
		$('#alignLeft').click(_onAction);
		$('#alignCenter').click(_onAction);
		$('#alignRight').click(_onAction);
	});
	
	
	function _loadFonts()
	{
		var canvas = document.createElement("canvas"),
			ctx = canvas.getContext("2d");
		
		$('#font &gt; option').each(function(index, item) 
		{
			ctx.save();
			ctx.font = "12px " + item.value; 
			
			ctx.fillText('A', 0, 0);
			ctx.restore();
		});
	}
	


	/**
	 * Align text
	 *
	 * @param Event event
	 */
	function _onAction(event)
	{
		var activeBoxId = CupSell.Generator.Canvas.getActiveBoxId(),
			boxAlign = undefined,
			align = undefined;

		switch(event.target.id) {
			case 'alignLeft':
				align = 'left';
			break;

			case 'alignCenter':
				align = 'center';
			break;

			case 'alignRight':
				align = 'right';
			break;
		}

		_editor.css('textAlign', align);
		if(activeBoxId) {
			boxAlign = CupSell.Generator.Canvas.getProperty(activeBoxId, 'align');
			CupSell.Generator.Canvas.setProperty(activeBoxId, 'align', align);
			CupSell.Generator.Canvas.setUnReDoProps(activeBoxId, {start: {align: boxAlign}, end: {align: align}});
		}
	}


	function _setAlign(align)
	{
		_editor.css('textAlign', align);
	}


	/**
	 * Format selected text
	 *
	 * @param String command
	 * @param mixed vValue
	 */
	function _onFormat(command, vValue)
	{
		var html = undefined,
			isSelection = false,
			htmlChunk = undefined,
			activeBoxId = CupSell.Generator.Canvas.getActiveBoxId(),
			boxWidth = undefined,
			boxHeight = undefined,
			boxHtml = undefined,
			boxHtmlChunk = undefined,
			selectedTxt = _range.toString();

		if(window.getSelection) {
			if(window.getSelection().toString().length &gt; 0) {
				isSelection = true;
			}
		}

		if(isSelection) {
			if(activeBoxId) {
				boxWidth = CupSell.Generator.Canvas.getProperty(activeBoxId, 'width');
				boxHeight = CupSell.Generator.Canvas.getProperty(activeBoxId, 'height');
				boxHtml = CupSell.Generator.Canvas.getProperty(activeBoxId, 'html');
				boxHtmlChunk = CupSell.Generator.Canvas.getProperty(activeBoxId, 'htmlChunk');
			}
	
			//fix for Opera
			if(command == 'foreColor') {
				vValue = _colorToHex(vValue);
			}

			try {
				document.execCommand(command, false, vValue);
			} catch (e) {
				alert(e.message);
			}

			html = _editor.html();
			html = html.replace('class="Apple-style-span"', '');
			
			switch(command) {
				case 'bold':
					html = html.replace(/&lt;b&gt;|&lt;strong&gt;/g, '&lt;span style="font-weight: bold;"&gt;').replace(/&lt;\/b&gt;|&lt;\/strong&gt;/g, '&lt;/span&gt;');
				break;

				case 'italic':
					html = html.replace(/&lt;i&gt;|&lt;em&gt;/g, '&lt;span style="font-style: italic;"&gt;').replace(/&lt;\/i&gt;|&lt;\/em&gt;/g, '&lt;/span&gt;');
				break;

				case 'foreColor':
					html = html.replace(/&lt;font\s+color="(rgb\([0-9]{1,3},\s?[0-9]{1,3},\s?[0-9]{1,3}\)|#[0-9a-f]{6})"&gt;/g, '&lt;span style="color: $1;"&gt;').replace(/&lt;\/font&gt;/g, '&lt;/span&gt;');
				break;

				case 'fontName':
					html = html.replace(/&lt;font\s+face="([^"]*)"&gt;/g, '&lt;span style="font-family: $1;"&gt;').replace(/&lt;\/font&gt;/g, '&lt;/span&gt;');
				break;

				case 'fontSize':
					html = html.replace(/&lt;font\s+size="[^"]*"&gt;/g, '&lt;span style="font-size: ' + $('#size')[0].value + 'px;"&gt;').replace(/&lt;\/font&gt;/g, '&lt;/span&gt;');
				break;
			}

			_editor.html(html);
			_refineHTML();
			_glueFragments();
			if(selectedTxt) {
				_setRange(selectedTxt);
			}

			if(activeBoxId) {
				htmlChunk = _getSpanChunks();
				
				CupSell.Generator.Canvas.setProperty(activeBoxId, 'htmlChunk', htmlChunk, true);
				CupSell.Generator.Canvas.setProperty(activeBoxId, 'html', _editor.html());
		
				
				CupSell.Generator.Canvas.setUnReDoProps(activeBoxId, {
					start: {
						width: boxWidth, 
						height: boxHeight, 
						html: boxHtml, 
						htmlChunk: boxHtmlChunk}, 
					end: {
						width: CupSell.Generator.Canvas.getProperty(activeBoxId, 'width'),
						height: CupSell.Generator.Canvas.getProperty(activeBoxId, 'height'),
						html: _editor.html(), 
						htmlChunk: htmlChunk}
				});
				

				//fix for rendering @font-face fonts
//				if(command == 'fontName') {
//					setTimeout(_setCanvasHTML, 300);
//				}
				
				setTimeout(CupSell.Generator.Canvas.redraw, 300);
				
//				if(command == 'fontName') {
//					setTimeout(CupSell.Generator.Canvas.redraw, 500);
//				}

//				$('#txtreset').attr('disabled', false);
			}
		}
	}

//	function _setCanvasHTML()
//	{
//		CupSell.Generator.Canvas.setProperty(CupSell.Generator.Canvas.getActiveBoxId(), 'html', _editor.html());
//	}

	function _refineHTML()
	{
		var fragments = _editor.children('span'),
			nodes = undefined,
			childStyle = undefined,
			style = undefined;

		for(var i = 0; i &lt; fragments.length; i++) {
			if($(fragments[i]).children('span').length &gt; 0) {

				nodes = $(fragments[i].childNodes);

				for(var j = 0; j &lt; nodes.length; j++) {
					if(nodes[j].nodeType == 3) {
						$(fragments[i]).before($(document.createElement('span')).attr('style', $(fragments[i].attributes)[0].nodeValue).html(nodes[j].textContent));
					} else if (nodes[j].tagName.toUpperCase() == 'BR') {
						$(fragments[i]).before($(document.createElement('span')).html('&lt;br&gt;'));
					} else {
						childStyle = $(nodes[j]).attr('style');
						$($(fragments[i].attributes)[0].nodeValue.split(';')).each(function(index, element)
						{
							var style = element.replace(/"/g, '').split(':')[0];

							style = $.trim(style);

							if(childStyle.indexOf(style) == -1) {
								childStyle = element + '; ' + childStyle;
							}
						});

						$(fragments[i]).before($(nodes[j]).attr('style', childStyle));
					}
				}

				$(fragments[i]).remove();
			}
		}
	}
	
	
	function _glueFragments()
	{
		var fragments = _editor.children('span'),
			prevStyle = {},
			currentStyle = {};

		prevStyle['font-family'] = '';
		prevStyle['font-weight'] = '';
		prevStyle['font-style'] = '';
		prevStyle['font-size'] = '';
		prevStyle['color'] = '';

		for(var i = 0; i &lt; fragments.length; i++) {

			if($(fragments[i]).html().replace(/\s/g, '').length == 0) {
				if(i &gt; 0) {
					$(fragments[i - 1]).html($(fragments[i - 1]).html() + $(fragments[i]).html());
					$(fragments[i]).remove();
				}
			}

			currentStyle['font-family'] = '';
			currentStyle['font-weight'] = '';
			currentStyle['font-style'] = '';
			currentStyle['font-size'] = '';
			currentStyle['color'] = '';

			if($(fragments[i].attributes).length &gt; 0) {
				$($(fragments[i].attributes)[0].nodeValue.split(';')).each(function(index, element)
				{
					var style = element.replace(/"/g, '').split(':');

					if(style.length &gt; 1) {
						currentStyle[$.trim(style[0])] = $.trim(style[1]);
					}
				});
			}

			if(currentStyle['font-family'] == prevStyle['font-family'] &amp;&amp; currentStyle['font-weight'] == prevStyle['font-weight'] &amp;&amp; currentStyle['font-style'] == prevStyle['font-style'] &amp;&amp; currentStyle['font-size'] == prevStyle['font-size'] &amp;&amp; currentStyle['color'] == prevStyle['color']) {
				if($(fragments[i]).prev()[0].tagName.toUpperCase() != 'BR') {
					$(fragments[prevStyle['i']]).html($(fragments[prevStyle['i']]).html() + $(fragments[i]).html());
					$(fragments[i]).remove();
				} else {
					prevStyle['i'] = i;
				}
			} else {
				prevStyle['font-family'] = currentStyle['font-family'];
				prevStyle['font-weight'] = currentStyle['font-weight'];
				prevStyle['font-style'] = currentStyle['font-style'];
				prevStyle['font-size'] = currentStyle['font-size'];
				prevStyle['color'] = currentStyle['color'];
				prevStyle['i'] = i;
			}

			if($(fragments[i]).html() == '&lt;br&gt;') {
				$(fragments[i]).replaceWith('&lt;br&gt;');
			}
		}
	}
	
	
	function _setRange(txt)
	{
		var fragments = _editor.children('span'),
			span = undefined,
			selection = undefined;
		
		for(var i = 0; i &lt; fragments.length; i++) {
			if(fragments[i].textContent == txt) {
				span = fragments[i];
			}
		}
		
		if(span) {
			selection = window.getSelection();
			_range = document.createRange();
			_range.selectNodeContents(span);
			selection.removeAllRanges();
			selection.addRange(_range);
		}
	}


	function _getSpanChunks()
	{
		var children = [],
			chunk = [];

		children = _editor.children();

		for(var i = 0; i &lt; children.length; i++) {
			if(children[i].tagName.toUpperCase() == 'SPAN') {
				chunk.push(_refineSpan($(children[i])));
			} else if(children[i].tagName.toUpperCase() == 'BR' &amp;&amp; i &lt; children.length - 1) {
				chunk.push({tag: 'br'});
			}
		}

		return chunk;
	}


	/**
	 * Build span chunk object for canvas txt object
	 *
	 * @param DOMElement span
	 * @return Object
	 */
	function _refineSpan(span)
	{
		var object = {};

		object.txt = span.html().replace(/&amp;nbsp;/g, ' ').replace(/&lt;br[^&gt;]*&gt;/g, '');
		object.txt = $("&lt;div/&gt;").html(object.txt).text();

		object.font = span.css('fontFamily');
		object.fontSize = span.css('fontSize');
		object.color = span.css('color');

		if(span.css('fontWeight') != 400) {
			object.fontWeight = span.css('fontWeight');
		}

		if(span.css('fontStyle') == 'italic') {
			object.fontStyle = 'italic';
		}

		return object;
	}


	/**
	 * Set Editor html
	 *
	 * @param String html
	 */
	function _setStyle(style, value)
	{
		var fragments = _editor.children('span'),
			activeBoxId = CupSell.Generator.Canvas.getActiveBoxId(),
			styled = 0,
			isReverted = false,
			htmlChunk = undefined,
			boxWidth = undefined,
			boxHeight = undefined,
			boxHtml = undefined,
			boxHtmlChunk = undefined;

		if(activeBoxId &amp;&amp; $('#' + activeBoxId).hasClass('txtBox')) {
			
			boxWidth = CupSell.Generator.Canvas.getProperty(activeBoxId, 'width');
			boxHeight = CupSell.Generator.Canvas.getProperty(activeBoxId, 'height');
			boxHtml = CupSell.Generator.Canvas.getProperty(activeBoxId, 'html');
			boxHtmlChunk = CupSell.Generator.Canvas.getProperty(activeBoxId, 'htmlChunk');
		}
			
		if(style == 'font-weight') {
			for(var i = 0; i &lt; fragments.length; i++) {
				if($(fragments[i].attributes)[0].nodeValue.indexOf('font-weight') != -1) {
					styled++;
				}
			}

			if(styled == fragments.length) {
				isReverted = true;
			}
		}


		if(style == 'font-style') {
			for(var i = 0; i &lt; fragments.length; i++) {
				if($(fragments[i].attributes)[0].nodeValue.indexOf('font-style') != -1) {
					styled++;
				}
			}

			if(styled == fragments.length) {
				isReverted = true;
			}
		}


		for(var i = 0; i &lt; fragments.length; i++) {
			switch(style) {
				case 'font-family':
					$(fragments[i].attributes)[0].nodeValue = $(fragments[i].attributes)[0].nodeValue.replace(/font-family:\s?([^;]*);/, 'font-family: ' + value + ';');
				break;

				case 'font-size':
					$(fragments[i].attributes)[0].nodeValue = $(fragments[i].attributes)[0].nodeValue.replace(/font-size:\s?([^;]*);/, 'font-size: ' + value + 'px;');
				break;

				case 'font-weight':
					if(isReverted) {
						$(fragments[i].attributes)[0].nodeValue = $(fragments[i].attributes)[0].nodeValue.replace(/font-weight:\s?([^;]*);/, '');
					} else {
						if($(fragments[i].attributes)[0].nodeValue.indexOf('font-weight') == -1) {
							$(fragments[i].attributes)[0].nodeValue = $(fragments[i].attributes)[0].nodeValue + 'font-weight: bold;';
						}
					}
				break;

				case 'font-style':
					if(isReverted) {
						$(fragments[i].attributes)[0].nodeValue = $(fragments[i].attributes)[0].nodeValue.replace(/font-style:\s?([^;]*);/, '');
					} else {
						if($(fragments[i].attributes)[0].nodeValue.indexOf('font-style') == -1) {
							$(fragments[i].attributes)[0].nodeValue = $(fragments[i].attributes)[0].nodeValue + 'font-style: italic;';
						}
					}
				break;

				case 'color':
					$(fragments[i].attributes)[0].nodeValue = $(fragments[i].attributes)[0].nodeValue.replace(/color:\s?([^;]*);/, 'color: ' + value + ';');
				break;
			}
		}
		
		_glueFragments();
		
		if(activeBoxId) {
			htmlChunk = _getSpanChunks();
			
			
			CupSell.Generator.Canvas.setProperty(activeBoxId, 'htmlChunk', htmlChunk, true);
			CupSell.Generator.Canvas.setProperty(activeBoxId, 'html', _editor.html());
			
			
			CupSell.Generator.Canvas.setUnReDoProps(activeBoxId, {
				start: {
					width: boxWidth, 
					height: boxHeight, 
					html: boxHtml, 
					htmlChunk: boxHtmlChunk}, 
					end: {
						width: CupSell.Generator.Canvas.getProperty(activeBoxId, 'width'),
						height: CupSell.Generator.Canvas.getProperty(activeBoxId, 'height'),
						html: _editor.html(), 
						htmlChunk: htmlChunk}
			});
		}
	}


	/**
	 * Set Editor html
	 *
	 * @param String html
	 */
	function _setHTML(html)
	{
		_editor.html(html);
	}


	/**
	 * Get Editor html
	 *
	 * @return String
	 */
	function _getHTML()
	{
		return _editor.html();
	}
	
	
	function _getText()
	{
		return _editor[0].textContent;
	}


	function _isEmpty()
	{
		var html = _editor.html();

		if(html == '' || (_editor.children('span').length == 1 &amp;&amp; $(_editor.children('span')[0]).html().replace('&lt;br&gt;', '').replace('&amp;nbsp;', '') == '')) {
			return true;
		} else {
			return false;
		}
	}

	function _setFocus(hasFocus)
	{
		_hasFocus = hasFocus;
	}
	
	function _colorToHex(color) 
	{
		var match = /rgba?\((\d+),\s?(\d+),\s?(\d+)/.exec(color);

    	if(match) {
    		return "#" + _zeroFill((match[1] &lt;&lt; 16 | match[2] &lt;&lt; 8 | match[3] ).toString(16), 6);
    	} else {
    		return color;
    	}
	};
	
	function _zeroFill(number, limit) 
	{
		for (var i = number.toString().length; i &lt; limit; i++) {
			number = '0' + number;
		}
		
		return number;
	}
	
	function _getBackgroundColor()
	{
		return _colorToHex(_editor.css('backgroundColor'));
	}
	
	function _setFontAndSize(fontFamily, fontSize)
	{
		fontSize = parseInt(fontSize);
	
		$('#font &gt; option').each(function(index, element)
		{
			if($(element).val() == fontFamily) {
				$(element).attr('selected', true);
			}
		});
		
		$('#size &gt; option').each(function(index, element)
		{
			if($(element).val() == fontSize) {
				$(element).attr('selected', true);
			}
		});
	}


	return {
		setHTML: _setHTML,
		getHTML: _getHTML,
		getSpanChunks: _getSpanChunks,
		getText: _getText,
		isEmpty: _isEmpty,
		setAlign: _setAlign,
		setFocus: _setFocus,
		setProductColor: function(color)
		{
			_productColor = /#[0-9a-z]{6}/i.test(color) ? color : '#FFFFFF';
		},
		setBackgroundColor: function(color)
		{
			color = /#[0-9a-z]{6}/i.test(color) ? color : _productColor;
			_editor.css('backgroundColor', color);
		},
		getBackgroundColor: _getBackgroundColor,
		hasFocus: function()
		{
			return _hasFocus;
		},
		disableReset: function()
		{
			$('#txtreset').attr('disabled', true);
		},

		enableReset: function()
		{
			$('#txtreset').attr('disabled', false);
		}
	};
})();;/**
 * UnReDo
 * Keeps last operation data for un/re do
 *
 */

CupSell.Generator.UnReDo = (function()
{
	var _queue = {},
		_index = {},
		_isDisabled = {},
		QUEUE_LIMIT = 16;
	
	$(document).ready(function()
	{
		$('#undo').click(_onUnReDo);
		$('#redo').click(_onUnReDo);
	});
	
	function _setProps(props)
	{
		if(_index[props.view] == undefined) {
			_index[props.view] = 0;
		} else {
			_index[props.view]++;
		}

		if(!_queue[props.view]) {
			_queue[props.view] = {};
			_queue[props.view]['list'] = [];
		} else {
			//if there are some undo's need to remove them form list
			if(_index[props.view] &lt; _queue[props.view]['list'].length) {
				_queue[props.view]['list'].splice(_index[props.view]);
			}
		}
		
		_queue[props.view]['list'].push(props);
		
		if(_queue[props.view]['list'].length &gt; QUEUE_LIMIT) {
			_queue[props.view]['list'].shift();
			_index[props.view]--;
		}
		
		if(!_isDisabled[props.view]) {
			_isDisabled[props.view] = {};
			
		}
		
		_isDisabled[props.view]['undo'] = false;
		_isDisabled[props.view]['redo'] = true;
		

		$('#undo').attr('disabled', false);
		$('#redo').attr('disabled', false);
	}
	
	function _setPositions(positions) 
	{
		var view = 'view_' + CupSell.Generator.Canvas.getCurrentView();
		_queue[view]['list'][_index[view]]['moved'] = positions;
	}
	
	function _onUnReDo(event)
	{
		var action = event.target.id,
			view = 'view_' + CupSell.Generator.Canvas.getCurrentView(),
			object = undefined,
			props = undefined,
			position = undefined,
			moved = undefined,
			activeBoxId = CupSell.Generator.Canvas.getActiveBoxId();
		
		
		if(activeBoxId) {
			CupSell.Generator.Canvas.deactivateBox($('#' + activeBoxId));
		}

		if(action == 'undo' &amp;&amp; !_isDisabled[view]['undo']) {
			object = _queue[view]['list'][_index[view]];
			props = object.props.start;
			
			if(_queue[view]['list'][_index[view]]['moved']) {
				moved = _queue[view]['list'][_index[view]]['moved'].start;
			}

			_index[view]--;
			if(_index[view] == -1) {
				_isDisabled[view]['undo'] = true;
			}
			
			if(object.position) {
				position = object.position.start;
			}

			if(props == null) {
				CupSell.Generator.Canvas.deleteBox(object.boxId);
			}
			
			if(object.props.end == null) {
				CupSell.Generator.Canvas.restoreBox(object);
			}
			
			_isDisabled[view]['redo'] = false;
		}
		
		
		if(action == 'redo' &amp;&amp; !_isDisabled[view]['redo']) {
			_index[view]++;

			if(_index[view] == _queue[view]['list'].length - 1) {
				_isDisabled[view]['redo'] = true;
			}
		
			object = _queue[view]['list'][_index[view]];
			props = object.props.end;
			
			if(_queue[view]['list'][_index[view]]['moved']) {
				moved = _queue[view]['list'][_index[view]]['moved'].end;
			}
			
			if(object.position) {
				position = object.position.end;
			}
			
			if(props == null) {
				CupSell.Generator.Canvas.deleteBox(object.boxId);
			}
			
			if(object.props.start == null) {
				CupSell.Generator.Canvas.restoreBox(object);
			}

			_isDisabled[view]['undo'] = false;
		}
		
		if(moved) {
			for(var item in moved) {
				CupSell.Generator.Canvas.setProperty(item, 'top', moved[item].top, true);
				CupSell.Generator.Canvas.setProperty(item, 'left', moved[item].left, true);
				CupSell.Generator.Canvas.setProperty(item, 'rect', moved[item].rect, true);
			}
		}
		

		if(props) {
			for(var key in props) {
				if(key == 'html' &amp;&amp; CupSell.Generator.Canvas.getActiveBoxId() == object.boxId) {
					if(_isEmptyHtml(props.html)) {
						CupSell.Generator.Editor.setHTML(props.initHtml);
					} else {
						CupSell.Generator.Editor.setHTML(props.html);
					}
					
				} else if(key == 'align' &amp;&amp; CupSell.Generator.Canvas.getActiveBoxId() == object.boxId) {
					CupSell.Generator.Editor.setAlign(props.align);
				}
					
				CupSell.Generator.Canvas.setProperty(object.boxId, key, props[key], true);
			}
			
			CupSell.Generator.Canvas.adjustBox(object.boxId);
			if(position) {
				CupSell.Generator.Canvas.setCanvasPosition(position);
			}
			CupSell.Generator.Canvas.redraw();
			CupSell.Generator.Canvas.storeData();
		}
	}
	
	function _isEmptyHtml(html)
	{
		if(html == '' || ($('#txtEditor').children('span').length == 1 &amp;&amp; $($('#txtEditor').children('span')[0]).html().replace('&lt;br&gt;', '').replace('&amp;nbsp;', '') == '')) {
			return true;
		} else {
			return false;
		}
	}
	

	return {
		setProps: _setProps,
		setPositions: _setPositions,
		clear: function(view)
		{
			if(view) {
				delete _queue[view];
				delete _index[view];
				delete _isDisabled[view];
			} else {
				_queue = {};
				_index = {};
				_isDisabled = {};
			}
			
			_isUndoDisabled = true;
			_isRedoDisabled = true;
			
//			$('#undo').attr('disabled', true);
//			$('#redo').attr('disabled', true);
		}
	};
})();

;/**
 * Storage
 */
CupSell.Generator.StorageManager = (function()
{
	var _namespace = '';

	/**
	 * Stores data in localStorage
	 *
	 * @param String key
	 * @param String value
	 */
	function _store(key, value) {
		localStorage[_namespace + key] = value;
	}


	/**
	 * Gets data from localStorage
	 *
	 * @param String key
	 * @param String value
	 *
	 * @return mixed [string || undefined]
	 */
	function _get(key) {
		return localStorage[_namespace + key]
			? localStorage[_namespace + key]
			: undefined;
	}


	/**
	 * Removes data from localStorage
	 *
	 * @param String key
	 */
	function _remove(key) {
		if (localStorage[_namespace + key]) {
			localStorage.removeItem(_namespace + key);
			return true;
		} else {
			return false;
		}
	}


	/**
	 * Clear data from localStorage with namespace
	 *
	 * @param String key
	 */
	function _clear() {
		var ts = _get('ts');
		var version = _get('version');
		var toClear = Array();
		for (var i=0; i &lt; localStorage.length; i++) {
			var key = localStorage.key(i);
			if (key.indexOf(_namespace) === 0) {
				toClear.push(key);
			}
		}
		for (var i=0; i &lt; toClear.length; i++) {
			localStorage.removeItem(toClear[i]);
		}

		_store('ts', ts);
		_store('version', version);
	}

	/**
	 * Initialize generator storage
	 *
	 * @param String namespace
	 * @param String appVersion
	 * @param Integer ttl TTL of generator data storage in seconds
	 */
	function _init(namespace, appVersion, ttl) {
		_namespace = namespace + ':';
		now = parseInt((new Date()).getTime().toString());

		// Check ttl and version
		if (parseInt(_get('ts')) + (ttl * 1000) &lt; now || _get('version') != appVersion) {
			_clear();
		}

		_store('ts', now);
		_store('version', appVersion);
	}


	/**
	 * Public interface
	 *
	 */
	return typeof(Storage) !== 'undefined'
		? {store: _store, get: _get, remove: _remove, clear: _clear, init: _init}
		: {store: function() {}, get: function() {return undefined;}, remove: function() {return false;}, clear: function() {}, init: function() {}};
})();;function log(object)
{
    console.log(object);
}
(function (b) {
    b.support.touch = "ontouchend" in document;
    if (!b.support.touch) {
        return;
    }
    var c = b.ui.mouse.prototype, e = c._mouseInit, a;
    function d(g, h)
    {
        if (g.originalEvent.touches.length &gt; 1) {
            return;
        }
        g.preventDefault();
        var i = g.originalEvent.changedTouches[0], f = document.createEvent("MouseEvents");
        f.initMouseEvent(
                h, true, true, window, 1, i.screenX, i.screenY, i.clientX, i.clientY, false, false, false, false, 0, null);
        g.target.dispatchEvent(f);
    }
    c._touchStart = function (g) {
        var f = this;
        if (a || !f._mouseCapture(g.originalEvent.changedTouches[0])) {
            return;
        }
        a = true;
        f._touchMoved = false;
        d(g, "mouseover");
        d(g, "mousemove");
        d(g, "mousedown");
    };
    c._touchMove = function (f) {
        if (!a) {
            return;
        }
        this._touchMoved = true;
        d(f, "mousemove");
    };
    c._touchEnd = function (f) {
        if (!a) {
            return;
        }
        d(f, "mouseup");
        d(f, "mouseout");
        if (!this._touchMoved) {
            d(f, "click");
        }
        a = false;
    };
    c._mouseInit = function () {
        var f = this;
        f.element.bind("touchstart", b.proxy(f, "_touchStart")).bind(
                "touchmove", b.proxy(f, "_touchMove")).bind("touchend", b.proxy(f, "_touchEnd"));
        e.call(f);
    };
})(jQuery);
CupSell.Generator.Canvas = (function ()
{
    var _canvas = undefined, // canvas element
            _context = undefined, // canvas' context
            _view = undefined, // current view
            _viewHash = undefined, // hash container for _objectHash with view objects
            _objectHash = undefined, // hash container for current view objects
            _sorting = undefined, // array with current view sorting
            _productCanvasPosition = undefined, // hash for canvas positions in views for different products
            _image = undefined, // hash container for image data
            _activeBoxId = undefined, // active object box id
            _ratio = undefined, // real size to preview size ratio
            _productId = undefined,
            _productTag = undefined,
            _isBusy = false,
            _isPrintAreaVisible = true,
            _colorLength = undefined,
            _colorOption = 'only',
            _exceptColors = [],
            DEFAULT_TXT = 'Wpisz tekst',
            DEFAULT_TXT_FONT_SIZE = '24px',
            DEFAULT_TXT_HEIGHT = 24,
            CONTROL_CENTER_OFFSET = 4;
    if (typeof (noJQ) !== "undefined") {
        noJQ.documentReady(function () {
            setTimeout(_redraw, 200);
        });
    }


    $(document).ready(function ()
    {
        var now = undefined,
                timestamp = undefined;

        // canvas
        _canvas = $('#canvas');

        // context
        _context = _canvas.get(0).getContext('2d');

        _sorting = [];

        //create transform controls
        _setUpControls();

        _productCanvasPosition = {};

        // Load product
        var pattern = window.location.hash.substr(1);
        if (pattern) {
            CupSell.Generator.ProductManager.loadProductData(pattern);
            window.location.hash = "";
        } else if (CupSell.Generator.defaultProductURL) {
            CupSell.Generator.ProductManager.loadProductData(CupSell.Generator.defaultProductURL);
        } else if (CupSell.Generator.StorageManager.get('pid')) {
            CupSell.Generator.ProductManager.loadProductData(CupSell.Generator.StorageManager.get('pid'));
        } else {
            CupSell.Generator.ProductManager.loadProductData(CupSell.Generator.defaultProduct);
        }

        if (CupSell.Generator.StorageManager.get('uid')) {
            $('[name=uid]').val(CupSell.Generator.StorageManager.get('uid'));
        } else {
            _getUID();
        }

        $('#reset').attr('disabled', false);

        $('#reset').click(function ()
        {
            CupSell.Generator.confirmDialog(
                    translation.editPrint, translation.resetEditPrint,
                    function ()
                    {
                        $('.txtBox, .imgBox').remove();

                        _activeBoxId = undefined;
                        _objectHash = {};
                        _sorting = [];
                        _image = {};

                        if (_productCanvasPosition[_productTag] &amp;&amp; _productCanvasPosition[_productTag]['view_' + _view]) {
                            delete _productCanvasPosition[_productTag]['view_' + _view];
                        }

                        _viewHash['view_' + _view]['box'] = _objectHash;
                        _viewHash['view_' + _view]['sorting'] = _sorting;
                        CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));
                        CupSell.Generator.Basket.updatePrice();

                        $('#controls').hide();
                        _redraw();

                        CupSell.Generator.Editor.setHTML('');
                        CupSell.Generator.Editor.setAlign('left');
                        //					CupSell.Generator.Editor.disableReset();
                        CupSell.Generator.UnReDo.clear('view_' + _view);
                        //					$('#reset').attr('disabled', true);
                    }
            );
        });


        $('#clear').click(function () {
            CupSell.Generator.confirmDialog(
                    translation.newProject, translation.confirmNewProject,
                    function () {
                        $('.txtBox, .imgBox').remove();
                        CupSell.Generator.StorageManager.clear();
                        CupSell.Generator.FileManager.clearImageData();

                        _activeBoxId = undefined;
                        _image = {};
                        _viewHash = {};
                        _objectHash = {};
                        _sorting = [];
                        _productCanvasPosition = {};

                        CupSell.Generator.ProductManager.clearViewsSelector();

                        $('#userImages').html('&lt;li&gt;&amp;nbsp;&lt;/li&gt;');
                        $('#workspaceBox').hide();
                        CupSell.Generator.Views.clearView();

                        $('#controls').hide();
                        _redraw();

                        CupSell.Generator.Editor.setHTML('');
                        CupSell.Generator.Editor.setAlign('left');
                        //					CupSell.Generator.Editor.disableReset();
                        CupSell.Generator.UnReDo.clear();
                        CupSell.Generator.Basket.clear();
                        CupSell.Generator.Basket.updatePrice();

                        //					$('#reset').attr('disabled', true);
                        $('#sizeSelectorGenerator').hide();
                        CupSell.Generator.ProductManager.loadProductData(CupSell.Generator.defaultProduct);
                        _getUID();
                    }
            )
        });

        $('#addToBasket').click(_addToBasket);
        $('#buyNow').click(_buyNow);
        $('#addToShop').click(_addToShop);
        $('#changeShopItem').click(_editItem);

        var print_area = $('#printarea');
        print_area.click(function () {

            if (_isPrintAreaVisible) {
                _canvas.css('border', '1px dotted transparent');
                _isPrintAreaVisible = false;

                print_area.addClass('deactivated');
                print_area.text(translation.generatorShowPrintarea);
            } else {
                _canvas.css('border', '1px dotted #CCCCCC');
                _isPrintAreaVisible = true;
                print_area.removeClass('deactivated');
                print_area.text(translation.generatorHidePrintarea);
            }
        });


        $('#centerBox').click(_centerBox);


        $('body').keyup(function (event)
        {
            if (event.which == 46) {
                if (_activeBoxId) {
                    if ($('#' + _activeBoxId).hasClass('txtBox')) {
                        if (!CupSell.Generator.Editor.hasFocus()) {
                            _removeActiveBox();
                        }
                    } else {
                        _removeActiveBox();
                    }
                }
            }
        });
    });


    function _getUID()
    {
        $.ajax({
            url: '/generator-ajax/index',
            type: 'post',
            dataType: 'json',
            data: {
                mod: 'creator',
                act: 'generateUid'
            },
            success: function (response)
            {
                CupSell.Generator.StorageManager.store('uid', response.uid);
                $('[name=uid]').val(response.uid);
            }
        });
    }
    function _setColorLength(colorLength) {
        _colorLength = colorLength;
    }

    function _setCanvasProps(productId, productTag, data, view, transratio)
    {
        var isEmpty = true,
                factor = undefined;

        transratio = transratio || {};

        _view = view;
        _productId = productId;
        _productTag = productTag;

        CupSell.Generator.StorageManager.store('pid', _productId);

        if (CupSell.Generator.StorageManager.get('csdata')) {
            _viewHash = $.evalJSON(CupSell.Generator.StorageManager.get('csdata'));
        } else {
            _viewHash = {};
        }

        for (var first in data.available_area.cm_size)
            break;

        factor = data.available_area.px_size.width / data.available_area.cm_size[first].width;
        _ratio = factor / _canvas.data()['dpcm'];

        /** To chyba niepotrzebne */
        if (_activeBoxId) {
            _deactivateBox($('#' + _activeBoxId));
        }
        /** */

        if (CupSell.Generator.StorageManager.get('previousPid') &amp;&amp; CupSell.Generator.StorageManager.get('previousPid') != _productTag) {
            CupSell.Generator.Tabs.togglePanel('typeTab');
            for (var transview in transratio) {
                if (_viewHash['view_' + transview]) {
                    _objectHash = _viewHash['view_' + transview]['box'];

                    for (var item in _objectHash) {
                        var object = _objectHash[item];
                        baseBoxHeight = object.props.height / object.props.yscale,
                                baseBoxWidth = object.props.width / object.props.xscale;


                        object.props.xscale *= transratio[transview].ratio;
                        object.props.yscale *= transratio[transview].ratio;


                        //zmiana top i left przy przeladowaniu produktu 
                        //
                        //
                        //object.props.left -= Math.floor((1 - transratio[transview].ratio) * object.props.left);
                        //object.props.top -= Math.floor((1 - transratio[transview].ratio) * object.props.top);                       

                        //object.props.left += transratio[transview].xOffset;
                        //object.props.top += transratio[transview].yOffset;
                        if (object.props.left &lt; 0) {
                            object.props.left = 0;
                        }

                        if (object.props.top &lt; 0) {
                            object.props.top = 0;
                        }

                        object.props.width = Math.ceil(baseBoxWidth * object.props.xscale);
                        object.props.height = Math.ceil(baseBoxHeight * object.props.yscale);

                        var downscale = 1;
                        // if image wider than print area fit image inside
                        if (object.props.width &gt; data.print_area.width * factor) {
                            var downscale = data.print_area.width * factor / object.props.width;
                        }

                        // if image higher than print area fit image inside
                        if (object.props.height &gt; data.print_area.height * factor) {
                            if (data.print_area.height * factor / object.props.height &lt; downscale) {
                                downscale = data.print_area.height * factor / object.props.height;
                            }
                        }

                        object.props.xscale *= downscale;
                        object.props.yscale *= downscale;

                        object.props.width = Math.ceil(baseBoxWidth * object.props.xscale);
                        object.props.height = Math.ceil(baseBoxHeight * object.props.yscale);

                        if (object.props.left + object.props.width &gt; Math.ceil(data.print_area.width * factor)) {
                            object.props.left = Math.ceil(data.print_area.width * factor) - object.props.width;
                        }

                        if (object.props.top + object.props.height &gt; Math.ceil(data.print_area.height * factor)) {
                            object.props.top = Math.ceil(data.print_area.height * factor) - object.props.height;

                        }

                        if (object.props.sprite &amp;&amp; (object.props.xscale &gt; 1 || object.props.yscale &gt; 1)) {
                            downscale = object.props.xscale &gt;= object.props.yscale ? object.props.xscale : object.props.yscale;

                            object.props.xscale = object.props.xscale / downscale;
                            object.props.yscale = object.props.yscale / downscale;

                            var oldW = object.props.width;
                            var oldH = object.props.height;

                            object.props.width = baseBoxWidth * object.props.xscale;
                            object.props.height = baseBoxHeight * object.props.yscale;

                            object.props.left += (oldW - object.props.width) / 2;
                            object.props.top += (oldH - object.props.height) / 2;
                        }

                        object.props.top = Math.floor(object.props.top);
                        object.props.left = Math.floor(object.props.left);
                        object.props.width = Math.floor(object.props.width);
                        object.props.height = Math.floor(object.props.height);

                        if (transview == _view) {
                            _setBoxRect(object.props.id);
                        }

                        $('#' + object.props.id).css({
                            top: object.props.top + 'px',
                            left: object.props.left + 'px',
                            width: object.props.width + 'px',
                            height: object.props.height + 'px'
                        });
                    }
                }
            }
        }


        if (CupSell.Generator.StorageManager.get('previousPid') &amp;&amp; CupSell.Generator.StorageManager.get('previousPid') != _productTag) {
            for (var viewId in _viewHash) {
                _viewHash[viewId]['position'] = {};
            }
        }

        if (_viewHash['view_' + _view] &amp;&amp; _viewHash['view_' + _view]['sorting'].length &gt; 0) {

            _objectHash = _viewHash['view_' + _view]['box'];
            _sorting = _viewHash['view_' + _view]['sorting'];
            if (_productCanvasPosition[_productTag] &amp;&amp; _productCanvasPosition[_productTag]['view_' + _view]) {
                _viewHash['view_' + _view]['position'].left = _productCanvasPosition[_productTag]['view_' + _view].left;
                _viewHash['view_' + _view]['position'].top = _productCanvasPosition[_productTag]['view_' + _view].top;
            } else {

                if (typeof _viewHash['view_' + _view]['position'].left == 'undefined') {
                    _viewHash['view_' + _view]['position'] = {
                        left: (data.available_area.px_size.width - data.print_area.width * factor) / 2,
                        //top: (data.available_area.cm_size[first].height - data.print_area.height) * factor / 2
                        top: 0
                    };
                }

                if (!_productCanvasPosition[_productTag]) {
                    _productCanvasPosition[_productTag] = {};
                }

                _productCanvasPosition[_productTag]['view_' + _view] = {};

                _productCanvasPosition[_productTag]['view_' + _view].left = _viewHash['view_' + _view]['position'].left;
                _productCanvasPosition[_productTag]['view_' + _view].top = _viewHash['view_' + _view]['position'].top;
            }

            isEmpty = false;
        } else {
            _objectHash = {};
            _sorting = [];
            _viewHash['view_' + _view] = {};
            _viewHash['view_' + _view]['box'] = _objectHash;
            _viewHash['view_' + _view]['sorting'] = _sorting;
            _viewHash['view_' + _view]['position'] = {
                left: (data.available_area.px_size.width - data.print_area.width * factor) / 2,
                //				top: (data.available_area.cm_size[first].height - data.print_area.height) * factor / 2
                top: 0
            };

            if (!_productCanvasPosition[_productTag]) {
                _productCanvasPosition[_productTag] = {};
            }

            _productCanvasPosition[_productTag]['view_' + _view] = {};

            _productCanvasPosition[_productTag]['view_' + _view].left = _viewHash['view_' + _view]['position'].left;
            _productCanvasPosition[_productTag]['view_' + _view].top = _viewHash['view_' + _view]['position'].top;
        }


        _viewHash['view_' + _view]['ratio'] = _ratio;

        CupSell.Generator.StorageManager.store('previousPid', _productTag);
        CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));

        _canvas.attr('width', parseInt(data.print_area.width * factor));
        _canvas.attr('height', parseInt(data.print_area.height * factor));

        _canvas.show();

        $(window).resize(function () {
            var fixWidthDynamicSpace = parseInt(parseInt(($('#designBox').width()) - 441) / 2);

            $('#workspaceBox').css({
                width: parseInt(data.available_area.px_size.width) + 'px',
                height: parseInt(data.available_area.cm_size[first].height * factor) + 'px',
                left: fixWidthDynamicSpace + parseInt(data.available_area.px_size.center_x - data.available_area.px_size.width / 2) + 'px',
                top: parseInt(data.available_area.px_size.center_y - data.available_area.cm_size[first].height * factor / 2) + 'px'
            });
        });
        $(window).resize();

        if ($('#generator').data('debug')) {
            $('#workspaceBox').css({
                border: '1px solid #0000FF'
            });
        }

        $('#workspaceBox').show();

        $('#canvasBox').css({
            width: parseInt(data.print_area.width * factor),
            height: parseInt(data.print_area.height * factor),
            left: parseInt(_viewHash['view_' + _view]['position'].left) + 'px',
            top: parseInt(_viewHash['view_' + _view]['position'].top) + 'px'
        });

        $('#canvasBox').droppable({
            tolerance: 'touch',
            accept: $('#userImages div'),
            create: function (event, ui)
            {
                var offset = $('#canvasBox').offset();
                this.props = {
                    left: offset.left,
                    top: offset.top
                };
            },
            drop: function (event, ui)
            {
                var container = $('#' + $(ui.helper).data('id'));
                var data = container.data('imageData');
                var offset = $(ui.helper).offset();
                if (!data) {
                    var dataOffset = {};
                    dataOffset.left = offset.left - this.props.left;
                    dataOffset.top = offset.top - this.props.top;
                    CupSell.Generator.ImagesManager.addImage(container, dataOffset);
                    return;
                }

                data.offset = {};
                data.offset.left = offset.left - this.props.left;
                data.offset.top = offset.top - this.props.top;

                _addImg(data);
            }
        });

        $('.txtBox, .imgBox').hide();

        if (!isEmpty) {
            _restoreImages();
        } else {
            _image = {};
            //			$('#reset').attr('disabled', true);
            setTimeout(_redraw, 200);
        }

        CupSell.Generator.Basket.updatePrice();
    }

    function _createTxtBox(align)
    {
        var index = undefined,
                box = undefined,
                boxProps = undefined,
                unredoProps = {},
                dimension = undefined,
                ratio = 1;

        index = _sorting.length == 0 ? 0 : Math.max.apply(undefined, _sorting) + 1;
        box = $(document.createElement('div')).attr('id', 'v' + _view + 'b' + index).addClass('txt-box txtBox view_' + _view);
        boxProps = new BoxProps('v' + _view + 'b' + index);

        boxProps.props.index = index;
        boxProps.props.align = align;
        boxProps.props.initalign = align;

        if (CupSell.Generator.Editor.isEmpty()) {

            var txtColor = undefined;

            if (CupSell.Generator.Views.getFontColor()) {
                txtColor = CupSell.Generator.Views.getFontColor();
            } else {
                txtColor = CupSell.Generator.Editor.getBackgroundColor() == '#000000' ? '#FFFFFF' : '#000000';
            }
            boxProps.props.htmlChunk = [{
                    txt: DEFAULT_TXT,
                    font: $('#font')[0].value,
                    fontSize: DEFAULT_TXT_FONT_SIZE,
                    color: txtColor
                }];

            boxProps.props.html = '&lt;span style="font-family: ' + boxProps.props.htmlChunk[0].font + '; font-size: ' + DEFAULT_TXT_FONT_SIZE + '; color: ' + txtColor + ';"&gt;' + DEFAULT_TXT + '&lt;/span&gt;';

        } else {
            boxProps.props.htmlChunk = CupSell.Generator.Editor.getSpanChunks();
            boxProps.props.html = CupSell.Generator.Editor.getHTML();
        }

        dimension = _measureChunk(boxProps.props);
        boxProps.props.lineWidth = dimension.lineWidth;
        boxProps.props.lineOffset = dimension.lineOffset;

        boxProps.props.width = dimension.width;
        boxProps.props.left = Math.floor((_canvas.width() - boxProps.props.width) / 2);

        boxProps.props.height = dimension.height;
        boxProps.props.top = Math.floor((_canvas.height() - boxProps.props.height) / 2);

        if (boxProps.props.width &gt; _canvas.width()) {
            ratio = _canvas.width() / boxProps.props.width;
            boxProps.props.left = 0;
        }

        if (boxProps.props.height &gt; _canvas.height()) {
            if (_canvas.height() / boxProps.props.height &lt; ratio) {
                ratio = _canvas.height() / boxProps.props.height;
                boxProps.props.top = 0;
            }
        }

        boxProps.props.xscale = ratio;
        boxProps.props.yscale = ratio;

        boxProps.props.width *= ratio;
        boxProps.props.height *= ratio;

        boxProps.props.rect = {
            left: boxProps.props.left,
            top: boxProps.props.top,
            width: boxProps.props.width,
            height: boxProps.props.height
        };

        for (var key in boxProps.props) {
            unredoProps[key] = boxProps.props[key];
        }

        _setUnReDoProps(boxProps.props.id, {
            start: null,
            end: unredoProps
        });
        box.css({
            position: 'absolute',
            top: boxProps.props.top + 'px',
            left: boxProps.props.left + 'px',
            width: boxProps.props.width + 'px',
            height: boxProps.props.height + 'px',
            zIndex: 900,
            backgroundColor: 'transparent'
        });
        _registerBoxEvents(box);

        //add text sprite props to hash
        _objectHash[box.attr('id')] = boxProps;
        _sorting.push(boxProps.props.index);

        CupSell.Generator.Basket.updatePrice();
        CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));

        $('#canvasBox').append(box);
        //		$('#reset').attr('disabled', false);

        if (_activeBoxId) {
            _deactivateBox($('#' + _activeBoxId));
        }

        _activateBox(box);

        //_getDesignBoundingBox();		
        setTimeout(_redraw, 200);
    }


    function _getTextOffset(htmlChunk)
    {
        var txtControl = document.getElementById("txtControl"),
                chunk = undefined,
                fontSize = 0;

        txtControl.textContent = htmlChunk.txt;
        txtControl.style.font = htmlChunk.fontSize + ' ' + htmlChunk.font;
        var offsetH = txtControl.offsetHeight;
        if (htmlChunk.font === "Gruby") {
            if (htmlChunk.fontSize === "12px")
                offsetH = 10.4;
            if (htmlChunk.fontSize === "16px")
                offsetH = 14.4;
            if (htmlChunk.fontSize === "20px")
                offsetH = 18;
            if (htmlChunk.fontSize === "24px")
                offsetH = 21;
            if (htmlChunk.fontSize === "28px")
                offsetH = 24.6;
            if (htmlChunk.fontSize === "32px")
                offsetH = 28.8;
            if (htmlChunk.fontSize === "36px")
                offsetH = 33;
            if (htmlChunk.fontSize === "40px")
                offsetH = 35;
        }
        if (htmlChunk.font === 'yellowtailregular') {
            offsetH -= 5;
        }
        return BitmapText.getBitmapBounds({
            text: htmlChunk.txt,
            bboxHeight: offsetH,
            fontFamily: htmlChunk.font,
            fontSize: parseInt(htmlChunk.fontSize)
        });
    }


    function _resetTxt(boxId)
    {
        var boxProps = _objectHash[boxId].props;

        boxProps.html = '&lt;span style="font-family: ' + $('#font')[0].value + '; font-size: ' + $('#size')[0].value + 'px; color: #000000;"&gt;' + CupSell.Generator.Editor.getText() + '&lt;/span&gt;';

        boxProps.align = boxProps.initalign;

        CupSell.Generator.Editor.setHTML(boxProps.html);
        boxProps.htmlChunk = CupSell.Generator.Editor.getSpanChunks();

        _updateTxtField(boxId);

        _redraw();
    }

    function _addImg(data)
    {
        var img = undefined;

        img = new Image();

        img.src = data.sprite;
        img.onload = function ()
        {
            _createImgBox(img, data);
        }
    }


    function _createImgBox(img, data)
    {
        var index = _sorting.length == 0 ? 0 : Math.max.apply(undefined, _sorting) + 1,
                box = $(document.createElement('div')).attr('id', 'v' + _view + 'b' + index).addClass('img-box imgBox view_' + _view),
                boxProps = new BoxProps('v' + _view + 'b' + index),
                unredoProps = {},
                ratio = 1,
                viewHash = undefined;

        _image['v' + _view + 'b' + index] = img;

        boxProps.props.index = index;
        boxProps.props.imgRatio = _ratio;
        boxProps.props.sprite = data.sprite;
        boxProps.props.userImage = data.userImage;

        boxProps.props.width = Math.ceil(_ratio * data.originalSize.width);

        // if image wider than print area fit image inside
        if (boxProps.props.width &gt; $('#canvasBox').width()) {
            ratio = $('#canvasBox').width() / boxProps.props.width;
            boxProps.props.left = 0;
        }


        boxProps.props.height = Math.ceil(_ratio * data.originalSize.height);

        // if image higher than print area fit image inside
        if (boxProps.props.height &gt; $('#canvasBox').height()) {
            if ($('#canvasBox').height() / boxProps.props.height &lt; ratio) {
                ratio = $('#canvasBox').height() / boxProps.props.height;
            }
            boxProps.props.top = 0;
        }
        // if image wider than picture fit image inside

        if (boxProps.props.width &gt; $('#productView img').width()) {
            if ($('#productView img').width() / boxProps.props.width &lt; ratio) {
                ratio = $('#productView img').width() / boxProps.props.width;
                boxProps.props.top = ($('#canvasBox').height() / 2) - (boxProps.props.height * ratio / 2);
                boxProps.props.left = ($('#canvasBox').width() / 2) - (boxProps.props.width * ratio / 2);
            }
        }
        // if image higher than picture area fit image inside
        if (boxProps.props.height &gt; $('#productView img').height()) {
            if ($('#productView img').height() / boxProps.props.height &lt; ratio) {
                ratio = $('#productView img').height() / boxProps.props.height;
                boxProps.props.top = ($('#canvasBox').height() / 2) - (boxProps.props.height * ratio / 2);
                boxProps.props.left = ($('#canvasBox').width() / 2) - (boxProps.props.width * ratio / 2);
            }
        }

        boxProps.props.xscale = ratio;
        boxProps.props.yscale = ratio;

        boxProps.props.width = Math.ceil(boxProps.props.width * ratio);
        boxProps.props.height = Math.ceil(boxProps.props.height * ratio);

        if (boxProps.props.left == undefined) {
            if (data.offset) {
                if (data.offset.left &lt; 0) {
                    boxProps.props.left = 0;
                } else if (data.offset.left + boxProps.props.width &gt; $('#canvasBox').width()) {
                    boxProps.props.left = $('#canvasBox').width() - boxProps.props.width;
                } else {
                    boxProps.props.left = data.offset.left;
                }
            } else {
                boxProps.props.left = (_canvas.width() - _ratio * data.originalSize.width) / 2;
            }
        }

        if (boxProps.props.top == undefined) {
            if (data.offset) {
                if (data.offset.top &lt; 0) {
                    boxProps.props.top = 0;
                } else if (data.offset.top + boxProps.props.height &gt; $('#canvasBox').height()) {
                    boxProps.props.top = $('#canvasBox').height() - boxProps.props.height;
                } else {
                    boxProps.props.top = data.offset.top;
                }
            } else {
                boxProps.props.top = (_canvas.height() - _ratio * data.originalSize.height) / 2;
            }
        }

        boxProps.props.rect = {
            left: boxProps.props.left,
            top: boxProps.props.top,
            width: boxProps.props.width,
            height: boxProps.props.height
        };

        for (var key in boxProps.props) {
            unredoProps[key] = boxProps.props[key];
        }

        _setUnReDoProps(boxProps.props.id, {
            start: null,
            end: unredoProps
        });

        //set box css styles
        box.css({
            position: 'absolute',
            top: boxProps.props.top + 'px',
            left: boxProps.props.left + 'px',
            width: boxProps.props.width + 'px',
            height: boxProps.props.height + 'px',
            zIndex: 900,
            backgroundColor: 'transparent'
        });

        _registerBoxEvents(box);

        //add text sprite props to hash
        _objectHash[box.attr('id')] = boxProps;
        _sorting.push(boxProps.props.index);

        CupSell.Generator.Basket.updatePrice();
        CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));

        $('#canvasBox').append(box);
        //		$('#reset').attr('disabled', false);

        if (_activeBoxId) {
            _deactivateBox($('#' + _activeBoxId));
        }

        _activateBox(box);

        //redraw canvas elements
        _redraw();
    }


    function _activateBox(box)
    {
        var boxProps = _objectHash[box.attr('id')].props;
        _activeBoxId = box.attr('id');
        _setBoxRect(_activeBoxId);

        box.addClass('active');
        $('#controls').css({
            'left': boxProps.left,
            'top': boxProps.top
        });

        $('#controls').show();

        if (boxProps.html) {
            _updateTxtField(_activeBoxId);
            CupSell.Generator.Editor.setHTML(boxProps.html);
            CupSell.Generator.Editor.setFocus(false);
            CupSell.Generator.Editor.setAlign(boxProps.align);
            //			CupSell.Generator.Editor.enableReset();
        } else {
            _relocateControls(_activeBoxId);
        }

        //  boxProps.html ? CupSell.Generator.Tabs.togglePanel('editorTab', true) : CupSell.Generator.Tabs.togglePanel('imageTab');

        if (_sorting.indexOf(boxProps.index) != _sorting.length - 1) {

            $('#canvasBox').append(box);

            _sorting.splice(_sorting.indexOf(boxProps.index), 1)
            _sorting.push(boxProps.index);
            _redraw();
        }
    }

    function _deactivateBox(box)
    {
        box.removeClass('active');
        $('#controls').hide();

        if (box.hasClass('txtBox')) {
            CupSell.Generator.Editor.setHTML('');
            //			CupSell.Generator.Editor.disableReset();
        }

        _activeBoxId = undefined;
    }

    function _restoreImages()
    {
        var boxProps = undefined,
                images = [],
                total = 0,
                counter = 0;

        _image = {};

        for (var i = 0; i &lt; _sorting.length; i++) {
            if (_objectHash['v' + _view + 'b' + _sorting[i]].props.sprite) {
                total++;
            }
        }

        if (total == 0) {
            _restoreBoxes();
        } else {

            for (var i = 0; i &lt; _sorting.length; i++) {
                boxProps = _objectHash['v' + _view + 'b' + _sorting[i]].props;

                if (boxProps.sprite) {
                    images[i] = new Image();
                    images[i].src = boxProps.sprite;
                    $.data(images[i], 'i', i);
                    images[i].onload = function ()
                    {
                        _image['v' + _view + 'b' + _sorting[$.data(this, 'i')]] = this;
                        counter++;
                        if (counter == total) {
                            _restoreBoxes();
                        }
                    }
                }
            }
        }
    }


    function _restoreBoxes()
    {
        var box = undefined
        degs = undefined;

        for (var i = 0; i &lt; _sorting.length; i++) {
            boxProps = _objectHash['v' + _view + 'b' + _sorting[i]].props;
            if (!$('#' + boxProps.id)[0]) {

                box = $(document.createElement('DIV')).attr('id', boxProps.id).addClass('view_' + _view).appendTo($('#canvasBox'));

                _registerBoxEvents(box);
                if (boxProps.html) {
                    box.addClass('txt-box txtBox');
                } else {
                    box.addClass('img-box imgBox');
                }

                box.css({
                    position: 'absolute',
                    top: boxProps.top + 'px',
                    left: boxProps.left + 'px',
                    width: boxProps.width + 'px',
                    height: boxProps.height + 'px',
                    zIndex: 900,
                    backgroundColor: 'transparent'
                });

                if (boxProps.rotation != 0) {
                    degs = boxProps.rotation * 180 / Math.PI;
                    box.css('-moz-transform', 'rotate(' + degs + 'deg)');
                    box.css('-webkit-transform', 'rotate(' + degs + 'deg)');
                    box.css('-o-transform', 'rotate(' + degs + 'deg)');
                    box.css('-ms-transform', 'rotate(' + degs + 'deg)');
                }
            }
        }

        $('.view_' + _view).show();

        setTimeout(_redraw, 200);
    }


    function _restoreBox(object)
    {
        var index = undefined,
                box = $(document.createElement('div')).attr('id', object.boxId),
                boxProps = undefined,
                props = {};

        if (object.props.start == null) {
            for (var key in object.props.end) {
                props[key] = object.props.end[key];
            }
        } else {
            for (var key in object.props.start) {
                props[key] = object.props.start[key];
            }
        }

        boxProps = new BoxProps('v' + object.view + 'b' + props.index);
        boxProps.props = props;

        if (boxProps.props.html) {
            box.addClass('img-box txtBox view_' + object.view);
        } else {
            box.addClass('img-box imgBox view_' + object.view);
        }

        box.css({
            position: 'absolute',
            top: boxProps.props.top + 'px',
            left: boxProps.props.left + 'px',
            width: boxProps.props.width + 'px',
            height: boxProps.props.height + 'px',
            zIndex: 900,
            backgroundColor: 'transparent'
        });

        _registerBoxEvents(box);

        //add text sprite props to hash
        _objectHash[box.attr('id')] = boxProps;
        _sorting.push(boxProps.props.index);

        CupSell.Generator.Basket.updatePrice();
        CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));

        $('#canvasBox').append(box);
        //		$('#reset').attr('disabled', false);

        _redraw();
        //		setTimeout(_redraw, 300);
    }


    function _registerBoxEvents(box)
    {
        box.draggable({
            start: function (event)
            {
                var boxProps = _objectHash[this.id].props,
                        cbPos = $('#canvasBox').position(),
                        positions = {},
                        id = undefined;

                _setBoxRect(this.id);

                for (var i = 0; i &lt; _sorting.length; i++) {
                    id = 'v' + _view + 'b' + _sorting[i];

                    positions[id] = {
                        left: _objectHash[id].props.left,
                        top: _objectHash[id].props.top,
                        rect: {
                            top: _objectHash[id].props.rect.top,
                            left: _objectHash[id].props.rect.left,
                            width: _objectHash[id].props.rect.width,
                            height: _objectHash[id].props.rect.height
                        }
                    };
                }

                this.props = {
                    left: parseInt(boxProps.left),
                    top: parseInt(boxProps.top),
                    mx: event.pageX,
                    my: event.pageY,
                    xoffset: cbPos.left,
                    yoffset: cbPos.top,
                    rectX: parseInt(boxProps.rect.left),
                    rectY: parseInt(boxProps.rect.top),
                    positions: positions
                };
            },
            drag: function (event, ui)
            {
                var boxProps = _objectHash[this.id].props,
                        dX = event.pageX - this.props.mx,
                        dY = event.pageY - this.props.my,
                        left = this.props.rectX + dX,
                        top = this.props.rectY + dY,
                        canvasBox = $('#canvasBox'),
                        cbPos = undefined,
                        cbDX = 0,
                        cbDY = 0,
                        id = undefined;
                if (left &lt;= 0) {
                    if (this.props.xoffset + left &lt; 0) {
                        canvasBox.css('left', 0);
                    } else {
                        canvasBox.css('left', this.props.xoffset + left + 'px');
                    }

                    boxProps.rect.left = 0;
                    boxProps.left = this.props.left - this.props.rectX;
                } else if (boxProps.rect.width + left &gt;= canvasBox.width()) {
                    if (this.props.xoffset + left + boxProps.rect.width &gt; $('#workspaceBox').width()) {
                        canvasBox.css('left', $('#workspaceBox').width() - canvasBox.width() + 'px');
                    } else {
                        canvasBox.css('left', this.props.xoffset + (left + boxProps.rect.width - canvasBox.width()) + 'px');
                    }

                    boxProps.rect.left = canvasBox.width() - boxProps.rect.width;
                    boxProps.left = this.props.left + boxProps.rect.left - this.props.rectX;
                } else {
                    boxProps.rect.left = left;
                    boxProps.left = this.props.left + dX;
                }


                ui.position.left = boxProps.left;

                if (top &lt;= 0) {
                    if (this.props.yoffset + top &lt; 0) {
                        canvasBox.css('top', 0);
                    } else {
                        canvasBox.css('top', this.props.yoffset + top + 'px');
                    }

                    boxProps.rect.top = 0;
                    boxProps.top = this.props.top - this.props.rectY;
                } else if (top + boxProps.rect.height &gt;= canvasBox.height()) {
                    if (this.props.yoffset + top + boxProps.rect.height &gt; $('#workspaceBox').height()) {
                        canvasBox.css('top', $('#workspaceBox').height() - canvasBox.height() + 'px');
                    } else {
                        canvasBox.css('top', this.props.yoffset + (top + boxProps.rect.height - canvasBox.height()) + 'px');
                    }

                    boxProps.rect.top = canvasBox.height() - boxProps.rect.height;
                    boxProps.top = this.props.top + boxProps.rect.top - this.props.rectY;
                } else {
                    boxProps.rect.top = top;
                    boxProps.top = this.props.top + dY;
                }


                ui.position.top = boxProps.top;

                //move other elements if canvas box position is changed
                cbPos = $('#canvasBox').position();

                if (cbPos.left != this.props.xoffset || cbPos.top != this.props.yoffset) {

                    cbDX = cbPos.left - this.props.xoffset;
                    cbDY = cbPos.top - this.props.yoffset;

                    for (var i = 0; i &lt; _sorting.length; i++) {
                        id = 'v' + _view + 'b' + _sorting[i];

                        if (this.id != id) {
                            if (cbDX != 0) {
                                if (cbDX &gt; 0) {
                                    if (this.props.positions[id].rect.left - cbDX &lt; 0) {
                                        _objectHash[id].props.rect.left = 0;
                                        _objectHash[id].props.left = this.props.positions[id].left - this.props.positions[id].rect.left;
                                    } else {
                                        _objectHash[id].props.rect.left = this.props.positions[id].rect.left - cbDX;
                                        _objectHash[id].props.left = this.props.positions[id].left - cbDX;
                                    }
                                } else if (cbDX &lt; 0) {
                                    if (this.props.positions[id].rect.left + _objectHash[id].props.rect.width - cbDX &gt; canvasBox.width()) {
                                        _objectHash[id].props.rect.left = canvasBox.width() - _objectHash[id].props.rect.width;
                                        _objectHash[id].props.left = this.props.positions[id].left + canvasBox.width() - (this.props.positions[id].rect.left + _objectHash[id].props.rect.width);
                                    } else {
                                        _objectHash[id].props.left = this.props.positions[id].left - cbDX;
                                        _objectHash[id].props.rect.left = this.props.positions[id].rect.left - cbDX;
                                    }
                                }


                                $('#' + id).css({
                                    left: _objectHash[id].props.left + 'px'
                                });
                            }


                            if (cbDY != 0) {
                                if (cbDY &gt; 0) {
                                    if (this.props.positions[id].rect.top - cbDY &lt; 0) {
                                        _objectHash[id].props.rect.top = 0;
                                        _objectHash[id].props.top = this.props.positions[id].top - this.props.positions[id].rect.top;
                                    } else {
                                        _objectHash[id].props.rect.top = this.props.positions[id].rect.top - cbDY;
                                        _objectHash[id].props.top = this.props.positions[id].top - cbDY;
                                    }
                                } else if (cbDY &lt; 0) {
                                    if (this.props.positions[id].rect.top + _objectHash[id].props.rect.height - cbDY &gt; canvasBox.height()) {
                                        _objectHash[id].props.rect.top = canvasBox.height() - _objectHash[id].props.rect.height;
                                        _objectHash[id].props.top = this.props.positions[id].top + canvasBox.height() - (this.props.positions[id].rect.top + _objectHash[id].props.rect.height);
                                    } else {
                                        _objectHash[id].props.top = this.props.positions[id].top - cbDY;
                                        _objectHash[id].props.rect.top = this.props.positions[id].rect.top - cbDY;
                                    }
                                }


                                $('#' + id).css({
                                    top: _objectHash[id].props.top + 'px'
                                });
                            }
                        }
                    }
                }
                //_tempBox(boxProps.rect.left, boxProps.rect.top, boxProps.rect.width, boxProps.rect.height)
                _redraw();
            },
            stop: function ()
            {
                var boxProps = _objectHash[this.id].props,
                        canvasBox = $('#canvasBox'),
                        cbPos = $('#canvasBox').position(),
                        positions = {},
                        id = undefined;

                if (this.props.left &lt; 0) {
                    this.props.left = 0;
                }

                if (this.props.left + boxProps.rect.width &gt; canvasBox.width()) {
                    this.props.left = canvasBox.width() - boxProps.rect.width;
                }

                if (this.props.top &lt; 0) {
                    this.props.top = 0;
                }

                if (this.props.top + boxProps.rect.height &gt; canvasBox.height()) {
                    this.props.top = canvasBox.height() - boxProps.rect.height;
                }

                if (this.props.xoffset != cbPos.left || this.props.yoffset != cbPos.top) {
                    _viewHash['view_' + _view]['position'].left = cbPos.left;
                    _viewHash['view_' + _view]['position'].top = cbPos.top;

                    //to jest bez sensu te obiekty powinny istniec
                    if (!_productCanvasPosition[_productTag]) {
                        _productCanvasPosition[_productTag] = {};
                    }

                    _productCanvasPosition[_productTag]['view_' + _view] = {};

                    _productCanvasPosition[_productTag]['view_' + _view].left = _viewHash['view_' + _view]['position'].left;
                    _productCanvasPosition[_productTag]['view_' + _view].top = _viewHash['view_' + _view]['position'].top;
                }

                _setUnReDoProps(this.id, {
                    start: {
                        left: this.props.left,
                        top: this.props.top
                    },
                    end: {
                        left: boxProps.left,
                        top: boxProps.top
                    }
                }, {
                    start: {
                        top: this.props.yoffset,
                        left: this.props.xoffset
                    },
                    end: {
                        top: cbPos.top,
                        left: cbPos.left
                    }
                });

                if (cbPos.left != this.props.xoffset || cbPos.top != this.props.yoffset) {
                    for (var i = 0; i &lt; _sorting.length; i++) {
                        id = 'v' + _view + 'b' + _sorting[i];

                        _setBoxRect(id);

                        positions[id] = {
                            left: _objectHash[id].props.left,
                            top: _objectHash[id].props.top,
                            rect: _objectHash[id].props.rect
                        };
                    }

                    CupSell.Generator.UnReDo.setPositions({
                        start: this.props.positions,
                        end: positions
                    });
                }

                if (_activeBoxId) {
                    if (_activeBoxId == this.id) {
                        $('#controls').css({
                            left: boxProps.left,
                            top: boxProps.top
                        });

                        _relocateControls(_activeBoxId, true);
                    }

                    if ((cbPos.left != this.props.xoffset || cbPos.top != this.props.yoffset) &amp;&amp; _activeBoxId != this.id) {
                        $('#controls').css({
                            left: _objectHash[_activeBoxId].props.left,
                            top: _objectHash[_activeBoxId].props.top
                        });

                        _relocateControls(_activeBoxId, true);
                    }

                    $('#controls').show();
                }
                //_getDesignBoundingBox();
                CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));
            }
        });

        box.mousedown(function (event)
        {
            $('#controls').hide();
        });

        box.click(function (event)
        {
            var target = $(event.target);

            if (_activeBoxId) {
                if (_activeBoxId == target.attr('id')) {
                    _deactivateBox(target);
                } else {
                    $('#' + _activeBoxId).removeClass('active');
                    if (_objectHash[_activeBoxId].props.html) {
                        //						CupSell.Generator.Editor.disableReset();
                    }
                    _activateBox(target);
                }
            } else {
                _activateBox(target);
            }
        });
    }


    function _adjustBox(boxId)
    {
        var box = $('#' + boxId),
                boxProps = _objectHash[boxId].props,
                degs = boxProps.rotation * 180 / Math.PI;

        $('#controls').css({
            'left': boxProps.left,
            'top': boxProps.top
        });

        box.css({
            'top': boxProps.top,
            'left': boxProps.left,
            'width': boxProps.width,
            'height': boxProps.height
        });

        box.css('-moz-transform', 'rotate(' + degs + 'deg)');
        box.css('-webkit-transform', 'rotate(' + degs + 'deg)');
        box.css('-o-transform', 'rotate(' + degs + 'deg)');
        box.css('-ms-transform', 'rotate(' + degs + 'deg)');

        _relocateControls(boxId, true);
        CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));
    }


    function _relocateControls(boxId, isRectChanged)
    {
        var boxProps = _objectHash[boxId].props,
                radius = _getRadius(boxProps.width, boxProps.height),
                corners = _getBoundingBoxCorners(boxProps.width, boxProps.height, boxProps.rotation, radius);

        isRectChanged = !!isRectChanged;

        $('#ulC_').css({
            top: corners.tops[0] - CONTROL_CENTER_OFFSET,
            left: corners.lefts[0] - CONTROL_CENTER_OFFSET
        });

        $('#urC_').css({
            top: corners.tops[1] - CONTROL_CENTER_OFFSET,
            left: corners.lefts[1] - CONTROL_CENTER_OFFSET
        });

        $('#rC_').css({
            top: boxProps.height / 2 + Math.sin(boxProps.rotation) * boxProps.width / 2 - CONTROL_CENTER_OFFSET,
            left: (1 + Math.cos(boxProps.rotation)) * boxProps.width / 2 - CONTROL_CENTER_OFFSET
        });

        $('#brC_').css({
            top: corners.tops[2] - CONTROL_CENTER_OFFSET,
            left: corners.lefts[2] - CONTROL_CENTER_OFFSET
        });

        $('#bC_').css({
            top: (1 + Math.cos(boxProps.rotation)) * boxProps.height / 2 - CONTROL_CENTER_OFFSET,
            left: boxProps.width / 2 - Math.sin(boxProps.rotation) * boxProps.height / 2 - CONTROL_CENTER_OFFSET
        });

        if (isRectChanged) {
            boxProps.rect.top = parseInt(boxProps.top + Math.min.apply(undefined, corners.tops));
            boxProps.rect.left = parseInt(boxProps.left + Math.min.apply(undefined, corners.lefts));
            boxProps.rect.width = parseInt(Math.max(Math.abs(corners.lefts[0] - corners.lefts[2]), Math.abs(corners.lefts[1] - corners.lefts[3])));
            boxProps.rect.height = parseInt(Math.max(Math.abs(corners.tops[0] - corners.tops[2]), Math.abs(corners.tops[1] - corners.tops[3])));

            //_rectBox(boxProps.rect.left, boxProps.rect.top, boxProps.rect.width, boxProps.rect.height);
        }
    }


    function _setBoxRect(boxId)
    {
        var boxProps = _objectHash[boxId].props,
                radius = undefined,
                corners = undefined;

        if (boxProps.rotation == 0) {
            boxProps.rect.top = boxProps.top;
            boxProps.rect.left = boxProps.left;
            boxProps.rect.width = boxProps.width;
            boxProps.rect.height = boxProps.height;

        } else {
            radius = _getRadius(boxProps.width, boxProps.height),
                    corners = _getBoundingBoxCorners(boxProps.width, boxProps.height, boxProps.rotation, radius);

            boxProps.rect.top = Math.floor(boxProps.top + Math.min.apply(undefined, corners.tops));
            boxProps.rect.left = Math.floor(boxProps.left + Math.min.apply(undefined, corners.lefts));
            boxProps.rect.width = Math.ceil(Math.max(Math.abs(corners.lefts[0] - corners.lefts[2]), Math.abs(corners.lefts[1] - corners.lefts[3])));
            boxProps.rect.height = Math.ceil(Math.max(Math.abs(corners.tops[0] - corners.tops[2]), Math.abs(corners.tops[1] - corners.tops[3])));
        }

        //_rectBox(boxProps.rect.left, boxProps.rect.top, boxProps.rect.width, boxProps.rect.height);
    }


    function _isOffside(boxId, width, height, rotation)
    {
        var boxProps = _objectHash[boxId].props,
                box = {},
                radius = _getRadius(width, height),
                corners = _getBoundingBoxCorners(width, height, rotation, radius);

        box.top = Math.floor(boxProps.top + Math.min.apply(undefined, corners.tops));
        box.left = Math.floor(boxProps.left + Math.min.apply(undefined, corners.lefts));
        box.width = Math.max(Math.abs(corners.lefts[0] - corners.lefts[2]), Math.abs(corners.lefts[1] - corners.lefts[3]));
        box.height = Math.max(Math.abs(corners.tops[0] - corners.tops[2]), Math.abs(corners.tops[1] - corners.tops[3]));

        if (box.top &lt; (-box.height) || box.left &lt; (-box.width) || box.top &gt; $('#canvasBox').height() || box.left &gt; $('#canvasBox').width()) {
            return true;
        } else {
            return false;
        }
    }


    function _getBoundingBoxCorners(width, height, rotation, radius)
    {
        // top and left starts from upper left corner in clockwise direction
        var tops = [
            height / 2 - Math.floor(radius * Math.sin(Math.atan(height / width) + rotation)),
            height / 2 - Math.floor(radius * Math.sin(Math.atan(height / width) - rotation)),
            height / 2 + Math.ceil(radius * Math.sin(Math.atan(height / width) + rotation)),
            height / 2 + Math.ceil(radius * Math.sin(Math.atan(height / width) - rotation))
        ],
                lefts = [
                    width / 2 - Math.floor(radius * Math.cos(Math.atan(height / width) + rotation)),
                    width / 2 + Math.ceil(radius * Math.cos(Math.atan(height / width) - rotation)),
                    width / 2 + Math.ceil(radius * Math.cos(Math.atan(height / width) + rotation)),
                    width / 2 - Math.floor(radius * Math.cos(Math.atan(height / width) - rotation))
                ];

        return {
            tops: tops,
            lefts: lefts
        };
    }


    function _getDesignBoundingBox()
    {
        var sorting = undefined,
                boxProps = undefined,
                corners = undefined,
                boundingBox = {},
                left = 0,
                top = 0,
                width = 0,
                height = 0;

        for (var viewId in _viewHash) {
            sorting = _viewHash[viewId]['sorting'];

            for (var i = 0; i &lt; sorting.length; i++) {
                boxProps = _viewHash[viewId]['box']['v' + viewId.replace('view_', '') + 'b' + sorting[i]].props;
                corners = _getBoundingBoxCorners(boxProps.width, boxProps.height, boxProps.rotation, _getRadius(boxProps.width, boxProps.height));

                top = boxProps.top + Math.min.apply(undefined, corners.tops);
                left = boxProps.left + Math.min.apply(undefined, corners.lefts);
                width = Math.max(Math.abs(corners.lefts[0] - corners.lefts[2]), Math.abs(corners.lefts[1] - corners.lefts[3]));
                height = Math.max(Math.abs(corners.tops[0] - corners.tops[2]), Math.abs(corners.tops[1] - corners.tops[3]));

                if (i == 0) {
                    boundingBox[viewId] = {};

                    boundingBox[viewId].top = top;
                    boundingBox[viewId].left = left;
                    boundingBox[viewId].width = width;
                    boundingBox[viewId].height = height;
                } else {
                    if (top &lt; boundingBox[viewId].top) {
                        boundingBox[viewId].height += boundingBox[viewId].top - top;
                        boundingBox[viewId].top = top;
                    }

                    if (left &lt; boundingBox[viewId].left) {
                        boundingBox[viewId].width += boundingBox[viewId].left - left;
                        boundingBox[viewId].left = left;
                    }

                    if (left + width &gt; boundingBox[viewId].left + boundingBox[viewId].width) {
                        boundingBox[viewId].width = left + width - boundingBox[viewId].left;
                    }

                    if (top + height &gt; boundingBox[viewId].top + boundingBox[viewId].height) {
                        boundingBox[viewId].height = top + height - boundingBox[viewId].top;
                    }
                }
            }
        }

        //		if(_sorting.length &gt; 0) {
        //			_tempBox(boundingBox['view_' + _view].left, boundingBox['view_' + _view].top, boundingBox['view_' + _view].width, boundingBox['view_' + _view].height);
        //		}

        return boundingBox;
    }


    function _removeActiveBox()
    {
        var boxId = _activeBoxId,
                boxProps = _objectHash[_activeBoxId].props,
                unredoProps = {};

        for (var key in boxProps) {
            unredoProps[key] = boxProps[key];
        }

        _setUnReDoProps(_activeBoxId, {
            start: unredoProps,
            end: null
        });
        _deleteBox(_activeBoxId);
    }


    function _removeBox(boxId)
    {
        var boxProps = _objectHash[boxId].props,
                unredoProps = {};

        for (var key in boxProps) {
            unredoProps[key] = boxProps[key];
        }

        _setUnReDoProps(boxId, {
            start: unredoProps,
            end: null
        });
        _deleteBox(boxId);
    }


    function _deleteBox(boxId)
    {
        var boxProps = undefined;

        if (boxId) {
            boxProps = _objectHash[boxId].props;

            $('#' + boxId).remove();

            if (boxProps.html) {
                CupSell.Generator.Editor.setHTML('');
                CupSell.Generator.Editor.setAlign('left');
                //				CupSell.Generator.Editor.disableReset();
            }

            _sorting.splice(_sorting.indexOf(boxProps.index), 1);

            delete _objectHash[boxId];

            CupSell.Generator.Basket.updatePrice();
            CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));

            if (boxId == _activeBoxId) {
                _activeBoxId = undefined;
            }
            $('#controls').hide();

            //			if(_sorting.length == 0) {
            //				$('#reset').attr('disabled', true);
            //			}

            _redraw();
        }
    }


    function _setUpControls()
    {
        $("#controls &gt; div").bind({
            mousedown: function (event)
            {
                if (event.target.id != 'ulC_') {
                    $(event.target).siblings().hide();
                }
            },
            mouseup: function (event)
            {
                if (event.target.id == 'ulC_') {
                    _removeActiveBox();
                } else {
                    $(event.target).siblings().show();
                }
            }
        });

        $('#rC_').draggable({
            start: function (event)
            {
                var boxProps = _objectHash[_activeBoxId].props;

                this.props = {
                    mx: event.pageX,
                    my: event.pageY,
                    xscale: boxProps.xscale,
                    boxWidth: boxProps.width,
                    baseBoxWidth: boxProps.width / boxProps.xscale
                };
            },
            drag: function (event, ui)
            {
                var boxProps = _objectHash[_activeBoxId].props,
                        //					dX = Math.abs(boxProps.rotation) == Math.PI / 2 ? 0 : (event.pageX - this.props.mx) / Math.cos(boxProps.rotation),
                        //					dY = boxProps.rotation == 0 || boxProps.rotation == Math.PI ? 0 : (event.pageY - this.props.my) / Math.sin(boxProps.rotation),
                        //					delta = undefined,
                        width = undefined,
                        xscale = undefined,
                        dM = Math.sqrt(Math.pow((event.pageX - this.props.mx), 2) + Math.pow((event.pageY - this.props.my), 2)),
                        dC = undefined;

                //				delta = Math.abs(dX) &gt; Math.abs(dY) ? dX : dY;
                //				width = this.props.boxWidth + delta;

                if (event.pageX - this.props.mx == 0) {
                    dC = Math.sin(boxProps.rotation) * (event.pageY - this.props.my);
                } else {
                    dC = dM * Math.cos(Math.abs(boxProps.rotation - Math.atan((event.pageY - this.props.my) / (event.pageX - this.props.mx))));
                }

                if (event.pageX - this.props.mx &gt; 0) {
                    width = parseInt(this.props.boxWidth + dC);
                } else {
                    width = parseInt(this.props.boxWidth - dC);
                }

                xscale = width / this.props.baseBoxWidth;

                if (width &gt;= 6 &amp;&amp; (boxProps.sprite &amp;&amp; xscale &lt;= 1 || boxProps.html) &amp;&amp; !_isOffside(_activeBoxId, width, boxProps.height, boxProps.rotation)) {
                    boxProps.width = width;
                    boxProps.xscale = xscale;

                    $('#' + _activeBoxId).css('width', width);
                }

                ui.position.left = (1 + Math.cos(boxProps.rotation)) * boxProps.width / 2 - CONTROL_CENTER_OFFSET;
                ui.position.top = (boxProps.height + Math.sin(boxProps.rotation) * boxProps.width) / 2 - CONTROL_CENTER_OFFSET;

                _redraw();
            },
            stop: function (event, ui)
            {
                var boxProps = _objectHash[_activeBoxId].props;


                _relocateControls(_activeBoxId, true);
                $(ui.helper[0]).siblings().show();

                _setUnReDoProps(_activeBoxId, {
                    start: {
                        xscale: this.props.xscale,
                        width: this.props.boxWidth
                    },
                    end: {
                        xscale: boxProps.xscale,
                        width: boxProps.width
                    }
                });

                CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));
            }
        });


        $('#bC_').draggable({
            start: function (event)
            {
                var boxProps = _objectHash[_activeBoxId].props;

                this.props = {
                    mx: event.pageX,
                    my: event.pageY,
                    yscale: boxProps.yscale,
                    boxHeight: boxProps.height,
                    baseBoxHeight: boxProps.height / boxProps.yscale
                };
            },
            drag: function (event, ui)
            {
                var boxProps = _objectHash[_activeBoxId].props,
                        //					dX = boxProps.rotation == 0 || boxProps.rotation == Math.PI  ? 0 : (event.pageX - this.props.mx) / Math.sin(boxProps.rotation),
                        //					dY = Math.abs(boxProps.rotation) == Math.PI / 2 ? 0 : (event.pageY - this.props.my) / Math.cos(boxProps.rotation),
                        //					delta = undefined,
                        height = undefined,
                        yscale = undefined,
                        dM = Math.sqrt(Math.pow((event.pageX - this.props.mx), 2) + Math.pow((event.pageY - this.props.my), 2)),
                        dC = undefined;


                //				delta = Math.abs(dY) &gt; Math.abs(dX) ? dY : dX;
                //				height = this.props.boxHeight + delta;

                if (event.pageY - this.props.my == 0) {
                    dC = Math.cos(boxProps.rotation) * (event.pageX - this.props.mx);
                } else {
                    dC = dM * Math.cos(Math.abs(boxProps.rotation - Math.atan((event.pageX - this.props.mx) / (event.pageY - this.props.my))));
                }

                if (event.pageY - this.props.my &gt; 0) {
                    height = parseInt(this.props.boxHeight + dC);
                } else {
                    height = parseInt(this.props.boxHeight - dC);
                }

                yscale = height / this.props.baseBoxHeight;

                if (height &gt;= 6 &amp;&amp; (boxProps.sprite &amp;&amp; yscale &lt;= 1 || boxProps.html) &amp;&amp; !_isOffside(_activeBoxId, boxProps.width, height, boxProps.rotation)) {
                    boxProps.height = height;
                    boxProps.yscale = yscale;

                    $('#' + _activeBoxId).css('height', height);
                }

                ui.position.left = (boxProps.width - Math.sin(boxProps.rotation) * boxProps.height) / 2 - CONTROL_CENTER_OFFSET;
                ui.position.top = (1 + Math.cos(boxProps.rotation)) * boxProps.height / 2 - CONTROL_CENTER_OFFSET;

                _redraw();
            },
            stop: function (event, ui)
            {
                var boxProps = _objectHash[_activeBoxId].props;

                _relocateControls(_activeBoxId, true);
                $(ui.helper[0]).siblings().show();

                _setUnReDoProps(_activeBoxId, {
                    start: {
                        yscale: this.props.yscale,
                        height: this.props.boxHeight
                    },
                    end: {
                        yscale: boxProps.yscale,
                        height: boxProps.height
                    }
                });
                CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));
            }
        });


        $('#brC_').draggable({
            start: function (event, ui)
            {
                var boxProps = _objectHash[_activeBoxId].props;

                this.props = {
                    mx: event.pageX,
                    my: event.pageY,
                    baseBoxHeight: boxProps.height / boxProps.yscale,
                    baseBoxWidth: boxProps.width / boxProps.xscale,
                    xscale: boxProps.xscale,
                    yscale: boxProps.yscale,
                    boxWidth: boxProps.width,
                    boxHeight: boxProps.height,
                    ratio: boxProps.width / boxProps.height
                };
            },
            drag: function (event, ui)
            {
                var boxProps = _objectHash[_activeBoxId].props,
                        dX = Math.abs(boxProps.rotation) == Math.PI / 2 ? event.pageY - this.props.my : (event.pageX - this.props.mx) / Math.cos(boxProps.rotation),
                        dY = boxProps.rotation == 0 || boxProps.rotation == Math.PI ? event.pageX - this.props.mx : (event.pageY - this.props.my) / Math.abs(Math.sin(boxProps.rotation)),
                        width = undefined,
                        height = undefined,
                        xscale = undefined,
                        yscale = undefined,
                        radius = undefined;

                if (this.props.ratio &gt;= 1) {
                    width = parseInt(this.props.boxWidth + dX);
                    height = parseInt(width / this.props.ratio);
                } else {
                    height = parseInt(this.props.boxHeight + dY);
                    width = parseInt(height * this.props.ratio);
                }

                xscale = width / this.props.baseBoxWidth;
                yscale = height / this.props.baseBoxHeight;

                if (width &gt;= 6 &amp;&amp; height &gt;= 6 &amp;&amp; ((boxProps.sprite &amp;&amp; yscale &lt;= 1 &amp;&amp; xscale &lt;= 1) || boxProps.html) &amp;&amp; !_isOffside(_activeBoxId, width, height, boxProps.rotation)) {
                    boxProps.width = width;
                    boxProps.height = height;

                    boxProps.xscale = xscale;
                    boxProps.yscale = yscale;

                    $('#' + _activeBoxId).css({
                        width: width,
                        height: height
                    });
                }

                radius = _getRadius(boxProps.width, boxProps.height);

                ui.position.left = boxProps.width / 2 + radius * Math.cos(Math.atan(boxProps.height / boxProps.width) + boxProps.rotation) - CONTROL_CENTER_OFFSET;
                ui.position.top = boxProps.height / 2 + radius * Math.sin(Math.atan(boxProps.height / boxProps.width) + boxProps.rotation) - CONTROL_CENTER_OFFSET;

                _redraw();
            },
            stop: function (event, ui)
            {
                var boxProps = _objectHash[_activeBoxId].props;

                _relocateControls(_activeBoxId, true);
                $(ui.helper[0]).siblings().show();

                _setUnReDoProps(_activeBoxId, {
                    start: {
                        yscale: this.props.yscale,
                        height: this.props.boxHeight,
                        xscale: this.props.xscale,
                        width: this.props.boxWidth
                    },
                    end: {
                        yscale: boxProps.yscale,
                        height: boxProps.height,
                        xscale: boxProps.xscale,
                        width: boxProps.width
                    }
                });
                CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));
            }
        });

        $('#urC_').draggable({
            start: function (event, ui)
            {
                var boxProps = _objectHash[_activeBoxId].props;

                this.props = {
                    x: boxProps.left + boxProps.width / 2,
                    y: boxProps.top + boxProps.height / 2,
                    angle: Math.atan2(boxProps.height / 2, boxProps.width / 2),
                    radius: _getRadius(boxProps.width, boxProps.height),
                    rotation: boxProps.rotation
                };
            },
            drag: function (event, ui)
            {
                var boxProps = _objectHash[_activeBoxId].props,
                        offset = $('#canvasBox').offset(),
                        angle = Math.atan2(event.pageY - offset.top - this.props.y, event.pageX - offset.left - this.props.x) + this.props.angle,
                        degs = angle * 180 / Math.PI;

                if (!_isOffside(_activeBoxId, boxProps.width, boxProps.height, angle)) {
                    boxProps.rotation = angle;

                    $('#' + _activeBoxId).css('-moz-transform', 'rotate(' + degs + 'deg)');
                    $('#' + _activeBoxId).css('-webkit-transform', 'rotate(' + degs + 'deg)');
                    $('#' + _activeBoxId).css('-o-transform', 'rotate(' + degs + 'deg)');
                    $('#' + _activeBoxId).css('-ms-transform', 'rotate(' + degs + 'deg)');
                }


                ui.position.left = boxProps.width / 2 + this.props.radius * Math.cos(Math.atan(boxProps.height / boxProps.width) - boxProps.rotation) - CONTROL_CENTER_OFFSET;
                ui.position.top = boxProps.height / 2 - this.props.radius * Math.sin(Math.atan(boxProps.height / boxProps.width) - boxProps.rotation) - CONTROL_CENTER_OFFSET;

                _redraw();
            },
            stop: function (event, ui)
            {
                var boxProps = _objectHash[_activeBoxId].props,
                        offset = $('#canvasBox').offset(),
                        angle = Math.atan2(event.pageY - offset.top - this.props.y, event.pageX - offset.left - this.props.x) + this.props.angle,
                        degs = angle * 180 / Math.PI,
                        isCorrected = false;

                if (Math.abs(degs) &lt;= 3) {
                    degs = 0;
                    boxProps.rotation = 0;
                    angle = degs * Math.PI / 180;
                    isCorrected = true;
                } else if (Math.abs(degs - 90) &lt;= 3) {
                    degs = 90;
                    boxProps.rotation = Math.PI / 2;
                    angle = degs * Math.PI / 180;
                    isCorrected = true;
                } else if (Math.abs(degs - 180) &lt;= 3) {
                    degs = 180;
                    boxProps.rotation = Math.PI;
                    angle = degs * Math.PI / 180;
                    isCorrected = true;
                } else if (Math.abs(degs + 90) &lt;= 3) {
                    degs = -90;
                    boxProps.rotation = -Math.PI / 2;
                    angle = degs * Math.PI / 180;
                    isCorrected = true;
                }

                if (isCorrected) {
                    $('#' + _activeBoxId).css('-moz-transform', 'rotate(' + degs + 'deg)');
                    $('#' + _activeBoxId).css('-webkit-transform', 'rotate(' + degs + 'deg)');
                    $('#' + _activeBoxId).css('-o-transform', 'rotate(' + degs + 'deg)');
                    $('#' + _activeBoxId).css('-ms-transform', 'rotate(' + degs + 'deg)');

                    _redraw();
                }

                _relocateControls(_activeBoxId, true);
                $(ui.helper[0]).siblings().show();

                _setUnReDoProps(_activeBoxId, {
                    start: {
                        rotation: this.props.rotation
                    },
                    end: {
                        rotation: boxProps.rotation
                    }
                });
                CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));
            }
        });
    }


    function _setProperty(boxId, property, value, isNotRedrawned)
    {
        isNotRedrawned = !!isNotRedrawned;
        if (_objectHash[boxId]) {
            _objectHash[boxId].props[property] = value;

            if (property == 'html' &amp;&amp; !isNotRedrawned &amp;&amp; value != undefined) {
                _updateTxtField(boxId);
            }

            if (!isNotRedrawned) {
                _redraw();
            }

            if (property == 'top') {
                $('#' + boxId).css({
                    top: value + 'px'
                });
            }

            if (property == 'left') {
                $('#' + boxId).css({
                    left: value + 'px'
                });
            }

            if (property == 'width') {
                $('#' + boxId).css({
                    width: value + 'px'
                });
            }

            if (property == 'height') {
                $('#' + boxId).css({
                    height: value + 'px'
                });
            }
        } else {
            //log('No box in hash ' + boxId);
        }
    }

    function _getProperty(boxId, property)
    {
        return _objectHash[boxId].props[property];
    }


    function _getProperties(boxId)
    {
        return _objectHash[boxId].props;
    }


    function _updateTxtField(boxId)
    {
        var boxProps = _objectHash[boxId].props,
                dimension = _measureChunk(boxProps),
                corners = undefined,
                boundingBox = {},
                ratio = undefined,
                offset = undefined;

        for (var key in dimension) {
            boxProps[key] = dimension[key];
        }

        _setBoxRect(boxProps.id);

        if (boxProps.rect.width &gt; _canvas.width()) {
            ratio = _canvas.width() / boxProps.rect.width;
        }

        if (boxProps.rect.height &gt; _canvas.height()) {
            if (ratio) {
                if (_canvas.height() / boxProps.rect.height &lt; ratio) {
                    ratio = _canvas.height() / boxProps.rect.height;
                }
            } else {
                ratio = _canvas.height() / boxProps.rect.height;
            }
        }

        if (ratio) {
            boxProps.xscale *= ratio;
            boxProps.yscale *= ratio;

            boxProps.width = Math.ceil(boxProps.width * boxProps.xscale);
            boxProps.height = Math.ceil(boxProps.height * boxProps.yscale);

            _setBoxRect(boxProps.id);

            _updateTxtField(boxId);
        } else {
            //			_tempBox(boundingBox.left, boundingBox.top, boundingBox.width, boundingBox.height);
            /*  RENDEROWANIE OKIENKA
             if (boxProps.rect.left &lt; 0) {
             boxProps.left -= boxProps.rect.left;
             }
             
             if (boxProps.rect.left + boxProps.rect.width &gt; _canvas.width()) {
             offset = boxProps.rect.left + boxProps.rect.width - _canvas.width();
             boxProps.left -= offset;
             }
             
             if (boxProps.rect.top &lt; 0) {
             boxProps.top -= boxProps.rect.top;
             }
             
             if (boxProps.rect.top + boxProps.rect.height &gt; _canvas.height()) {
             offset = boxProps.rect.top + boxProps.rect.height - _canvas.height();
             boxProps.top -= offset;
             }*/

            $('#' + boxId).css({
                width: boxProps.width,
                height: boxProps.height,
                left: boxProps.left,
                top: boxProps.top
            });

            $('#controls').css({
                'left': boxProps.left,
                'top': boxProps.top
            });

            _relocateControls(boxId, true);
            CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));
        }
    }


    function _measureChunk(boxProps)
    {
        var width = [],
                height = [],
                offset = [],
                txtOffset = [],
                localWidth = 0,
                localHeight = 0,
                localOffset = 0,
                maxWidth = 0,
                totalHeight = 0,
                fontStyle = '',
                fontWeight = '',
                htmlChunk = undefined,
                localFontSize = 0;

        for (var i = 0; i &lt; boxProps.htmlChunk.length; i++) {
            if (boxProps.htmlChunk[i].tag == 'br') {
                if (localHeight == 0) {
                    localHeight = DEFAULT_TXT_HEIGHT;
                    txtOffset.push(0);
                } else {
                    txtOffset.push(_getTextOffset(htmlChunk));
                }

                width.push(localWidth);
                height.push(localHeight);

                localWidth = 0;
                localHeight = 0;
                localFontSize = 0;
            } else {
                _context.save();

                fontStyle = boxProps.htmlChunk[i].fontStyle ? boxProps.htmlChunk[i].fontStyle + ' ' : '';
                fontWeight = boxProps.htmlChunk[i].fontWeight ? boxProps.htmlChunk[i].fontWeight + ' ' : '';

                _context.font = fontStyle + fontWeight + boxProps.htmlChunk[i].fontSize + ' ' + boxProps.htmlChunk[i].font;

                localWidth += _context.measureText(boxProps.htmlChunk[i].txt).width;

                if (parseInt(boxProps.htmlChunk[i].fontSize) &gt; localHeight) {
                    localHeight = parseInt(boxProps.htmlChunk[i].fontSize);
                }

                _context.restore();

                if (parseInt(boxProps.htmlChunk[i].fontSize) &gt; localFontSize) {
                    localFontSize = parseInt(boxProps.htmlChunk[i].fontSize);
                    htmlChunk = boxProps.htmlChunk[i];
                }
            }
        }

        width.push(localWidth);
        height.push(localHeight);
        txtOffset.push(_getTextOffset(htmlChunk));

        maxWidth = Math.max.apply(undefined, width);

        for (i = 0; i &lt; height.length; i++) {
            totalHeight += height[i];
        }

        offset.push(totalHeight);

        if (height.length &gt; 1) {
            localOffset = totalHeight;

            for (i = height.length - 1; i &gt; 0; i--) {
                if (i == height.length - 1) {
                    offset[0] -= txtOffset[i];
                }

                localOffset -= height[i];

                offset.unshift(localOffset - txtOffset[i - 1]);
            }
        } else {
            offset[0] -= txtOffset[0];
        }

        //log(offset);
        return {
            lineWidth: width,
            lineOffset: offset,
            width: (maxWidth + 1) * boxProps.xscale,
            height: totalHeight * boxProps.yscale
        };
    }


    function _centerBox()
    {
        var boxProps = undefined,
                initLeft = undefined,
                left = 0,
                cbPos = $('#canvasBox').position(),
                distance = 0,
                startPositions = {},
                endPositions = {},
                isRepositioned = false,
                id = undefined;

        if (_activeBoxId) {
            for (var i = 0; i &lt; _sorting.length; i++) {
                id = 'v' + _view + 'b' + _sorting[i];

                startPositions[id] = {
                    left: _objectHash[id].props.left,
                    top: _objectHash[id].props.top,
                    rect: {
                        top: _objectHash[id].props.rect.top,
                        left: _objectHash[id].props.rect.left,
                        width: _objectHash[id].props.rect.width,
                        height: _objectHash[id].props.rect.height
                    }
                };
            }


            boxProps = _objectHash[_activeBoxId].props;
            initLeft = boxProps.left;

            left = (($('#workspaceBox').width() - boxProps.width) / 2);

            if (left &lt; cbPos.left) {
                distance = left - cbPos.left;
                boxProps.left = 0;
            } else if (left + boxProps.width &gt; cbPos.left + $('#canvasBox').width()) {
                distance = (left + boxProps.width) - (cbPos.left + $('#canvasBox').width());
                boxProps.left = $('#canvasBox').width() - boxProps.width;
            } else {
                boxProps.left = left - cbPos.left;
            }

            if (distance) {
                $('#canvasBox').css('left', cbPos.left + distance);

                _viewHash['view_' + _view]['position'].left = cbPos.left + distance;

                if (!_productCanvasPosition[_productTag]) {
                    _productCanvasPosition[_productTag] = {};
                }

                _productCanvasPosition[_productTag]['view_' + _view] = {};

                _productCanvasPosition[_productTag]['view_' + _view].left = _viewHash['view_' + _view]['position'].left;
                _productCanvasPosition[_productTag]['view_' + _view].top = _viewHash['view_' + _view]['position'].top;

                _setUnReDoProps(boxProps.id, {
                    start: {
                        left: initLeft
                    },
                    end: {
                        left: boxProps.left
                    }
                }, {
                    start: {
                        left: cbPos.left
                    },
                    end: {
                        left: cbPos.left + distance
                    }
                });


                for (var i = 0; i &lt; _sorting.length; i++) {
                    id = 'v' + _view + 'b' + _sorting[i];

                    if (id != _activeBoxId) {
                        if (distance &gt; _objectHash[id].props.left) {
                            _objectHash[id].props.left = 0;
                            isRepositioned = true;
                        } else if ((_objectHash[id].props.left + _objectHash[id].props.width) - $('#canvasBox').width() &gt; distance) {
                            _objectHash[id].props.left = $('#canvasBox').width() - _objectHash[id].props.width;
                            isRepositioned = true;
                        }

                        _setBoxRect(id);

                        endPositions[id] = {
                            left: _objectHash[id].props.left,
                            top: _objectHash[id].props.top,
                            rect: _objectHash[id].props.rect
                        };
                    }
                }

                if (isRepositioned) {
                    CupSell.Generator.UnReDo.setPositions({
                        start: startPositions,
                        end: endPositions
                    });
                }

            } else {
                _setUnReDoProps(boxProps.id, {
                    start: {
                        left: initLeft
                    },
                    end: {
                        left: boxProps.left
                    }
                });
            }

            $('#' + _activeBoxId).css({
                left: boxProps.left + 'px'
            });

            $('#controls').css({
                left: boxProps.left,
                top: boxProps.top
            });

            _relocateControls(_activeBoxId, true);
            CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));
            _redraw();
        }
    }


    function _setUnReDoProps(boxId, props, position)
    {
        var unReDoProps = {};
        unReDoProps.props = props;

        unReDoProps.boxId = boxId;
        unReDoProps.view = 'view_' + _view;

        unReDoProps.position = position;

        CupSell.Generator.UnReDo.setProps(unReDoProps);
    }

    function _redraw()
    {
        var boxProps = undefined,
                xOffset = undefined,
                yOffset = undefined,
                fontStyle = '',
                fontWeight = '',
                width = 0,
                chunkWidth = 0,
                multi = undefined,
                lineXOffset = undefined,
                lineYOffset = undefined;

        _context.clearRect(0, 0, _canvas.width(), _canvas.height());
        //log(_sorting);
        for (var j = 0; j &lt; _sorting.length; j++) {
            _context.save();
            boxProps = _objectHash['v' + _view + 'b' + _sorting[j]].props;

            xOffset = boxProps.width / 2;
            yOffset = boxProps.height / 2;

            _context.translate(boxProps.left + xOffset, boxProps.top + yOffset);
            _context.rotate(boxProps.rotation);
            _context.scale(boxProps.xscale, boxProps.yscale);

            _context.textBaseline = 'alphabetic';

            if (boxProps.html) {
                width = 0;
                multi = 0;
                lineXOffset = 0;
                lineYOffset = boxProps.lineOffset[0];

                if (boxProps.align == 'right') {
                    lineXOffset = boxProps.width - boxProps.lineWidth[0] * boxProps.xscale;
                } else if (boxProps.align == 'center') {
                    lineXOffset = (boxProps.width - boxProps.lineWidth[0] * boxProps.xscale) / 2;
                }
                for (var i = 0; i &lt; boxProps.htmlChunk.length; i++) {
                    if (boxProps.htmlChunk[i].tag == 'br') {
                        multi++;
                        width = 0;

                        if (boxProps.align == 'right') {
                            lineXOffset = boxProps.width - boxProps.lineWidth[multi] * boxProps.xscale;
                        } else if (boxProps.align == 'center') {
                            lineXOffset = (boxProps.width - boxProps.lineWidth[multi] * boxProps.xscale) / 2;
                        }

                        lineYOffset = boxProps.lineOffset[multi];

                    } else {
                        _context.save();

                        fontStyle = boxProps.htmlChunk[i].fontStyle ? boxProps.htmlChunk[i].fontStyle + ' ' : '';
                        fontWeight = boxProps.htmlChunk[i].fontWeight ? boxProps.htmlChunk[i].fontWeight + ' ' : '';

                        _context.font = fontStyle + fontWeight + boxProps.htmlChunk[i].fontSize + ' ' + boxProps.htmlChunk[i].font;
                        _context.fillStyle = boxProps.htmlChunk[i].color;

                        chunkWidth = _context.measureText(boxProps.htmlChunk[i].txt).width * boxProps.xscale;
                        _context.fillText(boxProps.htmlChunk[i].txt, (lineXOffset + width - xOffset) / boxProps.xscale, lineYOffset - (yOffset / boxProps.yscale));
                        width += chunkWidth;

                        _context.restore();
                    }
                }

            } else if (boxProps.sprite) {
                try {
                    _context.drawImage(_image[boxProps.id], -xOffset / boxProps.xscale, -yOffset / boxProps.yscale, boxProps.width / boxProps.xscale, boxProps.height / boxProps.yscale);
                } catch (err) {
                    var img = new Image();
                    img.src = boxProps.sprite;

                    img.onload = function ()
                    {
                        _context.drawImage(img, -xOffset / boxProps.xscale, -yOffset / boxProps.yscale, boxProps.width / boxProps.xscale, boxProps.height / boxProps.yscale);
                    }
                }
            }

            _context.restore();
        }
    }

    function _getRadius(width, height)
    {
        return Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2));
    }


    function _getPrints()
    {
        var prints = [];

        for (var viewId in _viewHash) {
            if (_viewHash[viewId]['sorting'].length &gt; 0) {
                prints.push(viewId.replace('view_', ''));
            }
        }

        return prints;
    }


    function _isCurrentViewEmpty()
    {
        if (_view) {
            return _viewHash['view_' + _view]['sorting'].length &gt; 0 ? false : true;
        } else {
            return undefined;
        }
    }


    function _editItem()
    {
        if (_getPrints().length == 0) {
            CupSell.Generator.messageDialog(
                    translation.noPrint, translation.createOwnPrint
                    );

            return;
        }
        _generate(_editShopItem, [true]);
    }

    //TODO: scalic poniÅ¼sze 2 metody, a moÅ¼e i 3
    function _addToBasket()
    {
        if (_getPrints().length == 0) {
            CupSell.Generator.messageDialog(
                    translation.noPrint, translation.createOwnPrint
                    );

            return;
        }
        if (!CupSell.Generator.Basket.getSelectedSize()) {
            CupSell.Generator.Basket.sizeOptionDialog(function () {
                CupSell.Generator.Basket.shoppingOptionDialog();
            });
        } else {
            CupSell.Generator.Basket.shoppingOptionDialog();
        }
    }


    function _buyNow()
    {
        if (_getPrints().length == 0) {
            CupSell.Generator.messageDialog(
                    translation.noPrint, translation.createOwnPrint
                    );

            return;
        }

        if (!CupSell.Generator.Basket.getSelectedSize()) {
            CupSell.Generator.Basket.sizeOptionDialog(function () {
                _generate(_generateBasketItem, [true]);
            });
        } else {
            _generate(_generateBasketItem, [true]);
        }
    }

    function _addToShop() {
        if (_getPrints().length == 0) {
            CupSell.Generator.messageDialog(
                    translation.noPrint, translation.createOwnPrint
                    );

            return;
        }

        if (_colorLength &gt; 1) {
            // choose color
            var color_box = $('#colorOptionsBox');
            color_box.modal({
                onOpen: function (dialog) {
                    dialog.overlay.fadeIn(150, function () {
                        dialog.container.show();
                        dialog.data.show();
                        _resetColorOptions();
                        CupSell.Generator.ProductManager.addColorSelectorListeners();
                    });
                },
                escClose: true,
                overlayClose: true
            });

            color_box.find('.button.ok').bind('click', function () {
                $.modal.close();

                if ($('#color_opts_versions').children().length == _getExceptColors().length) {
                    CupSell.Generator.messageDialog(
                            translation.noColor, translation.choosColor
                            );
                    return;
                }

                _generate(_generateShopItem, []);
            });
        } else
            _generate(_generateShopItem, []);
    }


    function _generate(callback, args)
    {
        var view = {},
                box = undefined,
                props = undefined,
                sorting = undefined,
                boxProps = undefined,
                canvas = undefined,
                context = undefined,
                fontStyle = '',
                fontWeight = '',
                widths = [],
                width = 0,
                height = 0,
                multi = undefined,
                lineXOffset = undefined,
                lineYOffset = undefined;

        if (!_isBusy) {
            $('#wait').show('slow');
            _isBusy = true;

            for (var viewId in _viewHash) {

                sorting = _viewHash[viewId]['sorting'];

                if (sorting.length &gt; 0)
                {
                    box = {};
                    view[viewId] = box;

                    box['offset'] = {
                        top: _viewHash[viewId]['position'].top / _viewHash[viewId]['ratio'],
                        left: _viewHash[viewId]['position'].left / _viewHash[viewId]['ratio']
                    };

                    for (var j = 0; j &lt; sorting.length; j++) {
                        props = {};
                        boxProps = _viewHash[viewId]['box']['v' + viewId.replace('view_', '') + 'b' + sorting[j]].props;

                        props.id = boxProps.id;
                        props.rect = boxProps.rect;

                        if (boxProps.sprite) {
                            props.xscale = boxProps.xscale * (boxProps.imgRatio / _viewHash[viewId]['ratio']);
                            props.yscale = boxProps.yscale * (boxProps.imgRatio / _viewHash[viewId]['ratio']);
                        } else {
                            props.xscale = boxProps.xscale;
                            props.yscale = boxProps.yscale;
                        }

                        props.rotation = boxProps.rotation * 180 / Math.PI;

                        if (boxProps.html) {

                            canvas = $(document.createElement('canvas'));

                            canvas.attr({
                                width: boxProps.width + 'px',
                                height: boxProps.height + 'px'
                            });

                            context = canvas.get(0).getContext('2d');
                            context.textBaseline = 'alphabetic';

                            //jeszcze raz przeanalizowaÄ‡, czy to naprawde jest potrzebne
                            width = 0;

                            for (var i = 0; i &lt; boxProps.htmlChunk.length; i++) {

                                if (boxProps.htmlChunk[i].tag == 'br') {
                                    widths.push(width);
                                    width = 0;
                                } else {
                                    context.save();

                                    fontStyle = boxProps.htmlChunk[i].fontStyle ? boxProps.htmlChunk[i].fontStyle + ' ' : '';
                                    fontWeight = boxProps.htmlChunk[i].fontWeight ? boxProps.htmlChunk[i].fontWeight + ' ' : '';

                                    context.font = fontStyle + fontWeight + boxProps.htmlChunk[i].fontSize + ' ' + boxProps.htmlChunk[i].font;
                                    context.fillStyle = boxProps.htmlChunk[i].color;

                                    width += context.measureText(boxProps.htmlChunk[i].txt).width * boxProps.xscale;

                                    context.restore();
                                }
                            }

                            if (widths.length &gt; 0) {
                                widths.push(width);
                                width = Math.max.apply(undefined, widths);
                            }

                            canvas = $(document.createElement('canvas'));
                            //1.1 - fix for cutting off 
                            //1.25 - fix for cutting off bottom part
                            canvas.attr({
                                width: width * 1.05 / _viewHash[viewId]['ratio'] + 'px',
                                height: 1.25 * boxProps.height / _viewHash[viewId]['ratio'] + 'px'
                            });

                            context = canvas.get(0).getContext('2d');

                            context.textBaseline = 'alphabetic';

                            width = 0;

                            multi = 0;
                            lineXOffset = 0;
                            lineYOffset = boxProps.lineOffset[0];

                            if (boxProps.align == 'right') {
                                lineXOffset = boxProps.width - boxProps.lineWidth[0] * boxProps.xscale;
                            } else if (boxProps.align == 'center') {
                                lineXOffset = (boxProps.width - boxProps.lineWidth[0] * boxProps.xscale) / 2;
                            }

                            for (i = 0; i &lt; boxProps.htmlChunk.length; i++) {

                                if (boxProps.htmlChunk[i].tag == 'br') {
                                    multi++;
                                    width = 0;

                                    if (boxProps.align == 'right') {
                                        lineXOffset = boxProps.width - boxProps.lineWidth[multi] * boxProps.xscale;
                                    } else if (boxProps.align == 'center') {
                                        lineXOffset = (boxProps.width - boxProps.lineWidth[multi] * boxProps.xscale) / 2;
                                    }

                                    lineYOffset = boxProps.lineOffset[multi];

                                } else {
                                    context.save();

                                    context.scale(boxProps.xscale / _viewHash[viewId]['ratio'], boxProps.yscale / _viewHash[viewId]['ratio']);

                                    fontStyle = boxProps.htmlChunk[i].fontStyle ? boxProps.htmlChunk[i].fontStyle + ' ' : '';
                                    fontWeight = boxProps.htmlChunk[i].fontWeight ? boxProps.htmlChunk[i].fontWeight + ' ' : '';

                                    context.font = fontStyle + fontWeight + boxProps.htmlChunk[i].fontSize + ' ' + boxProps.htmlChunk[i].font;
                                    context.fillStyle = boxProps.htmlChunk[i].color;

                                    context.fillText(boxProps.htmlChunk[i].txt, (lineXOffset / boxProps.xscale + width), lineYOffset);
                                    width += context.measureText(boxProps.htmlChunk[i].txt).width;

                                    context.restore();
                                }
                            }

                            props.imageData = canvas[0].toDataURL();

                            context = undefined;
                            canvas = undefined;
                        } else if (boxProps.userImage) {
                            props.userImage = boxProps.userImage;
                        }
                        box[boxProps.id] = props;
                    }
                }
            }

            var generatorId = $('#id_generator').val();

            if (!generatorId) {
                generatorId = null;
            }

            var group = $('#group').val();

            if (!group) {
                group = null;
            }

            var act = 'create';
            var shopItemId = $('#shop-item-edit-id').val();
            var generatorDesignId = $('#generator-design-edit-id').val();

            if (shopItemId) {
                act = 'edit';
            } else {
                shopItemId = null;
                generatorDesignId = null;
            }

            $.ajax({
                url: '/generator-ajax/index',
                type: 'post',
                data: {
                    mod: 'creator',
                    act: act,
                    uid: CupSell.Generator.StorageManager.get('uid'),
                    group: group,
                    productId: _productId,
                    printData: $.toJSON(view),
                    generatorId: generatorId,
                    colorOpts: _getColorOption(),
                    exceptColors: $.toJSON(_getExceptColors()),
                    shopItemId: shopItemId,
                    generatorDesignId: generatorDesignId
                },
                dataType: 'json',
                error: function ()
                {
                    log('fail');
                },
                success: function (response)
                {
                    if (response.result == 'ok') {
                        args.unshift(response.id);
                        callback.apply(undefined, args);
                    } else {
                        CupSell.Generator.errorDialog(translation.sendFileFailure, translation.pleaseTryLater);
                        $('#wait').hide('slow');
                        _isBusy = false;
                    }
                }
            });
        }
    }

    function _resetColorOptions() {
        CupSell.Generator.Canvas._colorOption = 'only';
        CupSell.Generator.Canvas._exceptColors = [];
    }

    function _getColorOption() {
        return CupSell.Generator.Canvas._colorOption;
    }
    function _getExceptColors() {
        return CupSell.Generator.Canvas._exceptColors;
    }

    // buy now action callback
    function _generateBasketItem(generatorDesignId, isFinished) {

        var generatorId = $('#id_generator').val();
        var generatorInIframe = $('#generatorInIframe').val();

        generatorId = (generatorId) ? generatorId : null;

        $.ajax({
            url: '/cart/ajax-generator-add?sec_code=' + zend_vars.sec_code,
            type: 'post',
            data: {
                generator_design_id: generatorDesignId,
                size: CupSell.Generator.Basket.getSelectedSize(),
                sex: CupSell.Generator.Basket.getSelectedSex(), //GeneratorTeeroulette
                quantity: CupSell.Generator.Basket.getQuantity(),
                generator_id: generatorId,
                external_domain: zend_vars.external_domain
            },
            dataType: 'json',
            success: function (response)
            {
                if (isFinished &amp;&amp; response.status == 'success') {
                    if (generatorInIframe == 1) {
                        window.location = '/minikoszyk';
                    } else {
                        window.location = '/koszyk';
                    }
                } else {
                    $('#wait').hide('slow');
                    CupSell.Generator.redrawBasketItems(response[0].basket, response[0].dropdown);
                    _isBusy = false;
                }
            }
        });
    }

    function _editShopItem(generatorDesignId)
    {
        $.ajax({
            url: '/generator-ajax/index',
            type: 'post',
            data: {
                mod: 'creator',
                act: 'shopList',
                generator_design_id: generatorDesignId
            },
            dataType: 'json',
            error: function ()
            {
                log('fail');
            },
            success: function (response)
            {
                var pop = undefined,
                        html = '';

                $('#wait').hide('slow');
                _isBusy = false;

                window.location = '/konto/sklep/asortyment-edytuj/' + generatorDesignId;
            }
        });
    }


    function _generateShopItem(generatorDesignId)
    {
        $.ajax({
            url: '/generator-ajax/index',
            type: 'post',
            data: {
                mod: 'creator',
                act: 'shopList',
                generator_design_id: generatorDesignId
            },
            dataType: 'json',
            error: function ()
            {
                log('fail');
            },
            success: function (response)
            {
                var pop = undefined,
                        html = '';

                $('#wait').hide('slow');
                _isBusy = false;

                switch (response.length) {
                    case 0:
                        window.location = '/konto/sklepy/nowy';
                        break;
                    case 1:
                        window.location = '/konto/sklep/asortyment-dodaj/sklep/' + response[0].id + '/generator_design_id/' + generatorDesignId;
                        break;
                    default:
                    {
                        // show shop list
                        html = '';
                        for (var i = 0; i &lt; response.length; i++) {
                            html += '&lt;li&gt;&lt;input type="radio" name="shop_id" value="'
                                    + response[i].id + '"' + (i == 0 ? " checked" : "") + ' id="_shr' + i + '"&gt; &lt;label for="_shr' + i + '"&gt;' + response[i].name + '&lt;/label&gt;&lt;/li&gt;';
                        }
                        $('ul#shop_list').html(html);
                        $('#generator_design_id').val(generatorDesignId);
                        $('#shopListBox .button.ok ').off('click', '**').on('click', function (event) {
                            $('#shopList').submit();
                        });

                        $('#shopListBox').modal({
                            onOpen: function (dialog) {
                                dialog.overlay.fadeIn(150, function () {
                                    dialog.container.show();
                                    dialog.data.show();
                                });
                            },
                            escClose: true,
                            overlayClose: true
                        });
                    }
                }
            }
        });
    }

    function _setCanvasPosition(position)
    {
        $('#canvasBox').css({
            left: position.left + 'px',
            top: position.top + 'px'
        });

        _viewHash['view_' + _view]['position'].left = position.left;
        _viewHash['view_' + _view]['position'].top = position.top;

        //to jest bez sensu te obiekty powinny istniec
        if (!_productCanvasPosition[_productTag]) {
            _productCanvasPosition[_productTag] = {};
        }

        _productCanvasPosition[_productTag]['view_' + _view] = {};

        _productCanvasPosition[_productTag]['view_' + _view].left = position.left;
        _productCanvasPosition[_productTag]['view_' + _view].top = position.top;
    }


    function _storeData()
    {
        CupSell.Generator.StorageManager.store('csdata', $.toJSON(_viewHash));
    }

    // for debug only
    function _tempBox(left, top, width, height)
    {
        var box = $('#temp');

        if (!box[0]) {
            box = $(document.createElement('div')).attr('id', 'temp').appendTo($('#canvasBox'));
        }

        box.css({
            position: 'absolute',
            border: '1px solid brown',
            top: top,
            left: left,
            width: width,
            height: height
        });
    }

    // for debug only
    function _rectBox(left, top, width, height)
    {
        var box = $('#rect');

        if (!box[0]) {
            box = $(document.createElement('div')).attr('id', 'rect').appendTo($('#canvasBox'));
        }

        box.css({
            position: 'absolute',
            border: '1px solid green',
            top: top,
            left: left,
            width: width,
            height: height
        });
    }

    return {
        addImg: _addImg,
        createTxtBox: _createTxtBox,
        resetTxt: _resetTxt,
        removeBox: _removeBox,
        deleteBox: _deleteBox,
        getProperty: _getProperty,
        getProperties: _getProperties,
        getPrints: _getPrints,
        setProperty: _setProperty,
        setCanvasProps: _setCanvasProps,
        setColorLength: _setColorLength,
        setUnReDoProps: _setUnReDoProps,
        getExceptColors: _getExceptColors,
        getColorOption: _getColorOption,
        resetColorOptions: _resetColorOptions,
        redraw: _redraw,
        deactivateBox: _deactivateBox,
        adjustBox: _adjustBox,
        generate: _generate,
        generateBasketItem: _generateBasketItem,
        isCurrentViewEmpty: _isCurrentViewEmpty,
        restoreBox: _restoreBox,
        setCanvasPosition: _setCanvasPosition,
        storeData: _storeData,
        getDesignBoundingBox: _getDesignBoundingBox,
        getActiveBoxId: function ()
        {
            return _activeBoxId;
        },
        getCurrentView: function ()
        {
            return _view;
        }
    };
})();


function BoxProps(id)
{
    this.props = {};

    this.props.id = id;
    this.props.index = undefined;
    this.props.left = undefined;
    this.props.top = undefined;
    this.props.width = undefined;
    this.props.height = undefined;
    this.props.xscale = 1;
    this.props.yscale = 1;
    this.props.rect = undefined;
    this.props.rotation = 0;
    this.props.align = 'left';
    this.props.initalign = 'left';
    this.props.lineWidth = undefined;
    this.props.lineOffset = undefined;
    this.props.html = undefined;
    this.props.htmlChunk = undefined;
    this.props.sprite = undefined;
    this.props.imgRatio = undefined;
    this.props.userImage = undefined;
}


CupSell.Generator.Files = (function ()
{
    $('#addImg').click(function ()
    {
        CupSell.Generator.Canvas.addImg();
    });
})();


CupSell.Generator.Views = (function ()
{
    var _fontColor = undefined;


    function _setView(imgPath)
    {
        var img = new Image();

        img.src = imgPath;
        img.onload = function ()
        {
            $('#productView').html('&lt;img src="' + img.src + '" alt=""&gt;');
        };
    }

    function _setMask(imgPath)
    {
        if (!imgPath) {
            return $('#productMask').css('background-image', '');
        }
        var img = new Image();

        img.src = imgPath;
        img.onload = function ()
        {
            $('#productMask').css('background-image', 'url(' + img.src + ')');
        };
    }

    function _clearView()
    {
        $('#productView').html('');
    }

    function _setFontColor(color)
    {
        _fontColor = /#[0-9a-z]{6}/i.test(color) ? color : undefined;
    }


    function _getFontColor()
    {
        return _fontColor;
    }

    return {
        setView: _setView,
        clearView: _clearView,
        getFontColor: _getFontColor,
        setFontColor: _setFontColor,
        setMask: _setMask
    };
})();


CupSell.Generator.Tabs = (function ()
{
    $(document).ready(function ()
    {
        $('#boxTabs').click(function (event)
        {
            if (event.target.tagName.toUpperCase() == 'LI') {
                _togglePanel(event.target.id);
            }
        });
    });


    function _togglePanel(tabId, isNotInitialized)
    {
        var activeBoxId = CupSell.Generator.Canvas.getActiveBoxId();

        isNotInitialized = !!isNotInitialized;
        switch (tabId) {
            case 'typeTab':
                if (!$('#typeBox').is(':visible')) {
                    $('#editorTab').removeClass('selected');
                    $('#editorBox').hide();
                    $('#imageTab').removeClass('selected');
                    $('#imageBox').hide();
                    $('#typeTab').addClass('selected');
                    $('#typeBox').show();

                    if (activeBoxId &amp;&amp; $('#' + activeBoxId).hasClass('txtBox')) {
                        CupSell.Generator.Canvas.deactivateBox($('#' + activeBoxId));
                    }
                }
                break;

            case 'imageTab':
                if (!$('#imageBox').is(':visible')) {
                    $('#typeTab').removeClass('selected');
                    $('#typeBox').hide();
                    $('#editorTab').removeClass('selected');
                    $('#editorBox').hide();
                    $('#imageTab').addClass('selected');
                    $('#imageBox').show();

                    if (activeBoxId &amp;&amp; $('#' + activeBoxId).hasClass('txtBox')) {
                        CupSell.Generator.Canvas.deactivateBox($('#' + activeBoxId));
                    }
                }
                break;

            case 'editorTab':
                if (!$('#editorBox').is(':visible')) {
                    $('#typeTab').removeClass('selected');
                    $('#typeBox').hide();
                    $('#imageTab').removeClass('selected');
                    $('#imageBox').hide();
                    $('#editorTab').addClass('selected');
                    $('#editorBox').show();

                    if (activeBoxId &amp;&amp; $('#' + activeBoxId).hasClass('imgBox')) {
                        CupSell.Generator.Canvas.deactivateBox($('#' + activeBoxId));
                    }

                    if (!isNotInitialized) {

                        var txtColor = undefined;

                        if (CupSell.Generator.Views.getFontColor()) {
                            txtColor = CupSell.Generator.Views.getFontColor();
                        } else {
                            txtColor = CupSell.Generator.Editor.getBackgroundColor() == '#000000' ? '#FFFFFF' : '#000000';
                        }
                        CupSell.Generator.Editor.setHTML('&lt;span style="font-family: ' + $('#font')[0].value + '; font-size: ' + $('#size')[0].value + 'px; color: ' + txtColor + ';"&gt;' + translation.addText + '&lt;/span&gt;');
                    }
                }
                break;
        }
    }

    return {
        togglePanel: _togglePanel
    };

})();


var BitmapText = (function ()
{
    var _canvas = document.createElement("canvas"),
            _ctx = _canvas.getContext("2d"),
            _control = document.createElement("span");

    function _getBitmapBounds(props)
    {
        var text = props.text,
                fontSize = props.fontSize,
                fontFamily = props.fontFamily,
                bboxHeight = props.bboxHeight,
                canvasHeight = bboxHeight * 2,
                flip = false,
                drawBaseline = false;

        // setting up the canvas
        _ctx.save();
        _ctx.font = fontSize + "px " + fontFamily;
        var textWidth = _ctx.measureText(text).width;
        // Offsets keep the font in-screen, where measureText().width 
        // doesn't quite do it in some cases. For instance "j", or the 
        // letter "f" in the font "Zapfino".
        var offsetx = fontSize * 2;
        var offsety = fontSize * 2;
        var cwidth = _ctx.canvas.width = Math.round(textWidth + offsetx * 2);
        var cheight = _ctx.canvas.height = canvasHeight ? canvasHeight : Math.round(offsety * 2);
        if (typeof (baseline) == "string") {
            offsety = 0; // using &lt;canvas&gt; baseline
            _ctx.textBaseline = baseline;
        }
        // ctx.font has to be called twice because resetting the size resets the state
        if (flip)
            _ctx.scale(1, -1);
        _ctx.font = fontSize + "px " + fontFamily
        _ctx.fillText(text, offsetx, (typeof (bboxHeight) == "number" ? bboxHeight : offsety));
        // drawing baseline
        if (drawBaseline) {
            _ctx.fillRect(0, canvasHeight / 2, _ctx.canvas.width, 1);
        }
        // grabbing image data
        var imageData = _ctx.getImageData(0, 0, cwidth, cheight);
        var data = imageData.data;
        // calculating top

        // calculating bottom
        var bottom = 0;
        var pos = data.length;
        while (pos &gt; 0) {
            if (data[pos + 3]) {
                pos -= pos % (cwidth * 4); // back to beginning of the line
                bottom = (pos / 4) / cwidth;
                bottom -= offsety - fontSize;
                pos = 0; // exit loop
            }
            pos -= 4;
        }


        // restoring state
        _ctx.restore();
        // returning raw-metrics

        var off = bottom &gt;= 8 ? Math.ceil(bottom / 2) + 2 : Math.ceil(bottom / 2) + 1;

        return off;
    }
    ;

    return {
        getBitmapBounds: _getBitmapBounds
    };
})();

;/**
*
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
*
**/

AIM = {

	frame : function(c) {

		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '&lt;iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"&gt;&lt;/iframe&gt;';
		document.body.appendChild(d);

		var i = document.getElementById(n);
		if (c &amp;&amp; typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}

		return n;
	},

	form : function(f, name) {
		f.setAttribute('target', name);
	},

	submit : function(f, c) {
		AIM.form(f, AIM.frame(c));
		if (c &amp;&amp; typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},

	loaded : function(id) {
		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
			return;
		}

		if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML);
		}
	}

};CupSell.Generator.FileManager = (function ()
{
    var _imgData = undefined,
            _uploadInProgress = false,
            _carousel = null;

    $(document).ready(function () {

        $('#upButton').on('click', function () {
            if (!_uploadInProgress) {
                $('#upFile').val('');
                $('#upFile').click();
            }
        });

        if (!$.browser.msie) {
            $('#userImages').on('click', function () {
                if (!_uploadInProgress) {
                    $('#upFile').val('');
                    $('#upFile').click();
                }
            });
        }

        $('#upFile').change(function () {

            if ($('#generatorInIframe').val() == 1) {
                var position = [400];
            } else {
                var position = false;
            }

            $('#copyrightConfirm').modal({
                onOpen: function (dialog) {
                    dialog.overlay.fadeIn(150, function () {
                        dialog.container.show();
                        dialog.data.show();
                    });
                },
                escClose: true,
                overlayClose: true,
                position: position
            });
        });

        $('#copyrightConfirm input[type=checkbox]').on('click', function (event) {
            if ($(event.currentTarget).attr('checked')) {
                $('#copyrightConfirm .button.ok').removeClass('disabled');
            } else {
                $('#copyrightConfirm .button.ok').addClass('disabled');
            }
        });

        $('#copyrightConfirm .button.ok').on('click', function (event) {
            if ($('#copyrightConfirm input[type=checkbox]').attr('checked') == 'checked') {
                $('#GeneratorUploader').submit();
                $.modal.close();
            }
        });

        $('#GeneratorUploader').submit(function (event) {
            if (!_uploadInProgress) {
                AIM.submit($('#GeneratorUploader')[0], {'onStart': _startUpload, 'onComplete': _completeUpload});
            }
        });

        if (CupSell.Generator.StorageManager.get('csfile')) {
            _imgData = $.evalJSON(CupSell.Generator.StorageManager.get('csfile'));
            _redrawUserImages();

            // Add image if from external source
            if (CupSell.Generator.StorageManager.get('ext') &amp;&amp; _imgData.length == 1) {
                var imgData = _imgData[0];

                imgData.offset = undefined;
                CupSell.Generator.Canvas.addImg(imgData);
                CupSell.Generator.StorageManager.remove('ext')
            }
        } else {
            _imgData = [];
        }
    });

    function getTranslation(key)
    {
        return zend_vars['generator_translations'] &amp;&amp; zend_vars['generator_translations'][key] ? zend_vars['generator_translations'][key] : key;
    }

    /**
     * Insert image to list
     */
    function _carouselItemLoadCallback(carousel, state)
    {
        for (var i = 0; i &lt; _imgData.length; i++) {
            var elementHtml = '&lt;li id="ui_' + i + '"&gt;&lt;div data-id="ui_' + i +
                '" style="background-image: url(\'' + _imgData[i].thumbnail + '\')"&gt;&lt;span class="gallery-delete"&gt;'
                +getTranslation('usuÅ„')
                +'&lt;/span&gt;&lt;/div&gt;&lt;span class="gallery-add"&gt;'
                +getTranslation('dodaj na produkt')
                +'&lt;/span&gt;';
            var element = $(elementHtml);
            if (_imgData.length &gt; 8) {
                carousel.add(i, elementHtml + '&lt;/li&gt;');
                elementInfo = $('#ui_' + i);
                elementInfo.data('imageData', _imgData[i]);
            } else {
                element.appendTo('#userImages');
                elementInfo = $('#ui_' + i);
                elementInfo.data('imageData', _imgData[i]);
            }
        }


        $('#userImages div').draggable({
            helper: 'clone',
            appendTo: 'body',
            start: function (event, ui)
            {
                $(ui.helper).css('zIndex', 5000);
                $(ui.helper).addClass('generator-drag-image');
                $(ui.helper).addClass('dragme');
                $('#canvasBox').droppable('option', 'accept', $('#userImages div'));
            },
            stop: function (event, ui)
            {
                $(ui.helper).css('zIndex', 'auto');
                $(ui.helper).removeClass('generator-drag-image');
                $(ui.helper).removeClass('dragme');
            }
        });

        return false;
    }

    /**
     * Set observer for images actions
     */
    function _reloadObservers()
    {
        $('#userImages &gt; li &gt; div &gt; span').on('click', function (event)
        {
            event.stopPropagation();
            CupSell.Generator.confirmDialog(
                    translation.deleteFile, translation.confirmDeleteFile, function () {
                        _removeImage($(event.currentTarget).parents().eq(1))
                    }
            );
        });

        $('#userImages &gt; li').on('click', function (event) {
            event.stopPropagation();
            if (event.target.tagName.toUpperCase() == 'SPAN') {

                var imgData = $(event.currentTarget).data('imageData');
                imgData.offset = undefined;
                CupSell.Generator.Canvas.addImg(imgData);
            }
        });

    }

    /**
     * Redraw user image list
     */
    function _redrawUserImages() {
        $('#userImages &gt; li').off('click', '**');
        $('#userImages &gt; li &gt; div &gt; span').off('click', '**');
        $('#userImages').empty();

        if (_imgData.length &gt; 8) {
            _carousel = $('#userImages').jcarousel({
                animation: 'fast',
                scroll: 1,
                vertical: true,
                size: Math.ceil(_imgData.length / 4) + 1,
                itemLoadCallback: {onBeforeAnimation: _carouselItemLoadCallback, onAfterAnimation: _reloadObservers}
            });
            $('#userImagesWrapper').css({marginTop: '0px', height: '365px'});
        } else {
            if (_carousel) {
                _carousel = $('#userImages').jcarousel({
                    animation: 'fast',
                    scroll: 1,
                    vertical: true,
                    size: Math.ceil(_imgData.length / 4),
                    itemLoadCallback: {onBeforeAnimation: _carouselItemLoadCallback, onAfterAnimation: _reloadObservers}
                });
                $('#userImages').css({top: '0px'});
            } else {
                _carouselItemLoadCallback();
                _reloadObservers();
            }
        }
    }


    /**
     * Remove image from user image list
     */
    function _removeImage(element) {
        var clickedData = element.data('imageData'),
                tmpData = Array();

        for (var i = 0; i &lt; _imgData.length; i++) {
            if (_imgData[i].userImage != clickedData.userImage) {
                tmpData.push(_imgData[i]);
            }
        }
        _imgData = tmpData;
        CupSell.Generator.StorageManager.store('csfile', $.toJSON(_imgData));
        _redrawUserImages();
    }


    /**
     * On file upload callback
     *
     * @param {String} response Response from server
     */
    function _completeUpload(response) {
        _uploadInProgress = false;
        response = $.parseJSON(response);
        
        if (response.status == 'ok') {
            _imgData.unshift({
                thumbnail: response.thumbnail,
                sprite: response.sprite,
                originalSize: response.original_size,
                userImage: response.user_file
            });
            CupSell.Generator.StorageManager.store('csfile', $.toJSON(_imgData));
            _redrawUserImages();

            if (CupSell.Generator.StorageManager.get('pid') &amp;&amp; CupSell.Generator.Canvas.isCurrentViewEmpty()) {
                CupSell.Generator.Canvas.addImg({
                    thumbnail: response.thumbnail,
                    sprite: response.sprite,
                    originalSize: response.original_size,
                    userImage: response.user_file,
                    offset: undefined
                });
            }

        } else {
            CupSell.Generator.errorDialog(translation.sendFileFailure, response.message);
        }
        $('#upFile').val('');
    }


    /**
     * On start file uploading callback
     *
     * @return {Boolean}
     */
    function _startUpload() {
        _uploadInProgress = true;

        var imageBox = $('#imageBox');
        var uploadBox = $('#uploadBox');
        var generatorUploader = $('#GeneratorUploader');

        uploadBox.css({width: imageBox.outerWidth(), height: imageBox.outerHeight()}).show();
        generatorUploader.css('pointer-events', 'none');


        (function worker() {
            $.ajax({
                url: '/generator-ajax/index',
                type: 'post',
                data: {'mod': 'file', 'act': 'uploadProgress', 'upId': $('#progressKey').val()},
                dataType: 'json',
                complete: function () {
                    if (_uploadInProgress) {
                        setTimeout(worker, 1000);
                    } else {
                        generatorUploader.css('pointer-events', '');
                        uploadBox.hide();

                    }

                }
            });
        })();

        return true;
    }


    return {
        clearImageData: function () {
            _imgData = [];
        },
        redrawUserImages: function () {
            _redrawUserImages();
        }
    };
})();;CupSell.Generator.ProductManager = (function ()
{
    $(document).ready(function ()
    {
        _addCategoryListeners();
        _addProductListeners();
        _addColorSelectorListeners();
    });


    /**
     * Fetch product from category via Ajax request
     * @var integer cId
     */
    function _loadProductsFromCategory(cId)
    {
        $.ajax({
            url: '/generator-ajax/index',
            type: 'post',
            data: {
                'mod': 'pattern',
                'act': 'getList',
                'categoryId': cId
            },
            dataType: 'html',
            error: function ()
            {
                log('fail');
            },
            success: function (response) {
                _removeProductListeners();
                $('#products_container').empty().append(response);
                _addProductListeners();
            }
        });
    }
    function _loadProductsFromSubCategoryAndColor()
    {
        var cId = $('#categories select').val() || 0;
        var sId = [];

        $('#categories .products_types li.active').each(function () {
            sId.push($(this).find('a').attr('rel'));
        });
        var color = [];
        $('#categories .products_colors li.active').each(function () {
            color.push($(this).find('a').attr('rel'));
        });
        $.ajax({
            url: '/generator-ajax/index',
            type: 'post',
            data: {
                'mod': 'pattern',
                'act': 'getList',
                'categoryId': cId,
                'types': sId,
                'colors': color
            },
            dataType: 'html',
            error: function ()
            {
                log('fail');
            },
            success: function (response) {
                _removeProductListeners();
                $('#products_container').empty().append(response);
                //patternScroll($('.pattern-wrapper').height() - $('.pattern-filters').height());
                _addProductListeners();
            }
        });
    }

    /**
     * Fetch product data via Ajax request
     * @var integer pId
     */
    function _loadProductData(pId)
    {
        $.ajax({
            url: '/generator-ajax/index',
            type: 'post',
            data: {
                'mod': 'pattern',
                'act': 'get',
                'productId': pId,
                'currencyId': $('#currency').val(),
                'external_domain': zend_vars.external_domain
            },
            dataType: 'json',
            error: function ()
            {
                log('fail');
            },
            success: function (response)
            {
                var transratio = {};

                if (response.status == 'ok') {
                    _updateProductData(response.product);

                    if (response.product.images) {
                        if (CupSell.Generator.StorageManager.get('previousPid') != response.product.tag) {
                            if (CupSell.Generator.StorageManager.get('cscanvas')) {
                                transratio = _getTransRatio(response.product.printSizes);
                            }

                            _storeCanvasSizes(response.product.printSizes);
                        }

                        CupSell.Generator.Views.setView(response.product.images.views[1].image);
                        CupSell.Generator.Views.setFontColor(response.product.printSizes[1].font_color);
                        CupSell.Generator.Views.setMask(response.product.images.views[1].mask);

                        CupSell.Generator.Editor.setProductColor(response.product.color);
                        CupSell.Generator.Editor.setBackgroundColor(response.product.printSizes[1].background_color);

                        CupSell.Generator.Canvas.setCanvasProps(response.product.id, response.product.tag, response.product.printSizes[1], 1, transratio);


                        //Generator Teeroulette
                        $('#sexSelector .selected').click();
                    }
                }
            }
        });
    }


    function _updateColorOptions(colors, current_id) {
        CupSell.Generator.Canvas.setColorLength(colors.length);

        $('#selector #versions').empty();
        $('#color_opts_selector #color_opts_versions').empty();
        $('&lt;h class="selectors"&gt;' + translation.chooseColors + '&lt;/h&gt;').appendTo('#selector #versions');
        var selected = null;
        for (var i = 0; i &lt; colors.length; i++) {
            selected = colors[i].id == current_id ? 'selected' : '';

            $('&lt;li class="' + selected + '"&gt;&lt;a href="javascript:void(null);" rel="' + colors[i].id + '" style="background-color: ' + colors[i].color + '" /&gt;')
                    .appendTo('#selector #versions');


            if (!selected)
                $('&lt;li&gt;&lt;a href="javascript:void(null);" rel="' + colors[i].id + '" style="background-color: ' + colors[i].color + '" /&gt;')
                        .appendTo('#color_opts_selector #color_opts_versions');
        }
    }


    /**
     * Update product data
     * @var integer pId
     */
    function _updateProductData(data)
    {
        var rel = undefined;

        $('#product #sizes').empty();
        $('&lt;h3&gt;' + translation.sizeTable + '&lt;/h3&gt;').appendTo('#product #sizes');

        $('#previewFrame').css('background-color', '');
        if (data.bgcolor_container !== '') {
            $('#previewFrame').css('background-color', data.bgcolor_container);
        }

        if (data.images.sizesPhoto) {
            $('&lt;img /&gt;', {
                'src': data.images.sizesPhoto
            }).appendTo('#product #sizes');
        }

        $.ajax({
            url: '/size/index/id/' + data.id,
            success: function (data)
            {
                $('#sizes').append(data);
            }
        });

        $('#product #description').empty();
        $('#product #description').append('&lt;h3&gt;' + translation.productDescription + '&lt;/h3&gt;');
        $('#product #description').append(data.description);

        $('#product #realphoto').empty();
        if (data.images.realPhoto) {
            $('#product #realphoto').append('&lt;h3&gt;' + translation.realPhoto + '&lt;/h3&gt;');
            $('&lt;img /&gt;', {
                'src': data.images.realPhoto
            }).appendTo('#product #realphoto');
        }

        _removeSelectorListeners();
        $('#selector #views').empty();

        if (typeof data.promo != 'undefined') {
            if (data.promo.value &gt; 0) {
                $('#preview-pattern-promo').show();
            }
            $('#preview-pattern-promo &gt; #promo-price').html(data.promo.value * (-1));
            $('#preview-pattern-promo &gt; #promo-price').show();
            if (data.promo.value_type === 'percent') {
                $('#preview-pattern-promo &gt; #promo-percent').show();
                $('#preview-pattern-promo &gt; #promo-value').hide();
            } else {
                $('#preview-pattern-promo &gt; #promo-value').show();
                $('#preview-pattern-promo &gt; #promo-percent').hide();

            }
        } else {
            $('#preview-pattern-promo').hide();
        }

        var selected = 'selected';
        var printPrices = {};
        $('&lt;h class="selectors"&gt;' + translation.chooseView + '&lt;/h&gt;').appendTo('#selector #views');
        for (var i = 1; i &lt; 5; i++) {
            if (data.images.views[i]) {
                if (typeof (data.printSizes[i]) != 'undefined') {
                    data.printSizes[i].view = i;
                    data.printSizes[i].imgPath = data.images.views[i].image;
                    data.printSizes[i].productId = data.id;
                    data.printSizes[i].tag = data.tag;
                    data.printSizes[i].maskPath = data.images.views[i].mask;
                    rel = escape($.toJSON(data.printSizes[i]));
                    printPrices[i] = parseFloat(data.printSizes[i].price.replace(',', '.'));
                }


                var thumbImage = $('&lt;img /&gt;', {
                    'src': data.images.views[i].thumbnail,
                    'class': 'thumb-file'
                });

                var liElement = $('&lt;li &gt;', {
                    'class': selected
                });

                var thumbContainer = $('&lt;a &gt;', {
                    'class': 'thumb-container',
                    'href': data.images.views[i].image,
                    'rel': rel
                });

                thumbContainer.append(thumbImage);
                if (data.images.views[i].maskThumbnail) {
                    var maskImage = $('&lt;img /&gt;', {
                        'src': data.images.views[i].maskThumbnail,
                        'class': 'mask-file'
                    });
                    thumbContainer.append(maskImage);
                }

                liElement.append(thumbContainer);

                $('#selector #views').append(liElement);

                selected = '';
            }
        }
        _updateColorOptions(data.colorVersions, data.id);


        var firstSize = null;
        var sizesList = $('ol.sizeSelectorGenerator');
        var parent = sizesList.parent();
        parent.removeAttr('data-tag');
        parent.attr('data-tag', data.tag);
        sizesList.attr('data-pattern', data.id);

        sizesList.each(function (k, element) {

            element = $(element);
            element.empty().append('&lt;li class="label"&gt;' + translation.chooseSize + '&lt;/li&gt;');
            counter = 0;
            $.each(data.sizes, function (id, size) {
                if (counter == 0 &amp;&amp; !firstSize) {
                    firstSize = id;
                }
                if (size === "brak rozmiaru") {
                    $('&lt;li class="none"&gt;' + translation.brakRozmiaru + '&lt;/li&gt;').data({
                        id: parseInt(id)
                    }).appendTo(element);
                } else if (size === "bez rozmiaru") {
                    $('&lt;li class="none"&gt;' + translation.bezRozmiaru + '&lt;/li&gt;').data({
                        id: parseInt(id)
                    }).appendTo(element);
                } else {
                    $('&lt;li data-size="' + id + '"&gt;' + size + '&lt;/li&gt;').data({
                        id: parseInt(id)
                    }).appendTo(element);
                }
                counter++;
            });
            element.show();
        });

        // Basket update
        if (typeof (data.price) == 'string') {
            data.price.replace(',', '.');
        }
        CupSell.Generator.Basket.setProductPrice(parseFloat(data.price));
        
        var specyficTagNames = [
            'koszulka',
            'koszulka-damska',
            //'czapka-z-daszkiem-trucker'
        ];
        
        if (specyficTagNames.indexOf(data.tag.toLowerCase()) !== false) {
            CupSell.Generator.Basket.setCommision(typeof ($('#msval').val()) != 'undefined' ? parseFloat($('#msval').val().replace(',', '.')) : 0);
        } else {
            CupSell.Generator.Basket.setCommision(typeof ($('#mval').val()) != 'undefined' ? parseFloat($('#mval').val().replace(',', '.')) : 0);
        }
        CupSell.Generator.Basket.setProductPrintPrices(printPrices);
        // Select first size if only one exists
        if (counter == 1) {
            $('#sizeSelectorGenerator &gt; li').eq(1).addClass('selected');
            CupSell.Generator.Basket.setSelectedSize(firstSize);
        } else {
            CupSell.Generator.Basket.setSelectedSize(undefined);
        }
        CupSell.Generator.Basket.updatePrice();

        _addSelectorListeners();
        _addColorOptionsListeners();
    }


    function _storeCanvasSizes(sizes)
    {
        var ratio = undefined,
                factor = undefined,
                canvasSizes = {};
        $.each(sizes, function (id, size)
        {
            for (var first in size.available_area.cm_size)
                break;
            if (size.print_area.width == '' || size.print_area.height == '')
                return;
            ratio = size.available_area.px_size.width / (size.available_area.cm_size[first].width * $('#canvas').data()['dpcm']);
            factor = ratio * $('#canvas').data()['dpcm'];

            canvasSizes[id] = {
                width: size.print_area.width * factor,
                height: size.print_area.height * factor
            }
        });
        CupSell.Generator.StorageManager.store('cscanvas', $.toJSON(canvasSizes));
    }

    function _getTransRatio(sizes)
    {
        var csSizes = $.evalJSON(CupSell.Generator.StorageManager.get('cscanvas')),
                ratio = undefined,
                xratio = undefined,
                yratio = undefined,
                factor = undefined,
                transratio = {},
                boundingBox = undefined;

        boundingBox = CupSell.Generator.Canvas.getDesignBoundingBox();

        $.each(sizes, function (id, size)
        {
            if (csSizes[id]) {
                transratio[id] = {
                    ratio: 1,
                    xOffset: 0,
                    yOffset: 0
                };

                for (var first in size.available_area.cm_size)
                    break;

                factor = size.available_area.px_size.width / size.available_area.cm_size[first].width;

                if (boundingBox['view_' + id]) {
                    xratio = (size.print_area.width * factor) / csSizes[id].width;
                    yratio = (size.print_area.height * factor) / csSizes[id].height;

                    if (boundingBox['view_' + id].width &gt; size.print_area.width * factor) {
                        xratio = (size.print_area.width * factor) / boundingBox['view_' + id].width;
                    }

                    if (boundingBox['view_' + id].height &gt; size.print_area.height * factor) {
                        yratio = (size.print_area.height * factor) / boundingBox['view_' + id].height;
                    }

                    if (boundingBox['view_' + id].width / (size.print_area.width * factor) &gt; boundingBox['view_' + id].height / (size.print_area.height * factor)) {
                        ratio = xratio;

                        if (yratio &gt; xratio &amp;&amp; boundingBox['view_' + id].width * yratio &lt; size.print_area.width * factor) {
                            ratio = yratio;
                        }

                    } else {
                        ratio = yratio;

                        if (xratio &gt; yratio &amp;&amp; boundingBox['view_' + id].height * xratio &lt; size.print_area.height * factor) {
                            ratio = xratio;
                        }
                    }

                    transratio[id].ratio = ratio;

                    transratio[id].xOffset = Math.floor(size.print_area.width * factor / 2 - (boundingBox['view_' + id].left + boundingBox['view_' + id].width / 2) * transratio[id].ratio);
                    transratio[id].yOffset = Math.floor(size.print_area.height * factor / 2 - (boundingBox['view_' + id].top + boundingBox['view_' + id].height / 2) * transratio[id].ratio);
                }
            }
        });

        return transratio;
    }


    /**
     * Attach event listeners to categories
     */
    function _addCategoryListeners()
    {
        $('#categories select').each(function (index, element)
        {
            $(element).on('change', function ()
            {
                $('div#generator div#productSelector &gt; div#categories &gt; ul.products_types li').removeClass('active')
                var temp_id = $(this).val();
                if (temp_id &gt; 0) {
                    $('div#generator div#productSelector &gt; div#categories &gt; ul.products_types li').hide();
                    $('div#generator div#productSelector &gt; div#categories &gt; ul.products_types li.p_' + temp_id).show();
                } else {
                    $('div#generator div#productSelector &gt; div#categories &gt; ul.products_types li').show();
                }
                _loadProductsFromSubCategoryAndColor();
            });
        });
        $('#categories .products_types li').each(function (index, element) {
            $(element).find('a').on("click", function (e) {
                e.preventDefault();
                $(this).parent().toggleClass("active");
                _loadProductsFromSubCategoryAndColor();
            })
        });
        $('#categories .products_colors li').each(function (index, element) {
            $(element).find('a').on("click", function (e) {
                e.preventDefault();
                $(this).parent().toggleClass("active");
                _loadProductsFromSubCategoryAndColor();
            })
        });

    }


    /**
     * Attach event listeners to products
     */
    function _addProductListeners()
    {
        $('#products_container a').each(function (index, element)
        {
            $(element).on('click', function (event)
            {

                event.stopPropagation();
                event.preventDefault();
                _loadProductData(element.rel);
            });
        });


        $('#productList').jcarousel({
            animation: 'fast',
            scroll: 1,
            vertical: false
        });
    }


    /**
     * Remove listeners from products
     */
    function _removeProductListeners()
    {
        $('#products ol li a').each(function (index, element) {
            $(element).off('click', '**');
        });
    }


    function _addColorOptionsListeners() {
        $('#color_opts_selector #color_opts_versions a').each(function (index, element) {
            $(element).on('click', function (event) {
                event.stopPropagation();
                event.preventDefault();
                var handle = $(this);
                var id = handle.attr('rel');
                var parent = handle.parent('li');

                if (parent.hasClass('selected')) {
                    var temp = CupSell.Generator.Canvas._exceptColors;
                    var index = temp.indexOf(id);
                    if (index &gt; -1) {
                        temp.splice(index, 1);
                    }

                    CupSell.Generator.Canvas._exceptColors = temp;
                    parent.removeClass('selected');
                } else {
                    CupSell.Generator.Canvas._exceptColors.push(id);
                    parent.addClass('selected');
                }
            });
        });
    }

    function _addColorSelectorListeners() {
        var color_opts = $('#color_opts');
        var color_opts_selector = $('#color_opts_selector');

        color_opts.bind('change', function (event) {
            event.stopPropagation();
            event.preventDefault();

            var value = color_opts.find('option:selected').val();
            CupSell.Generator.Canvas._colorOption = value;

            if (value === 'except') {
                CupSell.Generator.Canvas._exceptColors = [];
                color_opts_selector.find('#color_opts_versions li').removeClass('selected');
                color_opts_selector.show();
            } else {
                if (value === 'all')
                    color_opts_selector.find('#color_opts_versions li').addClass('selected');
                else if (value === 'only') {
                    CupSell.Generator.Canvas._exceptColors = [];
                    color_opts_selector.find('#color_opts_versions li').removeClass('selected');
                }
                color_opts_selector.hide();
            }


        });
    }

    /**
     * Attach event listeners to selector items
     */
    function _addSelectorListeners()
    {
        $('#selector #versions a').each(function (index, element)
        {
            $(element).on('click', function (event)
            {
                event.stopPropagation();
                event.preventDefault();
                _loadProductData(element.rel);
            });
        });

        $('#selector #views a').each(function (index, element) {
            $(element).on('click', function (event)
            {
                event.stopPropagation();
                event.preventDefault();
                var sizeData = $.parseJSON(unescape(event.delegateTarget.rel));

                CupSell.Generator.Views.setView(sizeData.imgPath);
                CupSell.Generator.Views.setMask(sizeData.maskPath);
                CupSell.Generator.Views.setFontColor(sizeData.font_color);
                CupSell.Generator.Editor.setBackgroundColor(sizeData.background_color);

                CupSell.Generator.Tabs.togglePanel('imageTab');

                CupSell.Generator.Canvas.setCanvasProps(sizeData.productId, sizeData.tag, sizeData, sizeData.view, {});

                $('#selector #views li').removeClass('selected');
                $(element).parent('li').addClass('selected');
            });
        });



        // product sizes
        $('.sizeSelectorGenerator li').each(function (index, element) {
            if (index &gt; 0) {
                $(element).on('click', function (event) {
                    $('ol.sizeSelectorGenerator li').removeClass('selected');
                    $(event.currentTarget).addClass('selected');
                    CupSell.Generator.Basket.setSelectedSize($(event.currentTarget).data('id'));
                });



                var xOffset = -30;
                var yOffset = -340;

                var li = $(element);

                var request = null;

                li.hover(function (e) {

                    var patternId = $('ol.sizeSelectorGenerator').attr('data-pattern');
                    $("#individual_size").remove();
                    var sizeId = $(this).data('size');

                    if (request) {
                        request.abort();
                    }
                    request = $.ajax({
                        url: '/size/one-size/id/' + patternId + '/size/' + sizeId,
                        beforeSend: function () {
                            var paragraph = $("&lt;p id='individual_size' style=\"display:block;color: #000\"&gt;&lt;/p&gt;");
                            paragraph.html('&lt;img src="/img/default/layout/loading.gif" style="width:100px;"&gt;');
                            $('body').append(paragraph);

                            $(paragraph)
                                    .css("top", (e.pageY - xOffset) + "px")
                                    .css("left", (e.pageX + yOffset) + "px")
                                    .fadeIn("fast");

                        },
                        success: function (data)
                        {
                            $('#individual_size').html(data);
                        }
                    });

                }, function () {
                    $("#individual_size").remove();
                });

                li.mousemove(function (e) {

                    $("#individual_size")
                            .css("top", (e.pageY - xOffset) + "px")
                            .css("left", (e.pageX + yOffset) + "px");
                });

            }
        });
        //product sex
        $('.sexSelector li').each(function (index, element) {
            $(element).on('click', function (event) {
                $('ol.sexSelector li').removeClass('selected');
                $(event.currentTarget).addClass('selected');
                CupSell.Generator.Basket.setSelectedSex($(event.currentTarget).data('id'));
            });
        });

        $('#chooseSizeDialog ol.sizeSelectorGenerator li').each(function (index, element) {
            if (index &gt; 0) {
                $(element).on('click', function (event) {
                    $('ol.sizeSelectorGenerator li').removeClass('selected');
                    $(event.currentTarget).addClass('selected');
                    CupSell.Generator.Basket.setSelectedSize($(event.currentTarget).data('id'));

                    // find twin element to hilite
                    $('#sizeSelectorGenerator li').each(function (k, element) {
                        if ($(element).data('id') == $(event.currentTarget).data('id')) {
                            $(element).addClass('selected');
                        }
                    });

                    $('#chooseSizeDialog .button.ok').removeClass('disabled');
                });
            }
        });
    }


    /**
     * Remove listeners from selector items
     */
    function _removeSelectorListeners()
    {
        $('#selector a').each(function (index, element) {
            $(element).off('click', '**');
        });

        $('ol.sizeSelectorGenerator li').each(function (index, element) {
            $(element).off('click', '**');
        });
    }


    function _clearViewsSelector() {
        $('#selector #views').empty();
    }


    return {
        loadProductData: _loadProductData,
        clearViewsSelector: _clearViewsSelector,
        addColorSelectorListeners: _addColorSelectorListeners
    };

})();;CupSell.Generator.ImagesManager = (function ()
{
    $(document).ready(function () {
        _initSelector();
        _initDraggable();


        $('#galleryImages &gt; li').each(function () {
        });

        $('#galleryImages &gt; li').on('click', function (event) {

            _addImage(this);
        });

    });

    function _initSelector() {
        $('#categorySelect').on('change', function () {
            var category = $(this).val();
            $('#galleryImages li').each(function () {
                if (!category || $(this).data('category') === category) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });

        });
    }

    function _addImage(object,offset) {
        var imageBox = $('#typeBox');
        $('#galleryBox').css({width: imageBox.outerWidth(), height: imageBox.outerHeight()}).show();

        var imageObj = $(object);
        var filepath = $(object).data('filepath');
        var image = new Image();
        var thumb = $(object).data('thumb');
        image.src = filepath;
        image.onload = function ()
        {
            var imgData = {
                offset: offset,
                originalSize: {
                    height: image.height,
                    width: image.width
                },
                sprite: thumb,
                thumbnail: thumb,
                userImage: filepath
            };
            imageObj.data('imageData',imgData);
            CupSell.Generator.Canvas.addImg(imgData);
            $('#galleryBox').hide();
        };
    };
    
    function _initDraggable() {

        $('.generator-drag-image').draggable({
            helper: 'clone',
            appendTo: 'body',
            start: function (event, ui)
            {
                $(ui.helper).css('zIndex', 5000);
                //$(ui.helper).addClass('generator-drag-image');
                $(ui.helper).addClass('dragme');
                $('#canvasBox').droppable('option', 'accept', $('.generator-drag-image'));
            },
            stop: function (event, ui)
            {
                $(ui.helper).css('zIndex', 'auto');
                //$(ui.helper).removeClass('generator-drag-image');
                $(ui.helper).removeClass('dragme');
            }
        });
    };


    return {
        addImage: _addImage
    };

})();;function number_format (number, decimals, dec_point, thousands_sep) {
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec);
        return '' + Math.round(n * k) / k;
    };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length &gt; 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length &lt; prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function initLazyload() {
    $("img.lazyload").lazyload({
        effect : "fadeIn",
        thereshold: 200,
        skip_invisible : false
    });
}

function htmlspecialchars(text) {
    return text
    .replace(/&amp;/g, "&amp;amp;")
    .replace(/&lt;/g, "&amp;lt;")
    .replace(/&gt;/g, "&amp;gt;")
    .replace(/"/g, "&amp;quot;")
    .replace(/'/g, "&amp;#039;");
}

jQuery(function(){
    if ($.fn.datepicker) {
        $('.date').datepicker({
            dateFormat : 'yy-mm-dd',
            monthNames : ['Stycze\u0144','Luty','Marzec',
            'Kw\u0144ecieÅ„','Maj','Czerwiec','Lipiec',
            'Sierpie\u0144','Wrzesie\u0144','Pa\u017adziernik','Listopad',
            'GrudzieÅ„'
            ],
            dayNames : [ 'Poniedzia\u0142ek', 'Wtore\u015a', '\u015aroda', 'Czwartek', 'Pi\u0105tek'],
            dayNamesMin : ['Pn', 'Wt', 'Sr', 'Cz', 'Pt', 'Sb', 'Nd']
        });
        
        $('.date-month-year').datepicker( {
            changeMonth: true,
            changeYear: true,
            showButtonPanel: false,
            dateFormat: 'yy-mm',
            monthNamesShort : ['Stycze\u0144','Luty','Marzec',
            'Kw\u0144ecieÅ„','Maj','Czerwiec','Lipiec',
            'Sierpie\u0144','Wrzesie\u0144','Pa\u017adziernik','Listopad',
            'GrudzieÅ„'
            ],
            onClose: function(dateText, inst) { 
                var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                $(this).datepicker('setDate', new Date(year, month, 1));
            }
        });
    }
    
    // toggle shop description
    var shop_desc_toggles = $('.shop_desc_toggle');
    shop_desc_toggles.click(function(e) {
        e.preventDefault();
        if ($(this).hasClass('more')) {
            $(this).closest('div').data('height', $(this).closest('div').height());
            $(this).closest('div').height('auto');

            $('#shop_desc_long').removeClass('hidden');
            $('#shop_desc_short').addClass('hidden');
        } else {
            $('#shop_desc_long').addClass('hidden');
            $('#shop_desc_short').removeClass('hidden');

            $(this).closest('div').height($(this).closest('div').data('height'));
        }
    });
    
    initLazyload();
});;/*
 * Lazy Load - jQuery plugin for lazy loading images
 *
 * Copyright (c) 2007-2013 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://www.appelsiini.net/projects/lazyload
 *
 * Version:  1.9.1
 *
 */

(function($, window, document, undefined) {
    var $window = $(window);

    $.fn.lazyload = function(options) {
        var elements = this;
        var $container;
        var settings = {
            threshold       : 0,
            failure_limit   : 0,
            event           : "scroll",
            effect          : "show",
            container       : window,
            data_attribute  : "original",
            skip_invisible  : true,
            appear          : null,
            load            : null,
            placeholder     : "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC"
        };

        function update() {
            var counter = 0;

            elements.each(function() {
                var $this = $(this);
                if (settings.skip_invisible &amp;&amp; !$this.is(":visible")) {
                    return;
                }
                if ($.abovethetop(this, settings) ||
                    $.leftofbegin(this, settings)) {
                        /* Nothing. */
                } else if (!$.belowthefold(this, settings) &amp;&amp;
                    !$.rightoffold(this, settings)) {
                        $this.trigger("appear");
                        /* if we found an image we'll load, reset the counter */
                        counter = 0;
                } else {
                    if (++counter &gt; settings.failure_limit) {
                        return false;
                    }
                }
            });

        }

        if(options) {
            /* Maintain BC for a couple of versions. */
            if (undefined !== options.failurelimit) {
                options.failure_limit = options.failurelimit;
                delete options.failurelimit;
            }
            if (undefined !== options.effectspeed) {
                options.effect_speed = options.effectspeed;
                delete options.effectspeed;
            }

            $.extend(settings, options);
        }

        /* Cache container as jQuery as object. */
        $container = (settings.container === undefined ||
                      settings.container === window) ? $window : $(settings.container);

        /* Fire one scroll event per scroll. Not one scroll event per image. */
        if (0 === settings.event.indexOf("scroll")) {
            $container.bind(settings.event, function() {
                return update();
            });
        }

        this.each(function() {
            var self = this;
            var $self = $(self);

            self.loaded = false;

            /* If no src attribute given use data:uri. */
            if ($self.attr("src") === undefined || $self.attr("src") === false) {
                if ($self.is("img")) {
                    $self.attr("src", settings.placeholder);
                }
            }

            /* When appear is triggered load original image. */
            $self.one("appear", function() {
                if (!this.loaded) {
                    if (settings.appear) {
                        var elements_left = elements.length;
                        settings.appear.call(self, elements_left, settings);
                    }
                    $("&lt;img /&gt;")
                        .bind("load", function() {

                            var original = $self.attr("data-" + settings.data_attribute);
                            $self.hide();
                            if ($self.is("img")) {
                                $self.attr("src", original);
                            } else {
                                $self.css("background-image", "url('" + original + "')");
                            }
                            $self[settings.effect](settings.effect_speed);

                            self.loaded = true;

                            /* Remove image from array so it is not looped next time. */
                            var temp = $.grep(elements, function(element) {
                                return !element.loaded;
                            });
                            elements = $(temp);

                            if (settings.load) {
                                var elements_left = elements.length;
                                settings.load.call(self, elements_left, settings);
                            }
                        })
                        .attr("src", $self.attr("data-" + settings.data_attribute));
                }
            });

            /* When wanted event is triggered load original image */
            /* by triggering appear.                              */
            if (0 !== settings.event.indexOf("scroll")) {
                $self.bind(settings.event, function() {
                    if (!self.loaded) {
                        $self.trigger("appear");
                    }
                });
            }
        });

        /* Check if something appears when window is resized. */
        $window.bind("resize", function() {
            update();
        });

        /* With IOS5 force loading images when navigating with back button. */
        /* Non optimal workaround. */
        if ((/(?:iphone|ipod|ipad).*os 5/gi).test(navigator.appVersion)) {
            $window.bind("pageshow", function(event) {
                if (event.originalEvent &amp;&amp; event.originalEvent.persisted) {
                    elements.each(function() {
                        $(this).trigger("appear");
                    });
                }
            });
        }

        /* Force initial check if images should appear. */
        $(document).ready(function() {
            update();
        });

        return this;
    };

    /* Convenience methods in jQuery namespace.           */
    /* Use as  $.belowthefold(element, {threshold : 100, container : window}) */

    $.belowthefold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = (window.innerHeight ? window.innerHeight : $window.height()) + $window.scrollTop();
        } else {
            fold = $(settings.container).offset().top + $(settings.container).height();
        }

        return fold &lt;= $(element).offset().top - settings.threshold;
    };

    $.rightoffold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.width() + $window.scrollLeft();
        } else {
            fold = $(settings.container).offset().left + $(settings.container).width();
        }

        return fold &lt;= $(element).offset().left - settings.threshold;
    };

    $.abovethetop = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollTop();
        } else {
            fold = $(settings.container).offset().top;
        }

        return fold &gt;= $(element).offset().top + settings.threshold  + $(element).height();
    };

    $.leftofbegin = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollLeft();
        } else {
            fold = $(settings.container).offset().left;
        }

        return fold &gt;= $(element).offset().left + settings.threshold + $(element).width();
    };

    $.inviewport = function(element, settings) {
         return !$.rightoffold(element, settings) &amp;&amp; !$.leftofbegin(element, settings) &amp;&amp;
                !$.belowthefold(element, settings) &amp;&amp; !$.abovethetop(element, settings);
     };

    /* Custom selectors for your convenience.   */
    /* Use as $("img:below-the-fold").something() or */
    /* $("img").filter(":below-the-fold").something() which is faster */

    $.extend($.expr[":"], {
        "below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0}); },
        "above-the-top"  : function(a) { return !$.belowthefold(a, {threshold : 0}); },
        "right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0}); },
        "left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0}); },
        "in-viewport"    : function(a) { return $.inviewport(a, {threshold : 0}); },
        /* Maintain BC for couple of versions. */
        "above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
        "right-of-fold"  : function(a) { return $.rightoffold(a, {threshold : 0}); },
        "left-of-fold"   : function(a) { return !$.rightoffold(a, {threshold : 0}); }
    });

})(jQuery, window, document);;/*
	Copyright (c) 2004-2006, The Dojo Foundation
	All Rights Reserved.

	Licensed under the Academic Free License version 2.1 or above OR the
	modified BSD license. For more information on Dojo licensing, see:

		http://dojotoolkit.org/community/licensing.shtml
*/

/*
	This is a compiled version of Dojo, built for deployment and not for
	development. To get an editable version, please visit:

		http://dojotoolkit.org

	for documentation and information on getting the source.
*/

if(typeof dojo=="undefined"){
var dj_global=this;
var dj_currentContext=this;
function dj_undef(_1,_2){
return (typeof (_2||dj_currentContext)[_1]=="undefined");
}
if(dj_undef("djConfig",this)){
var djConfig={};
}
if(dj_undef("dojo",this)){
var dojo={};
}
dojo.global=function(){
return dj_currentContext;
};
dojo.locale=djConfig.locale;
dojo.version={major:0,minor:4,patch:3,flag:"",revision:Number("$Rev: 8617 $".match(/[0-9]+/)[0]),toString:function(){
with(dojo.version){
return major+"."+minor+"."+patch+flag+" ("+revision+")";
}
}};
dojo.evalProp=function(_3,_4,_5){
if((!_4)||(!_3)){
return undefined;
}
if(!dj_undef(_3,_4)){
return _4[_3];
}
return (_5?(_4[_3]={}):undefined);
};
dojo.parseObjPath=function(_6,_7,_8){
var _9=(_7||dojo.global());
var _a=_6.split(".");
var _b=_a.pop();
for(var i=0,l=_a.length;i&lt;l&amp;&amp;_9;i++){
_9=dojo.evalProp(_a[i],_9,_8);
}
return {obj:_9,prop:_b};
};
dojo.evalObjPath=function(_e,_f){
if(typeof _e!="string"){
return dojo.global();
}
if(_e.indexOf(".")==-1){
return dojo.evalProp(_e,dojo.global(),_f);
}
var ref=dojo.parseObjPath(_e,dojo.global(),_f);
if(ref){
return dojo.evalProp(ref.prop,ref.obj,_f);
}
return null;
};
dojo.errorToString=function(_11){
if(!dj_undef("message",_11)){
return _11.message;
}else{
if(!dj_undef("description",_11)){
return _11.description;
}else{
return _11;
}
}
};
dojo.raise=function(_12,_13){
if(_13){
_12=_12+": "+dojo.errorToString(_13);
}else{
_12=dojo.errorToString(_12);
}
try{
if(djConfig.isDebug){
dojo.hostenv.println("FATAL exception raised: "+_12);
}
}
catch(e){
}
throw _13||Error(_12);
};
dojo.debug=function(){
};
dojo.debugShallow=function(obj){
};
dojo.profile={start:function(){
},end:function(){
},stop:function(){
},dump:function(){
}};
function dj_eval(_15){
return dj_global.eval?dj_global.eval(_15):eval(_15);
}
dojo.unimplemented=function(_16,_17){
var _18="'"+_16+"' not implemented";
if(_17!=null){
_18+=" "+_17;
}
dojo.raise(_18);
};
dojo.deprecated=function(_19,_1a,_1b){
var _1c="DEPRECATED: "+_19;
if(_1a){
_1c+=" "+_1a;
}
if(_1b){
_1c+=" -- will be removed in version: "+_1b;
}
dojo.debug(_1c);
};
dojo.render=(function(){
function vscaffold(_1d,_1e){
var tmp={capable:false,support:{builtin:false,plugin:false},prefixes:_1d};
for(var i=0;i&lt;_1e.length;i++){
tmp[_1e[i]]=false;
}
return tmp;
}
return {name:"",ver:dojo.version,os:{win:false,linux:false,osx:false},html:vscaffold(["html"],["ie","opera","khtml","safari","moz"]),svg:vscaffold(["svg"],["corel","adobe","batik"]),vml:vscaffold(["vml"],["ie"]),swf:vscaffold(["Swf","Flash","Mm"],["mm"]),swt:vscaffold(["Swt"],["ibm"])};
})();
dojo.hostenv=(function(){
var _21={isDebug:false,allowQueryConfig:false,baseScriptUri:"",baseRelativePath:"",libraryScriptUri:"",iePreventClobber:false,ieClobberMinimal:true,preventBackButtonFix:true,delayMozLoadingFix:false,searchIds:[],parseWidgets:true};
if(typeof djConfig=="undefined"){
djConfig=_21;
}else{
for(var _22 in _21){
if(typeof djConfig[_22]=="undefined"){
djConfig[_22]=_21[_22];
}
}
}
return {name_:"(unset)",version_:"(unset)",getName:function(){
return this.name_;
},getVersion:function(){
return this.version_;
},getText:function(uri){
dojo.unimplemented("getText","uri="+uri);
}};
})();
dojo.hostenv.getBaseScriptUri=function(){
if(djConfig.baseScriptUri.length){
return djConfig.baseScriptUri;
}
var uri=new String(djConfig.libraryScriptUri||djConfig.baseRelativePath);
if(!uri){
dojo.raise("Nothing returned by getLibraryScriptUri(): "+uri);
}
var _25=uri.lastIndexOf("/");
djConfig.baseScriptUri=djConfig.baseRelativePath;
return djConfig.baseScriptUri;
};
(function(){
var _26={pkgFileName:"__package__",loading_modules_:{},loaded_modules_:{},addedToLoadingCount:[],removedFromLoadingCount:[],inFlightCount:0,modulePrefixes_:{dojo:{name:"dojo",value:"src"}},setModulePrefix:function(_27,_28){
this.modulePrefixes_[_27]={name:_27,value:_28};
},moduleHasPrefix:function(_29){
var mp=this.modulePrefixes_;
return Boolean(mp[_29]&amp;&amp;mp[_29].value);
},getModulePrefix:function(_2b){
if(this.moduleHasPrefix(_2b)){
return this.modulePrefixes_[_2b].value;
}
return _2b;
},getTextStack:[],loadUriStack:[],loadedUris:[],post_load_:false,modulesLoadedListeners:[],unloadListeners:[],loadNotifying:false};
for(var _2c in _26){
dojo.hostenv[_2c]=_26[_2c];
}
})();
dojo.hostenv.loadPath=function(_2d,_2e,cb){
var uri;
if(_2d.charAt(0)=="/"||_2d.match(/^\w+:/)){
uri=_2d;
}else{
uri=this.getBaseScriptUri()+_2d;
}
if(djConfig.cacheBust&amp;&amp;dojo.render.html.capable){
uri+="?"+String(djConfig.cacheBust).replace(/\W+/g,"");
}
try{
return !_2e?this.loadUri(uri,cb):this.loadUriAndCheck(uri,_2e,cb);
}
catch(e){
dojo.debug(e);
return false;
}
};
dojo.hostenv.loadUri=function(uri,cb){
if(this.loadedUris[uri]){
return true;
}
var _33=this.getText(uri,null,true);
if(!_33){
return false;
}
this.loadedUris[uri]=true;
if(cb){
_33="("+_33+")";
}
var _34=dj_eval(_33);
if(cb){
cb(_34);
}
return true;
};
dojo.hostenv.loadUriAndCheck=function(uri,_36,cb){
var ok=true;
try{
ok=this.loadUri(uri,cb);
}
catch(e){
dojo.debug("failed loading ",uri," with error: ",e);
}
return Boolean(ok&amp;&amp;this.findModule(_36,false));
};
dojo.loaded=function(){
};
dojo.unloaded=function(){
};
dojo.hostenv.loaded=function(){
this.loadNotifying=true;
this.post_load_=true;
var mll=this.modulesLoadedListeners;
for(var x=0;x&lt;mll.length;x++){
mll[x]();
}
this.modulesLoadedListeners=[];
this.loadNotifying=false;
dojo.loaded();
};
dojo.hostenv.unloaded=function(){
var mll=this.unloadListeners;
while(mll.length){
(mll.pop())();
}
dojo.unloaded();
};
dojo.addOnLoad=function(obj,_3d){
var dh=dojo.hostenv;
if(arguments.length==1){
dh.modulesLoadedListeners.push(obj);
}else{
if(arguments.length&gt;1){
dh.modulesLoadedListeners.push(function(){
obj[_3d]();
});
}
}
if(dh.post_load_&amp;&amp;dh.inFlightCount==0&amp;&amp;!dh.loadNotifying){
dh.callLoaded();
}
};
dojo.addOnUnload=function(obj,_40){
var dh=dojo.hostenv;
if(arguments.length==1){
dh.unloadListeners.push(obj);
}else{
if(arguments.length&gt;1){
dh.unloadListeners.push(function(){
obj[_40]();
});
}
}
};
dojo.hostenv.modulesLoaded=function(){
if(this.post_load_){
return;
}
if(this.loadUriStack.length==0&amp;&amp;this.getTextStack.length==0){
if(this.inFlightCount&gt;0){
dojo.debug("files still in flight!");
return;
}
dojo.hostenv.callLoaded();
}
};
dojo.hostenv.callLoaded=function(){
if(typeof setTimeout=="object"||(djConfig["useXDomain"]&amp;&amp;dojo.render.html.opera)){
setTimeout("dojo.hostenv.loaded();",0);
}else{
dojo.hostenv.loaded();
}
};
dojo.hostenv.getModuleSymbols=function(_42){
var _43=_42.split(".");
for(var i=_43.length;i&gt;0;i--){
var _45=_43.slice(0,i).join(".");
if((i==1)&amp;&amp;!this.moduleHasPrefix(_45)){
_43[0]="../"+_43[0];
}else{
var _46=this.getModulePrefix(_45);
if(_46!=_45){
_43.splice(0,i,_46);
break;
}
}
}
return _43;
};
dojo.hostenv._global_omit_module_check=false;
dojo.hostenv.loadModule=function(_47,_48,_49){
if(!_47){
return;
}
_49=this._global_omit_module_check||_49;
var _4a=this.findModule(_47,false);
if(_4a){
return _4a;
}
if(dj_undef(_47,this.loading_modules_)){
this.addedToLoadingCount.push(_47);
}
this.loading_modules_[_47]=1;
var _4b=_47.replace(/\./g,"/")+".js";
var _4c=_47.split(".");
var _4d=this.getModuleSymbols(_47);
var _4e=((_4d[0].charAt(0)!="/")&amp;&amp;!_4d[0].match(/^\w+:/));
var _4f=_4d[_4d.length-1];
var ok;
if(_4f=="*"){
_47=_4c.slice(0,-1).join(".");
while(_4d.length){
_4d.pop();
_4d.push(this.pkgFileName);
_4b=_4d.join("/")+".js";
if(_4e&amp;&amp;_4b.charAt(0)=="/"){
_4b=_4b.slice(1);
}
ok=this.loadPath(_4b,!_49?_47:null);
if(ok){
break;
}
_4d.pop();
}
}else{
_4b=_4d.join("/")+".js";
_47=_4c.join(".");
var _51=!_49?_47:null;
ok=this.loadPath(_4b,_51);
if(!ok&amp;&amp;!_48){
_4d.pop();
while(_4d.length){
_4b=_4d.join("/")+".js";
ok=this.loadPath(_4b,_51);
if(ok){
break;
}
_4d.pop();
_4b=_4d.join("/")+"/"+this.pkgFileName+".js";
if(_4e&amp;&amp;_4b.charAt(0)=="/"){
_4b=_4b.slice(1);
}
ok=this.loadPath(_4b,_51);
if(ok){
break;
}
}
}
if(!ok&amp;&amp;!_49){
dojo.raise("Could not load '"+_47+"'; last tried '"+_4b+"'");
}
}
if(!_49&amp;&amp;!this["isXDomain"]){
_4a=this.findModule(_47,false);
if(!_4a){
dojo.raise("symbol '"+_47+"' is not defined after loading '"+_4b+"'");
}
}
return _4a;
};
dojo.hostenv.startPackage=function(_52){
var _53=String(_52);
var _54=_53;
var _55=_52.split(/\./);
if(_55[_55.length-1]=="*"){
_55.pop();
_54=_55.join(".");
}
var _56=dojo.evalObjPath(_54,true);
this.loaded_modules_[_53]=_56;
this.loaded_modules_[_54]=_56;
return _56;
};
dojo.hostenv.findModule=function(_57,_58){
var lmn=String(_57);
if(this.loaded_modules_[lmn]){
return this.loaded_modules_[lmn];
}
if(_58){
dojo.raise("no loaded module named '"+_57+"'");
}
return null;
};
dojo.kwCompoundRequire=function(_5a){
var _5b=_5a["common"]||[];
var _5c=_5a[dojo.hostenv.name_]?_5b.concat(_5a[dojo.hostenv.name_]||[]):_5b.concat(_5a["default"]||[]);
for(var x=0;x&lt;_5c.length;x++){
var _5e=_5c[x];
if(_5e.constructor==Array){
dojo.hostenv.loadModule.apply(dojo.hostenv,_5e);
}else{
dojo.hostenv.loadModule(_5e);
}
}
};
dojo.require=function(_5f){
dojo.hostenv.loadModule.apply(dojo.hostenv,arguments);
};
dojo.requireIf=function(_60,_61){
var _62=arguments[0];
if((_62===true)||(_62=="common")||(_62&amp;&amp;dojo.render[_62].capable)){
var _63=[];
for(var i=1;i&lt;arguments.length;i++){
_63.push(arguments[i]);
}
dojo.require.apply(dojo,_63);
}
};
dojo.requireAfterIf=dojo.requireIf;
dojo.provide=function(_65){
return dojo.hostenv.startPackage.apply(dojo.hostenv,arguments);
};
dojo.registerModulePath=function(_66,_67){
return dojo.hostenv.setModulePrefix(_66,_67);
};
if(djConfig["modulePaths"]){
for(var param in djConfig["modulePaths"]){
dojo.registerModulePath(param,djConfig["modulePaths"][param]);
}
}
dojo.setModulePrefix=function(_68,_69){
dojo.deprecated("dojo.setModulePrefix(\""+_68+"\", \""+_69+"\")","replaced by dojo.registerModulePath","0.5");
return dojo.registerModulePath(_68,_69);
};
dojo.exists=function(obj,_6b){
var p=_6b.split(".");
for(var i=0;i&lt;p.length;i++){
if(!obj[p[i]]){
return false;
}
obj=obj[p[i]];
}
return true;
};
dojo.hostenv.normalizeLocale=function(_6e){
var _6f=_6e?_6e.toLowerCase():dojo.locale;
if(_6f=="root"){
_6f="ROOT";
}
return _6f;
};
dojo.hostenv.searchLocalePath=function(_70,_71,_72){
_70=dojo.hostenv.normalizeLocale(_70);
var _73=_70.split("-");
var _74=[];
for(var i=_73.length;i&gt;0;i--){
_74.push(_73.slice(0,i).join("-"));
}
_74.push(false);
if(_71){
_74.reverse();
}
for(var j=_74.length-1;j&gt;=0;j--){
var loc=_74[j]||"ROOT";
var _78=_72(loc);
if(_78){
break;
}
}
};
dojo.hostenv.localesGenerated;
dojo.hostenv.registerNlsPrefix=function(){
dojo.registerModulePath("nls","nls");
};
dojo.hostenv.preloadLocalizations=function(){
if(dojo.hostenv.localesGenerated){
dojo.hostenv.registerNlsPrefix();
function preload(_79){
_79=dojo.hostenv.normalizeLocale(_79);
dojo.hostenv.searchLocalePath(_79,true,function(loc){
for(var i=0;i&lt;dojo.hostenv.localesGenerated.length;i++){
if(dojo.hostenv.localesGenerated[i]==loc){
dojo["require"]("nls.dojo_"+loc);
return true;
}
}
return false;
});
}
preload();
var _7c=djConfig.extraLocale||[];
for(var i=0;i&lt;_7c.length;i++){
preload(_7c[i]);
}
}
dojo.hostenv.preloadLocalizations=function(){
};
};
dojo.requireLocalization=function(_7e,_7f,_80,_81){
dojo.hostenv.preloadLocalizations();
var _82=dojo.hostenv.normalizeLocale(_80);
var _83=[_7e,"nls",_7f].join(".");
var _84="";
if(_81){
var _85=_81.split(",");
for(var i=0;i&lt;_85.length;i++){
if(_82.indexOf(_85[i])==0){
if(_85[i].length&gt;_84.length){
_84=_85[i];
}
}
}
if(!_84){
_84="ROOT";
}
}
var _87=_81?_84:_82;
var _88=dojo.hostenv.findModule(_83);
var _89=null;
if(_88){
if(djConfig.localizationComplete&amp;&amp;_88._built){
return;
}
var _8a=_87.replace("-","_");
var _8b=_83+"."+_8a;
_89=dojo.hostenv.findModule(_8b);
}
if(!_89){
_88=dojo.hostenv.startPackage(_83);
var _8c=dojo.hostenv.getModuleSymbols(_7e);
var _8d=_8c.concat("nls").join("/");
var _8e;
dojo.hostenv.searchLocalePath(_87,_81,function(loc){
var _90=loc.replace("-","_");
var _91=_83+"."+_90;
var _92=false;
if(!dojo.hostenv.findModule(_91)){
dojo.hostenv.startPackage(_91);
var _93=[_8d];
if(loc!="ROOT"){
_93.push(loc);
}
_93.push(_7f);
var _94=_93.join("/")+".js";
_92=dojo.hostenv.loadPath(_94,null,function(_95){
var _96=function(){
};
_96.prototype=_8e;
_88[_90]=new _96();
for(var j in _95){
_88[_90][j]=_95[j];
}
});
}else{
_92=true;
}
if(_92&amp;&amp;_88[_90]){
_8e=_88[_90];
}else{
_88[_90]=_8e;
}
if(_81){
return true;
}
});
}
if(_81&amp;&amp;_82!=_84){
_88[_82.replace("-","_")]=_88[_84.replace("-","_")];
}
};
(function(){
var _98=djConfig.extraLocale;
if(_98){
if(!_98 instanceof Array){
_98=[_98];
}
var req=dojo.requireLocalization;
dojo.requireLocalization=function(m,b,_9c,_9d){
req(m,b,_9c,_9d);
if(_9c){
return;
}
for(var i=0;i&lt;_98.length;i++){
req(m,b,_98[i],_9d);
}
};
}
})();
}
if(typeof window!="undefined"){
(function(){
if(djConfig.allowQueryConfig){
var _9f=document.location.toString();
var _a0=_9f.split("?",2);
if(_a0.length&gt;1){
var _a1=_a0[1];
var _a2=_a1.split("&amp;");
for(var x in _a2){
var sp=_a2[x].split("=");
if((sp[0].length&gt;9)&amp;&amp;(sp[0].substr(0,9)=="djConfig.")){
var opt=sp[0].substr(9);
try{
djConfig[opt]=eval(sp[1]);
}
catch(e){
djConfig[opt]=sp[1];
}
}
}
}
}
if(((djConfig["baseScriptUri"]=="")||(djConfig["baseRelativePath"]==""))&amp;&amp;(document&amp;&amp;document.getElementsByTagName)){
var _a6=document.getElementsByTagName("script");
var _a7=/(__package__|dojo|bootstrap1)\.js([\?\.]|$)/i;
for(var i=0;i&lt;_a6.length;i++){
var src=_a6[i].getAttribute("src");
if(!src){
continue;
}
var m=src.match(_a7);
if(m){
var _ab=src.substring(0,m.index);
if(src.indexOf("bootstrap1")&gt;-1){
_ab+="../";
}
if(!this["djConfig"]){
djConfig={};
}
if(djConfig["baseScriptUri"]==""){
djConfig["baseScriptUri"]=_ab;
}
if(djConfig["baseRelativePath"]==""){
djConfig["baseRelativePath"]=_ab;
}
break;
}
}
}
var dr=dojo.render;
var drh=dojo.render.html;
var drs=dojo.render.svg;
var dua=(drh.UA=navigator.userAgent);
var dav=(drh.AV=navigator.appVersion);
var t=true;
var f=false;
drh.capable=t;
drh.support.builtin=t;
dr.ver=parseFloat(drh.AV);
dr.os.mac=dav.indexOf("Macintosh")&gt;=0;
dr.os.win=dav.indexOf("Windows")&gt;=0;
dr.os.linux=dav.indexOf("X11")&gt;=0;
drh.opera=dua.indexOf("Opera")&gt;=0;
drh.khtml=(dav.indexOf("Konqueror")&gt;=0)||(dav.indexOf("Safari")&gt;=0);
drh.safari=dav.indexOf("Safari")&gt;=0;
var _b3=dua.indexOf("Gecko");
drh.mozilla=drh.moz=(_b3&gt;=0)&amp;&amp;(!drh.khtml);
if(drh.mozilla){
drh.geckoVersion=dua.substring(_b3+6,_b3+14);
}
drh.ie=(document.all)&amp;&amp;(!drh.opera);
drh.ie50=drh.ie&amp;&amp;dav.indexOf("MSIE 5.0")&gt;=0;
drh.ie55=drh.ie&amp;&amp;dav.indexOf("MSIE 5.5")&gt;=0;
drh.ie60=drh.ie&amp;&amp;dav.indexOf("MSIE 6.0")&gt;=0;
drh.ie70=drh.ie&amp;&amp;dav.indexOf("MSIE 7.0")&gt;=0;
var cm=document["compatMode"];
drh.quirks=(cm=="BackCompat")||(cm=="QuirksMode")||drh.ie55||drh.ie50;
dojo.locale=dojo.locale||(drh.ie?navigator.userLanguage:navigator.language).toLowerCase();
dr.vml.capable=drh.ie;
drs.capable=f;
drs.support.plugin=f;
drs.support.builtin=f;
var _b5=window["document"];
var tdi=_b5["implementation"];
if((tdi)&amp;&amp;(tdi["hasFeature"])&amp;&amp;(tdi.hasFeature("org.w3c.dom.svg","1.0"))){
drs.capable=t;
drs.support.builtin=t;
drs.support.plugin=f;
}
if(drh.safari){
var tmp=dua.split("AppleWebKit/")[1];
var ver=parseFloat(tmp.split(" ")[0]);
if(ver&gt;=420){
drs.capable=t;
drs.support.builtin=t;
drs.support.plugin=f;
}
}else{
}
})();
dojo.hostenv.startPackage("dojo.hostenv");
dojo.render.name=dojo.hostenv.name_="browser";
dojo.hostenv.searchIds=[];
dojo.hostenv._XMLHTTP_PROGIDS=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"];
dojo.hostenv.getXmlhttpObject=function(){
var _b9=null;
var _ba=null;
try{
_b9=new XMLHttpRequest();
}
catch(e){
}
if(!_b9){
for(var i=0;i&lt;3;++i){
var _bc=dojo.hostenv._XMLHTTP_PROGIDS[i];
try{
_b9=new ActiveXObject(_bc);
}
catch(e){
_ba=e;
}
if(_b9){
dojo.hostenv._XMLHTTP_PROGIDS=[_bc];
break;
}
}
}
if(!_b9){
return dojo.raise("XMLHTTP not available",_ba);
}
return _b9;
};
dojo.hostenv._blockAsync=false;
dojo.hostenv.getText=function(uri,_be,_bf){
if(!_be){
this._blockAsync=true;
}
var _c0=this.getXmlhttpObject();
function isDocumentOk(_c1){
var _c2=_c1["status"];
return Boolean((!_c2)||((200&lt;=_c2)&amp;&amp;(300&gt;_c2))||(_c2==304));
}
if(_be){
var _c3=this,_c4=null,gbl=dojo.global();
var xhr=dojo.evalObjPath("dojo.io.XMLHTTPTransport");
_c0.onreadystatechange=function(){
if(_c4){
gbl.clearTimeout(_c4);
_c4=null;
}
if(_c3._blockAsync||(xhr&amp;&amp;xhr._blockAsync)){
_c4=gbl.setTimeout(function(){
_c0.onreadystatechange.apply(this);
},10);
}else{
if(4==_c0.readyState){
if(isDocumentOk(_c0)){
_be(_c0.responseText);
}
}
}
};
}
_c0.open("GET",uri,_be?true:false);
try{
_c0.send(null);
if(_be){
return null;
}
if(!isDocumentOk(_c0)){
var err=Error("Unable to load "+uri+" status:"+_c0.status);
err.status=_c0.status;
err.responseText=_c0.responseText;
throw err;
}
}
catch(e){
this._blockAsync=false;
if((_bf)&amp;&amp;(!_be)){
return null;
}else{
throw e;
}
}
this._blockAsync=false;
return _c0.responseText;
};
dojo.hostenv.defaultDebugContainerId="dojoDebug";
dojo.hostenv._println_buffer=[];
dojo.hostenv._println_safe=false;
dojo.hostenv.println=function(_c8){
if(!dojo.hostenv._println_safe){
dojo.hostenv._println_buffer.push(_c8);
}else{
try{
var _c9=document.getElementById(djConfig.debugContainerId?djConfig.debugContainerId:dojo.hostenv.defaultDebugContainerId);
if(!_c9){
_c9=dojo.body();
}
var div=document.createElement("div");
div.appendChild(document.createTextNode(_c8));
_c9.appendChild(div);
}
catch(e){
try{
document.write("&lt;div&gt;"+_c8+"&lt;/div&gt;");
}
catch(e2){
window.status=_c8;
}
}
}
};
dojo.addOnLoad(function(){
dojo.hostenv._println_safe=true;
while(dojo.hostenv._println_buffer.length&gt;0){
dojo.hostenv.println(dojo.hostenv._println_buffer.shift());
}
});
function dj_addNodeEvtHdlr(_cb,_cc,fp){
var _ce=_cb["on"+_cc]||function(){
};
_cb["on"+_cc]=function(){
fp.apply(_cb,arguments);
_ce.apply(_cb,arguments);
};
return true;
}
dojo.hostenv._djInitFired=false;
function dj_load_init(e){
dojo.hostenv._djInitFired=true;
var _d0=(e&amp;&amp;e.type)?e.type.toLowerCase():"load";
if(arguments.callee.initialized||(_d0!="domcontentloaded"&amp;&amp;_d0!="load")){
return;
}
arguments.callee.initialized=true;
if(typeof (_timer)!="undefined"){
clearInterval(_timer);
delete _timer;
}
var _d1=function(){
if(dojo.render.html.ie){
dojo.hostenv.makeWidgets();
}
};
if(dojo.hostenv.inFlightCount==0){
_d1();
dojo.hostenv.modulesLoaded();
}else{
dojo.hostenv.modulesLoadedListeners.unshift(_d1);
}
}
if(document.addEventListener){
if(dojo.render.html.opera||(dojo.render.html.moz&amp;&amp;(djConfig["enableMozDomContentLoaded"]===true))){
document.addEventListener("DOMContentLoaded",dj_load_init,null);
}
window.addEventListener("load",dj_load_init,null);
}
if(dojo.render.html.ie&amp;&amp;dojo.render.os.win){
document.attachEvent("onreadystatechange",function(e){
if(document.readyState=="complete"){
dj_load_init();
}
});
}
if(/(WebKit|khtml)/i.test(navigator.userAgent)){
var _timer=setInterval(function(){
if(/loaded|complete/.test(document.readyState)){
dj_load_init();
}
},10);
}
if(dojo.render.html.ie){
dj_addNodeEvtHdlr(window,"beforeunload",function(){
dojo.hostenv._unloading=true;
window.setTimeout(function(){
dojo.hostenv._unloading=false;
},0);
});
}
dj_addNodeEvtHdlr(window,"unload",function(){
dojo.hostenv.unloaded();
if((!dojo.render.html.ie)||(dojo.render.html.ie&amp;&amp;dojo.hostenv._unloading)){
dojo.hostenv.unloaded();
}
});
dojo.hostenv.makeWidgets=function(){
var _d3=[];
if(djConfig.searchIds&amp;&amp;djConfig.searchIds.length&gt;0){
_d3=_d3.concat(djConfig.searchIds);
}
if(dojo.hostenv.searchIds&amp;&amp;dojo.hostenv.searchIds.length&gt;0){
_d3=_d3.concat(dojo.hostenv.searchIds);
}
if((djConfig.parseWidgets)||(_d3.length&gt;0)){
if(dojo.evalObjPath("dojo.widget.Parse")){
var _d4=new dojo.xml.Parse();
if(_d3.length&gt;0){
for(var x=0;x&lt;_d3.length;x++){
var _d6=document.getElementById(_d3[x]);
if(!_d6){
continue;
}
var _d7=_d4.parseElement(_d6,null,true);
dojo.widget.getParser().createComponents(_d7);
}
}else{
if(djConfig.parseWidgets){
var _d7=_d4.parseElement(dojo.body(),null,true);
dojo.widget.getParser().createComponents(_d7);
}
}
}
}
};
dojo.addOnLoad(function(){
if(!dojo.render.html.ie){
dojo.hostenv.makeWidgets();
}
});
try{
if(dojo.render.html.ie){
document.namespaces.add("v","urn:schemas-microsoft-com:vml");
document.createStyleSheet().addRule("v\\:*","behavior:url(#default#VML)");
}
}
catch(e){
}
dojo.hostenv.writeIncludes=function(){
};
if(!dj_undef("document",this)){
dj_currentDocument=this.document;
}
dojo.doc=function(){
return dj_currentDocument;
};
dojo.body=function(){
return dojo.doc().body||dojo.doc().getElementsByTagName("body")[0];
};
dojo.byId=function(id,doc){
if((id)&amp;&amp;((typeof id=="string")||(id instanceof String))){
if(!doc){
doc=dj_currentDocument;
}
var ele=doc.getElementById(id);
if(ele&amp;&amp;(ele.id!=id)&amp;&amp;doc.all){
ele=null;
eles=doc.all[id];
if(eles){
if(eles.length){
for(var i=0;i&lt;eles.length;i++){
if(eles[i].id==id){
ele=eles[i];
break;
}
}
}else{
ele=eles;
}
}
}
return ele;
}
return id;
};
dojo.setContext=function(_dc,_dd){
dj_currentContext=_dc;
dj_currentDocument=_dd;
};
dojo._fireCallback=function(_de,_df,_e0){
if((_df)&amp;&amp;((typeof _de=="string")||(_de instanceof String))){
_de=_df[_de];
}
return (_df?_de.apply(_df,_e0||[]):_de());
};
dojo.withGlobal=function(_e1,_e2,_e3,_e4){
var _e5;
var _e6=dj_currentContext;
var _e7=dj_currentDocument;
try{
dojo.setContext(_e1,_e1.document);
_e5=dojo._fireCallback(_e2,_e3,_e4);
}
finally{
dojo.setContext(_e6,_e7);
}
return _e5;
};
dojo.withDoc=function(_e8,_e9,_ea,_eb){
var _ec;
var _ed=dj_currentDocument;
try{
dj_currentDocument=_e8;
_ec=dojo._fireCallback(_e9,_ea,_eb);
}
finally{
dj_currentDocument=_ed;
}
return _ec;
};
}
dojo.requireIf((djConfig["isDebug"]||djConfig["debugAtAllCosts"]),"dojo.debug");
dojo.requireIf(djConfig["debugAtAllCosts"]&amp;&amp;!window.widget&amp;&amp;!djConfig["useXDomain"],"dojo.browser_debug");
dojo.requireIf(djConfig["debugAtAllCosts"]&amp;&amp;!window.widget&amp;&amp;djConfig["useXDomain"],"dojo.browser_debug_xd");
dojo.provide("dojo.string.common");
dojo.string.trim=function(str,wh){
if(!str.replace){
return str;
}
if(!str.length){
return str;
}
var re=(wh&gt;0)?(/^\s+/):(wh&lt;0)?(/\s+$/):(/^\s+|\s+$/g);
return str.replace(re,"");
};
dojo.string.trimStart=function(str){
return dojo.string.trim(str,1);
};
dojo.string.trimEnd=function(str){
return dojo.string.trim(str,-1);
};
dojo.string.repeat=function(str,_f4,_f5){
var out="";
for(var i=0;i&lt;_f4;i++){
out+=str;
if(_f5&amp;&amp;i&lt;_f4-1){
out+=_f5;
}
}
return out;
};
dojo.string.pad=function(str,len,c,dir){
var out=String(str);
if(!c){
c="0";
}
if(!dir){
dir=1;
}
while(out.length&lt;len){
if(dir&gt;0){
out=c+out;
}else{
out+=c;
}
}
return out;
};
dojo.string.padLeft=function(str,len,c){
return dojo.string.pad(str,len,c,1);
};
dojo.string.padRight=function(str,len,c){
return dojo.string.pad(str,len,c,-1);
};
dojo.provide("dojo.string");
dojo.provide("dojo.lang.common");
dojo.lang.inherits=function(_103,_104){
if(!dojo.lang.isFunction(_104)){
dojo.raise("dojo.inherits: superclass argument ["+_104+"] must be a function (subclass: ["+_103+"']");
}
_103.prototype=new _104();
_103.prototype.constructor=_103;
_103.superclass=_104.prototype;
_103["super"]=_104.prototype;
};
dojo.lang._mixin=function(obj,_106){
var tobj={};
for(var x in _106){
if((typeof tobj[x]=="undefined")||(tobj[x]!=_106[x])){
obj[x]=_106[x];
}
}
if(dojo.render.html.ie&amp;&amp;(typeof (_106["toString"])=="function")&amp;&amp;(_106["toString"]!=obj["toString"])&amp;&amp;(_106["toString"]!=tobj["toString"])){
obj.toString=_106.toString;
}
return obj;
};
dojo.lang.mixin=function(obj,_10a){
for(var i=1,l=arguments.length;i&lt;l;i++){
dojo.lang._mixin(obj,arguments[i]);
}
return obj;
};
dojo.lang.extend=function(_10d,_10e){
for(var i=1,l=arguments.length;i&lt;l;i++){
dojo.lang._mixin(_10d.prototype,arguments[i]);
}
return _10d;
};
dojo.inherits=dojo.lang.inherits;
dojo.mixin=dojo.lang.mixin;
dojo.extend=dojo.lang.extend;
dojo.lang.find=function(_111,_112,_113,_114){
if(!dojo.lang.isArrayLike(_111)&amp;&amp;dojo.lang.isArrayLike(_112)){
dojo.deprecated("dojo.lang.find(value, array)","use dojo.lang.find(array, value) instead","0.5");
var temp=_111;
_111=_112;
_112=temp;
}
var _116=dojo.lang.isString(_111);
if(_116){
_111=_111.split("");
}
if(_114){
var step=-1;
var i=_111.length-1;
var end=-1;
}else{
var step=1;
var i=0;
var end=_111.length;
}
if(_113){
while(i!=end){
if(_111[i]===_112){
return i;
}
i+=step;
}
}else{
while(i!=end){
if(_111[i]==_112){
return i;
}
i+=step;
}
}
return -1;
};
dojo.lang.indexOf=dojo.lang.find;
dojo.lang.findLast=function(_11a,_11b,_11c){
return dojo.lang.find(_11a,_11b,_11c,true);
};
dojo.lang.lastIndexOf=dojo.lang.findLast;
dojo.lang.inArray=function(_11d,_11e){
return dojo.lang.find(_11d,_11e)&gt;-1;
};
dojo.lang.isObject=function(it){
if(typeof it=="undefined"){
return false;
}
return (typeof it=="object"||it===null||dojo.lang.isArray(it)||dojo.lang.isFunction(it));
};
dojo.lang.isArray=function(it){
return (it&amp;&amp;it instanceof Array||typeof it=="array");
};
dojo.lang.isArrayLike=function(it){
if((!it)||(dojo.lang.isUndefined(it))){
return false;
}
if(dojo.lang.isString(it)){
return false;
}
if(dojo.lang.isFunction(it)){
return false;
}
if(dojo.lang.isArray(it)){
return true;
}
if((it.tagName)&amp;&amp;(it.tagName.toLowerCase()=="form")){
return false;
}
if(dojo.lang.isNumber(it.length)&amp;&amp;isFinite(it.length)){
return true;
}
return false;
};
dojo.lang.isFunction=function(it){
return (it instanceof Function||typeof it=="function");
};
(function(){
if((dojo.render.html.capable)&amp;&amp;(dojo.render.html["safari"])){
dojo.lang.isFunction=function(it){
if((typeof (it)=="function")&amp;&amp;(it=="[object NodeList]")){
return false;
}
return (it instanceof Function||typeof it=="function");
};
}
})();
dojo.lang.isString=function(it){
return (typeof it=="string"||it instanceof String);
};
dojo.lang.isAlien=function(it){
if(!it){
return false;
}
return !dojo.lang.isFunction(it)&amp;&amp;/\{\s*\[native code\]\s*\}/.test(String(it));
};
dojo.lang.isBoolean=function(it){
return (it instanceof Boolean||typeof it=="boolean");
};
dojo.lang.isNumber=function(it){
return (it instanceof Number||typeof it=="number");
};
dojo.lang.isUndefined=function(it){
return ((typeof (it)=="undefined")&amp;&amp;(it==undefined));
};
dojo.provide("dojo.lang.extras");
dojo.lang.setTimeout=function(func,_12a){
var _12b=window,_12c=2;
if(!dojo.lang.isFunction(func)){
_12b=func;
func=_12a;
_12a=arguments[2];
_12c++;
}
if(dojo.lang.isString(func)){
func=_12b[func];
}
var args=[];
for(var i=_12c;i&lt;arguments.length;i++){
args.push(arguments[i]);
}
return dojo.global().setTimeout(function(){
func.apply(_12b,args);
},_12a);
};
dojo.lang.clearTimeout=function(_12f){
dojo.global().clearTimeout(_12f);
};
dojo.lang.getNameInObj=function(ns,item){
if(!ns){
ns=dj_global;
}
for(var x in ns){
if(ns[x]===item){
return new String(x);
}
}
return null;
};
dojo.lang.shallowCopy=function(obj,deep){
var i,ret;
if(obj===null){
return null;
}
if(dojo.lang.isObject(obj)){
ret=new obj.constructor();
for(i in obj){
if(dojo.lang.isUndefined(ret[i])){
ret[i]=deep?dojo.lang.shallowCopy(obj[i],deep):obj[i];
}
}
}else{
if(dojo.lang.isArray(obj)){
ret=[];
for(i=0;i&lt;obj.length;i++){
ret[i]=deep?dojo.lang.shallowCopy(obj[i],deep):obj[i];
}
}else{
ret=obj;
}
}
return ret;
};
dojo.lang.firstValued=function(){
for(var i=0;i&lt;arguments.length;i++){
if(typeof arguments[i]!="undefined"){
return arguments[i];
}
}
return undefined;
};
dojo.lang.getObjPathValue=function(_138,_139,_13a){
with(dojo.parseObjPath(_138,_139,_13a)){
return dojo.evalProp(prop,obj,_13a);
}
};
dojo.lang.setObjPathValue=function(_13b,_13c,_13d,_13e){
dojo.deprecated("dojo.lang.setObjPathValue","use dojo.parseObjPath and the '=' operator","0.6");
if(arguments.length&lt;4){
_13e=true;
}
with(dojo.parseObjPath(_13b,_13d,_13e)){
if(obj&amp;&amp;(_13e||(prop in obj))){
obj[prop]=_13c;
}
}
};
dojo.provide("dojo.io.common");
dojo.io.transports=[];
dojo.io.hdlrFuncNames=["load","error","timeout"];
dojo.io.Request=function(url,_140,_141,_142){
if((arguments.length==1)&amp;&amp;(arguments[0].constructor==Object)){
this.fromKwArgs(arguments[0]);
}else{
this.url=url;
if(_140){
this.mimetype=_140;
}
if(_141){
this.transport=_141;
}
if(arguments.length&gt;=4){
this.changeUrl=_142;
}
}
};
dojo.lang.extend(dojo.io.Request,{url:"",mimetype:"text/plain",method:"GET",content:undefined,transport:undefined,changeUrl:undefined,formNode:undefined,sync:false,bindSuccess:false,useCache:false,preventCache:false,jsonFilter:function(_143){
if((this.mimetype=="text/json-comment-filtered")||(this.mimetype=="application/json-comment-filtered")){
var _144=_143.indexOf("/*");
var _145=_143.lastIndexOf("*/");
if((_144==-1)||(_145==-1)){
dojo.debug("your JSON wasn't comment filtered!");
return "";
}
return _143.substring(_144+2,_145);
}
dojo.debug("please consider using a mimetype of text/json-comment-filtered to avoid potential security issues with JSON endpoints");
return _143;
},load:function(type,data,_148,_149){
},error:function(type,_14b,_14c,_14d){
},timeout:function(type,_14f,_150,_151){
},handle:function(type,data,_154,_155){
},timeoutSeconds:0,abort:function(){
},fromKwArgs:function(_156){
if(_156["url"]){
_156.url=_156.url.toString();
}
if(_156["formNode"]){
_156.formNode=dojo.byId(_156.formNode);
}
if(!_156["method"]&amp;&amp;_156["formNode"]&amp;&amp;_156["formNode"].method){
_156.method=_156["formNode"].method;
}
if(!_156["handle"]&amp;&amp;_156["handler"]){
_156.handle=_156.handler;
}
if(!_156["load"]&amp;&amp;_156["loaded"]){
_156.load=_156.loaded;
}
if(!_156["changeUrl"]&amp;&amp;_156["changeURL"]){
_156.changeUrl=_156.changeURL;
}
_156.encoding=dojo.lang.firstValued(_156["encoding"],djConfig["bindEncoding"],"");
_156.sendTransport=dojo.lang.firstValued(_156["sendTransport"],djConfig["ioSendTransport"],false);
var _157=dojo.lang.isFunction;
for(var x=0;x&lt;dojo.io.hdlrFuncNames.length;x++){
var fn=dojo.io.hdlrFuncNames[x];
if(_156[fn]&amp;&amp;_157(_156[fn])){
continue;
}
if(_156["handle"]&amp;&amp;_157(_156["handle"])){
_156[fn]=_156.handle;
}
}
dojo.lang.mixin(this,_156);
}});
dojo.io.Error=function(msg,type,num){
this.message=msg;
this.type=type||"unknown";
this.number=num||0;
};
dojo.io.transports.addTransport=function(name){
this.push(name);
this[name]=dojo.io[name];
};
dojo.io.bind=function(_15e){
if(!(_15e instanceof dojo.io.Request)){
try{
_15e=new dojo.io.Request(_15e);
}
catch(e){
dojo.debug(e);
}
}
var _15f="";
if(_15e["transport"]){
_15f=_15e["transport"];
if(!this[_15f]){
dojo.io.sendBindError(_15e,"No dojo.io.bind() transport with name '"+_15e["transport"]+"'.");
return _15e;
}
if(!this[_15f].canHandle(_15e)){
dojo.io.sendBindError(_15e,"dojo.io.bind() transport with name '"+_15e["transport"]+"' cannot handle this type of request.");
return _15e;
}
}else{
for(var x=0;x&lt;dojo.io.transports.length;x++){
var tmp=dojo.io.transports[x];
if((this[tmp])&amp;&amp;(this[tmp].canHandle(_15e))){
_15f=tmp;
break;
}
}
if(_15f==""){
dojo.io.sendBindError(_15e,"None of the loaded transports for dojo.io.bind()"+" can handle the request.");
return _15e;
}
}
this[_15f].bind(_15e);
_15e.bindSuccess=true;
return _15e;
};
dojo.io.sendBindError=function(_162,_163){
if((typeof _162.error=="function"||typeof _162.handle=="function")&amp;&amp;(typeof setTimeout=="function"||typeof setTimeout=="object")){
var _164=new dojo.io.Error(_163);
setTimeout(function(){
_162[(typeof _162.error=="function")?"error":"handle"]("error",_164,null,_162);
},50);
}else{
dojo.raise(_163);
}
};
dojo.io.queueBind=function(_165){
if(!(_165 instanceof dojo.io.Request)){
try{
_165=new dojo.io.Request(_165);
}
catch(e){
dojo.debug(e);
}
}
var _166=_165.load;
_165.load=function(){
dojo.io._queueBindInFlight=false;
var ret=_166.apply(this,arguments);
dojo.io._dispatchNextQueueBind();
return ret;
};
var _168=_165.error;
_165.error=function(){
dojo.io._queueBindInFlight=false;
var ret=_168.apply(this,arguments);
dojo.io._dispatchNextQueueBind();
return ret;
};
dojo.io._bindQueue.push(_165);
dojo.io._dispatchNextQueueBind();
return _165;
};
dojo.io._dispatchNextQueueBind=function(){
if(!dojo.io._queueBindInFlight){
dojo.io._queueBindInFlight=true;
if(dojo.io._bindQueue.length&gt;0){
dojo.io.bind(dojo.io._bindQueue.shift());
}else{
dojo.io._queueBindInFlight=false;
}
}
};
dojo.io._bindQueue=[];
dojo.io._queueBindInFlight=false;
dojo.io.argsFromMap=function(map,_16b,last){
var enc=/utf/i.test(_16b||"")?encodeURIComponent:dojo.string.encodeAscii;
var _16e=[];
var _16f=new Object();
for(var name in map){
var _171=function(elt){
var val=enc(name)+"="+enc(elt);
_16e[(last==name)?"push":"unshift"](val);
};
if(!_16f[name]){
var _174=map[name];
if(dojo.lang.isArray(_174)){
dojo.lang.forEach(_174,_171);
}else{
_171(_174);
}
}
}
return _16e.join("&amp;");
};
dojo.io.setIFrameSrc=function(_175,src,_177){
try{
var r=dojo.render.html;
if(!_177){
if(r.safari){
_175.location=src;
}else{
frames[_175.name].location=src;
}
}else{
var idoc;
if(r.ie){
idoc=_175.contentWindow.document;
}else{
if(r.safari){
idoc=_175.document;
}else{
idoc=_175.contentWindow;
}
}
if(!idoc){
_175.location=src;
return;
}else{
idoc.location.replace(src);
}
}
}
catch(e){
dojo.debug(e);
dojo.debug("setIFrameSrc: "+e);
}
};
dojo.provide("dojo.lang.array");
dojo.lang.mixin(dojo.lang,{has:function(obj,name){
try{
return typeof obj[name]!="undefined";
}
catch(e){
return false;
}
},isEmpty:function(obj){
if(dojo.lang.isObject(obj)){
var tmp={};
var _17e=0;
for(var x in obj){
if(obj[x]&amp;&amp;(!tmp[x])){
_17e++;
break;
}
}
return _17e==0;
}else{
if(dojo.lang.isArrayLike(obj)||dojo.lang.isString(obj)){
return obj.length==0;
}
}
},map:function(arr,obj,_182){
var _183=dojo.lang.isString(arr);
if(_183){
arr=arr.split("");
}
if(dojo.lang.isFunction(obj)&amp;&amp;(!_182)){
_182=obj;
obj=dj_global;
}else{
if(dojo.lang.isFunction(obj)&amp;&amp;_182){
var _184=obj;
obj=_182;
_182=_184;
}
}
if(Array.map){
var _185=Array.map(arr,_182,obj);
}else{
var _185=[];
for(var i=0;i&lt;arr.length;++i){
_185.push(_182.call(obj,arr[i]));
}
}
if(_183){
return _185.join("");
}else{
return _185;
}
},reduce:function(arr,_188,obj,_18a){
var _18b=_188;
if(arguments.length==2){
_18a=_188;
_18b=arr[0];
arr=arr.slice(1);
}else{
if(arguments.length==3){
if(dojo.lang.isFunction(obj)){
_18a=obj;
obj=null;
}
}else{
if(dojo.lang.isFunction(obj)){
var tmp=_18a;
_18a=obj;
obj=tmp;
}
}
}
var ob=obj||dj_global;
dojo.lang.map(arr,function(val){
_18b=_18a.call(ob,_18b,val);
});
return _18b;
},forEach:function(_18f,_190,_191){
if(dojo.lang.isString(_18f)){
_18f=_18f.split("");
}
if(Array.forEach){
Array.forEach(_18f,_190,_191);
}else{
if(!_191){
_191=dj_global;
}
for(var i=0,l=_18f.length;i&lt;l;i++){
_190.call(_191,_18f[i],i,_18f);
}
}
},_everyOrSome:function(_194,arr,_196,_197){
if(dojo.lang.isString(arr)){
arr=arr.split("");
}
if(Array.every){
return Array[_194?"every":"some"](arr,_196,_197);
}else{
if(!_197){
_197=dj_global;
}
for(var i=0,l=arr.length;i&lt;l;i++){
var _19a=_196.call(_197,arr[i],i,arr);
if(_194&amp;&amp;!_19a){
return false;
}else{
if((!_194)&amp;&amp;(_19a)){
return true;
}
}
}
return Boolean(_194);
}
},every:function(arr,_19c,_19d){
return this._everyOrSome(true,arr,_19c,_19d);
},some:function(arr,_19f,_1a0){
return this._everyOrSome(false,arr,_19f,_1a0);
},filter:function(arr,_1a2,_1a3){
var _1a4=dojo.lang.isString(arr);
if(_1a4){
arr=arr.split("");
}
var _1a5;
if(Array.filter){
_1a5=Array.filter(arr,_1a2,_1a3);
}else{
if(!_1a3){
if(arguments.length&gt;=3){
dojo.raise("thisObject doesn't exist!");
}
_1a3=dj_global;
}
_1a5=[];
for(var i=0;i&lt;arr.length;i++){
if(_1a2.call(_1a3,arr[i],i,arr)){
_1a5.push(arr[i]);
}
}
}
if(_1a4){
return _1a5.join("");
}else{
return _1a5;
}
},unnest:function(){
var out=[];
for(var i=0;i&lt;arguments.length;i++){
if(dojo.lang.isArrayLike(arguments[i])){
var add=dojo.lang.unnest.apply(this,arguments[i]);
out=out.concat(add);
}else{
out.push(arguments[i]);
}
}
return out;
},toArray:function(_1aa,_1ab){
var _1ac=[];
for(var i=_1ab||0;i&lt;_1aa.length;i++){
_1ac.push(_1aa[i]);
}
return _1ac;
}});
dojo.provide("dojo.lang.func");
dojo.lang.hitch=function(_1ae,_1af){
var args=[];
for(var x=2;x&lt;arguments.length;x++){
args.push(arguments[x]);
}
var fcn=(dojo.lang.isString(_1af)?_1ae[_1af]:_1af)||function(){
};
return function(){
var ta=args.concat([]);
for(var x=0;x&lt;arguments.length;x++){
ta.push(arguments[x]);
}
return fcn.apply(_1ae,ta);
};
};
dojo.lang.anonCtr=0;
dojo.lang.anon={};
dojo.lang.nameAnonFunc=function(_1b5,_1b6,_1b7){
var nso=(_1b6||dojo.lang.anon);
if((_1b7)||((dj_global["djConfig"])&amp;&amp;(djConfig["slowAnonFuncLookups"]==true))){
for(var x in nso){
try{
if(nso[x]===_1b5){
return x;
}
}
catch(e){
}
}
}
var ret="__"+dojo.lang.anonCtr++;
while(typeof nso[ret]!="undefined"){
ret="__"+dojo.lang.anonCtr++;
}
nso[ret]=_1b5;
return ret;
};
dojo.lang.forward=function(_1bb){
return function(){
return this[_1bb].apply(this,arguments);
};
};
dojo.lang.curry=function(_1bc,func){
var _1be=[];
_1bc=_1bc||dj_global;
if(dojo.lang.isString(func)){
func=_1bc[func];
}
for(var x=2;x&lt;arguments.length;x++){
_1be.push(arguments[x]);
}
var _1c0=(func["__preJoinArity"]||func.length)-_1be.length;
function gather(_1c1,_1c2,_1c3){
var _1c4=_1c3;
var _1c5=_1c2.slice(0);
for(var x=0;x&lt;_1c1.length;x++){
_1c5.push(_1c1[x]);
}
_1c3=_1c3-_1c1.length;
if(_1c3&lt;=0){
var res=func.apply(_1bc,_1c5);
_1c3=_1c4;
return res;
}else{
return function(){
return gather(arguments,_1c5,_1c3);
};
}
}
return gather([],_1be,_1c0);
};
dojo.lang.curryArguments=function(_1c8,func,args,_1cb){
var _1cc=[];
var x=_1cb||0;
for(x=_1cb;x&lt;args.length;x++){
_1cc.push(args[x]);
}
return dojo.lang.curry.apply(dojo.lang,[_1c8,func].concat(_1cc));
};
dojo.lang.tryThese=function(){
for(var x=0;x&lt;arguments.length;x++){
try{
if(typeof arguments[x]=="function"){
var ret=(arguments[x]());
if(ret){
return ret;
}
}
}
catch(e){
dojo.debug(e);
}
}
};
dojo.lang.delayThese=function(farr,cb,_1d2,_1d3){
if(!farr.length){
if(typeof _1d3=="function"){
_1d3();
}
return;
}
if((typeof _1d2=="undefined")&amp;&amp;(typeof cb=="number")){
_1d2=cb;
cb=function(){
};
}else{
if(!cb){
cb=function(){
};
if(!_1d2){
_1d2=0;
}
}
}
setTimeout(function(){
(farr.shift())();
cb();
dojo.lang.delayThese(farr,cb,_1d2,_1d3);
},_1d2);
};
dojo.provide("dojo.string.extras");
dojo.string.substituteParams=function(_1d4,hash){
var map=(typeof hash=="object")?hash:dojo.lang.toArray(arguments,1);
return _1d4.replace(/\%\{(\w+)\}/g,function(_1d7,key){
if(typeof (map[key])!="undefined"&amp;&amp;map[key]!=null){
return map[key];
}
dojo.raise("Substitution not found: "+key);
});
};
dojo.string.capitalize=function(str){
if(!dojo.lang.isString(str)){
return "";
}
if(arguments.length==0){
str=this;
}
var _1da=str.split(" ");
for(var i=0;i&lt;_1da.length;i++){
_1da[i]=_1da[i].charAt(0).toUpperCase()+_1da[i].substring(1);
}
return _1da.join(" ");
};
dojo.string.isBlank=function(str){
if(!dojo.lang.isString(str)){
return true;
}
return (dojo.string.trim(str).length==0);
};
dojo.string.encodeAscii=function(str){
if(!dojo.lang.isString(str)){
return str;
}
var ret="";
var _1df=escape(str);
var _1e0,re=/%u([0-9A-F]{4})/i;
while((_1e0=_1df.match(re))){
var num=Number("0x"+_1e0[1]);
var _1e3=escape("&amp;#"+num+";");
ret+=_1df.substring(0,_1e0.index)+_1e3;
_1df=_1df.substring(_1e0.index+_1e0[0].length);
}
ret+=_1df.replace(/\+/g,"%2B");
return ret;
};
dojo.string.escape=function(type,str){
var args=dojo.lang.toArray(arguments,1);
switch(type.toLowerCase()){
case "xml":
case "html":
case "xhtml":
return dojo.string.escapeXml.apply(this,args);
case "sql":
return dojo.string.escapeSql.apply(this,args);
case "regexp":
case "regex":
return dojo.string.escapeRegExp.apply(this,args);
case "javascript":
case "jscript":
case "js":
return dojo.string.escapeJavaScript.apply(this,args);
case "ascii":
return dojo.string.encodeAscii.apply(this,args);
default:
return str;
}
};
dojo.string.escapeXml=function(str,_1e8){
str=str.replace(/&amp;/gm,"&amp;amp;").replace(/&lt;/gm,"&amp;lt;").replace(/&gt;/gm,"&amp;gt;").replace(/"/gm,"&amp;quot;");
if(!_1e8){
str=str.replace(/'/gm,"&amp;#39;");
}
return str;
};
dojo.string.escapeSql=function(str){
return str.replace(/'/gm,"''");
};
dojo.string.escapeRegExp=function(str){
return str.replace(/\\/gm,"\\\\").replace(/([\f\b\n\t\r[\^$|?*+(){}])/gm,"\\$1");
};
dojo.string.escapeJavaScript=function(str){
return str.replace(/(["'\f\b\n\t\r])/gm,"\\$1");
};
dojo.string.escapeString=function(str){
return ("\""+str.replace(/(["\\])/g,"\\$1")+"\"").replace(/[\f]/g,"\\f").replace(/[\b]/g,"\\b").replace(/[\n]/g,"\\n").replace(/[\t]/g,"\\t").replace(/[\r]/g,"\\r");
};
dojo.string.summary=function(str,len){
if(!len||str.length&lt;=len){
return str;
}
return str.substring(0,len).replace(/\.+$/,"")+"...";
};
dojo.string.endsWith=function(str,end,_1f1){
if(_1f1){
str=str.toLowerCase();
end=end.toLowerCase();
}
if((str.length-end.length)&lt;0){
return false;
}
return str.lastIndexOf(end)==str.length-end.length;
};
dojo.string.endsWithAny=function(str){
for(var i=1;i&lt;arguments.length;i++){
if(dojo.string.endsWith(str,arguments[i])){
return true;
}
}
return false;
};
dojo.string.startsWith=function(str,_1f5,_1f6){
if(_1f6){
str=str.toLowerCase();
_1f5=_1f5.toLowerCase();
}
return str.indexOf(_1f5)==0;
};
dojo.string.startsWithAny=function(str){
for(var i=1;i&lt;arguments.length;i++){
if(dojo.string.startsWith(str,arguments[i])){
return true;
}
}
return false;
};
dojo.string.has=function(str){
for(var i=1;i&lt;arguments.length;i++){
if(str.indexOf(arguments[i])&gt;-1){
return true;
}
}
return false;
};
dojo.string.normalizeNewlines=function(text,_1fc){
if(_1fc=="\n"){
text=text.replace(/\r\n/g,"\n");
text=text.replace(/\r/g,"\n");
}else{
if(_1fc=="\r"){
text=text.replace(/\r\n/g,"\r");
text=text.replace(/\n/g,"\r");
}else{
text=text.replace(/([^\r])\n/g,"$1\r\n").replace(/\r([^\n])/g,"\r\n$1");
}
}
return text;
};
dojo.string.splitEscaped=function(str,_1fe){
var _1ff=[];
for(var i=0,_201=0;i&lt;str.length;i++){
if(str.charAt(i)=="\\"){
i++;
continue;
}
if(str.charAt(i)==_1fe){
_1ff.push(str.substring(_201,i));
_201=i+1;
}
}
_1ff.push(str.substr(_201));
return _1ff;
};
dojo.provide("dojo.dom");
dojo.dom.ELEMENT_NODE=1;
dojo.dom.ATTRIBUTE_NODE=2;
dojo.dom.TEXT_NODE=3;
dojo.dom.CDATA_SECTION_NODE=4;
dojo.dom.ENTITY_REFERENCE_NODE=5;
dojo.dom.ENTITY_NODE=6;
dojo.dom.PROCESSING_INSTRUCTION_NODE=7;
dojo.dom.COMMENT_NODE=8;
dojo.dom.DOCUMENT_NODE=9;
dojo.dom.DOCUMENT_TYPE_NODE=10;
dojo.dom.DOCUMENT_FRAGMENT_NODE=11;
dojo.dom.NOTATION_NODE=12;
dojo.dom.dojoml="http://www.dojotoolkit.org/2004/dojoml";
dojo.dom.xmlns={svg:"http://www.w3.org/2000/svg",smil:"http://www.w3.org/2001/SMIL20/",mml:"http://www.w3.org/1998/Math/MathML",cml:"http://www.xml-cml.org",xlink:"http://www.w3.org/1999/xlink",xhtml:"http://www.w3.org/1999/xhtml",xul:"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",xbl:"http://www.mozilla.org/xbl",fo:"http://www.w3.org/1999/XSL/Format",xsl:"http://www.w3.org/1999/XSL/Transform",xslt:"http://www.w3.org/1999/XSL/Transform",xi:"http://www.w3.org/2001/XInclude",xforms:"http://www.w3.org/2002/01/xforms",saxon:"http://icl.com/saxon",xalan:"http://xml.apache.org/xslt",xsd:"http://www.w3.org/2001/XMLSchema",dt:"http://www.w3.org/2001/XMLSchema-datatypes",xsi:"http://www.w3.org/2001/XMLSchema-instance",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",dc:"http://purl.org/dc/elements/1.1/",dcq:"http://purl.org/dc/qualifiers/1.0","soap-env":"http://schemas.xmlsoap.org/soap/envelope/",wsdl:"http://schemas.xmlsoap.org/wsdl/",AdobeExtensions:"http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"};
dojo.dom.isNode=function(wh){
if(typeof Element=="function"){
try{
return wh instanceof Element;
}
catch(e){
}
}else{
return wh&amp;&amp;!isNaN(wh.nodeType);
}
};
dojo.dom.getUniqueId=function(){
var _203=dojo.doc();
do{
var id="dj_unique_"+(++arguments.callee._idIncrement);
}while(_203.getElementById(id));
return id;
};
dojo.dom.getUniqueId._idIncrement=0;
dojo.dom.firstElement=dojo.dom.getFirstChildElement=function(_205,_206){
var node=_205.firstChild;
while(node&amp;&amp;node.nodeType!=dojo.dom.ELEMENT_NODE){
node=node.nextSibling;
}
if(_206&amp;&amp;node&amp;&amp;node.tagName&amp;&amp;node.tagName.toLowerCase()!=_206.toLowerCase()){
node=dojo.dom.nextElement(node,_206);
}
return node;
};
dojo.dom.lastElement=dojo.dom.getLastChildElement=function(_208,_209){
var node=_208.lastChild;
while(node&amp;&amp;node.nodeType!=dojo.dom.ELEMENT_NODE){
node=node.previousSibling;
}
if(_209&amp;&amp;node&amp;&amp;node.tagName&amp;&amp;node.tagName.toLowerCase()!=_209.toLowerCase()){
node=dojo.dom.prevElement(node,_209);
}
return node;
};
dojo.dom.nextElement=dojo.dom.getNextSiblingElement=function(node,_20c){
if(!node){
return null;
}
do{
node=node.nextSibling;
}while(node&amp;&amp;node.nodeType!=dojo.dom.ELEMENT_NODE);
if(node&amp;&amp;_20c&amp;&amp;_20c.toLowerCase()!=node.tagName.toLowerCase()){
return dojo.dom.nextElement(node,_20c);
}
return node;
};
dojo.dom.prevElement=dojo.dom.getPreviousSiblingElement=function(node,_20e){
if(!node){
return null;
}
if(_20e){
_20e=_20e.toLowerCase();
}
do{
node=node.previousSibling;
}while(node&amp;&amp;node.nodeType!=dojo.dom.ELEMENT_NODE);
if(node&amp;&amp;_20e&amp;&amp;_20e.toLowerCase()!=node.tagName.toLowerCase()){
return dojo.dom.prevElement(node,_20e);
}
return node;
};
dojo.dom.moveChildren=function(_20f,_210,trim){
var _212=0;
if(trim){
while(_20f.hasChildNodes()&amp;&amp;_20f.firstChild.nodeType==dojo.dom.TEXT_NODE){
_20f.removeChild(_20f.firstChild);
}
while(_20f.hasChildNodes()&amp;&amp;_20f.lastChild.nodeType==dojo.dom.TEXT_NODE){
_20f.removeChild(_20f.lastChild);
}
}
while(_20f.hasChildNodes()){
_210.appendChild(_20f.firstChild);
_212++;
}
return _212;
};
dojo.dom.copyChildren=function(_213,_214,trim){
var _216=_213.cloneNode(true);
return this.moveChildren(_216,_214,trim);
};
dojo.dom.replaceChildren=function(node,_218){
var _219=[];
if(dojo.render.html.ie){
for(var i=0;i&lt;node.childNodes.length;i++){
_219.push(node.childNodes[i]);
}
}
dojo.dom.removeChildren(node);
node.appendChild(_218);
for(var i=0;i&lt;_219.length;i++){
dojo.dom.destroyNode(_219[i]);
}
};
dojo.dom.removeChildren=function(node){
var _21c=node.childNodes.length;
while(node.hasChildNodes()){
dojo.dom.removeNode(node.firstChild);
}
return _21c;
};
dojo.dom.replaceNode=function(node,_21e){
return node.parentNode.replaceChild(_21e,node);
};
dojo.dom.destroyNode=function(node){
if(node.parentNode){
node=dojo.dom.removeNode(node);
}
if(node.nodeType!=3){
if(dojo.evalObjPath("dojo.event.browser.clean",false)){
dojo.event.browser.clean(node);
}
if(dojo.render.html.ie){
node.outerHTML="";
}
}
};
dojo.dom.removeNode=function(node){
if(node&amp;&amp;node.parentNode){
return node.parentNode.removeChild(node);
}
};
dojo.dom.getAncestors=function(node,_222,_223){
var _224=[];
var _225=(_222&amp;&amp;(_222 instanceof Function||typeof _222=="function"));
while(node){
if(!_225||_222(node)){
_224.push(node);
}
if(_223&amp;&amp;_224.length&gt;0){
return _224[0];
}
node=node.parentNode;
}
if(_223){
return null;
}
return _224;
};
dojo.dom.getAncestorsByTag=function(node,tag,_228){
tag=tag.toLowerCase();
return dojo.dom.getAncestors(node,function(el){
return ((el.tagName)&amp;&amp;(el.tagName.toLowerCase()==tag));
},_228);
};
dojo.dom.getFirstAncestorByTag=function(node,tag){
return dojo.dom.getAncestorsByTag(node,tag,true);
};
dojo.dom.isDescendantOf=function(node,_22d,_22e){
if(_22e&amp;&amp;node){
node=node.parentNode;
}
while(node){
if(node==_22d){
return true;
}
node=node.parentNode;
}
return false;
};
dojo.dom.innerXML=function(node){
if(node.innerXML){
return node.innerXML;
}else{
if(node.xml){
return node.xml;
}else{
if(typeof XMLSerializer!="undefined"){
return (new XMLSerializer()).serializeToString(node);
}
}
}
};
dojo.dom.createDocument=function(){
var doc=null;
var _231=dojo.doc();
if(!dj_undef("ActiveXObject")){
var _232=["MSXML2","Microsoft","MSXML","MSXML3"];
for(var i=0;i&lt;_232.length;i++){
try{
doc=new ActiveXObject(_232[i]+".XMLDOM");
}
catch(e){
}
if(doc){
break;
}
}
}else{
if((_231.implementation)&amp;&amp;(_231.implementation.createDocument)){
doc=_231.implementation.createDocument("","",null);
}
}
return doc;
};
dojo.dom.createDocumentFromText=function(str,_235){
if(!_235){
_235="text/xml";
}
if(!dj_undef("DOMParser")){
var _236=new DOMParser();
return _236.parseFromString(str,_235);
}else{
if(!dj_undef("ActiveXObject")){
var _237=dojo.dom.createDocument();
if(_237){
_237.async=false;
_237.loadXML(str);
return _237;
}else{
dojo.debug("toXml didn't work?");
}
}else{
var _238=dojo.doc();
if(_238.createElement){
var tmp=_238.createElement("xml");
tmp.innerHTML=str;
if(_238.implementation&amp;&amp;_238.implementation.createDocument){
var _23a=_238.implementation.createDocument("foo","",null);
for(var i=0;i&lt;tmp.childNodes.length;i++){
_23a.importNode(tmp.childNodes.item(i),true);
}
return _23a;
}
return ((tmp.document)&amp;&amp;(tmp.document.firstChild?tmp.document.firstChild:tmp));
}
}
}
return null;
};
dojo.dom.prependChild=function(node,_23d){
if(_23d.firstChild){
_23d.insertBefore(node,_23d.firstChild);
}else{
_23d.appendChild(node);
}
return true;
};
dojo.dom.insertBefore=function(node,ref,_240){
if((_240!=true)&amp;&amp;(node===ref||node.nextSibling===ref)){
return false;
}
var _241=ref.parentNode;
_241.insertBefore(node,ref);
return true;
};
dojo.dom.insertAfter=function(node,ref,_244){
var pn=ref.parentNode;
if(ref==pn.lastChild){
if((_244!=true)&amp;&amp;(node===ref)){
return false;
}
pn.appendChild(node);
}else{
return this.insertBefore(node,ref.nextSibling,_244);
}
return true;
};
dojo.dom.insertAtPosition=function(node,ref,_248){
if((!node)||(!ref)||(!_248)){
return false;
}
switch(_248.toLowerCase()){
case "before":
return dojo.dom.insertBefore(node,ref);
case "after":
return dojo.dom.insertAfter(node,ref);
case "first":
if(ref.firstChild){
return dojo.dom.insertBefore(node,ref.firstChild);
}else{
ref.appendChild(node);
return true;
}
break;
default:
ref.appendChild(node);
return true;
}
};
dojo.dom.insertAtIndex=function(node,_24a,_24b){
var _24c=_24a.childNodes;
if(!_24c.length||_24c.length==_24b){
_24a.appendChild(node);
return true;
}
if(_24b==0){
return dojo.dom.prependChild(node,_24a);
}
return dojo.dom.insertAfter(node,_24c[_24b-1]);
};
dojo.dom.textContent=function(node,text){
if(arguments.length&gt;1){
var _24f=dojo.doc();
dojo.dom.replaceChildren(node,_24f.createTextNode(text));
return text;
}else{
if(node.textContent!=undefined){
return node.textContent;
}
var _250="";
if(node==null){
return _250;
}
for(var i=0;i&lt;node.childNodes.length;i++){
switch(node.childNodes[i].nodeType){
case 1:
case 5:
_250+=dojo.dom.textContent(node.childNodes[i]);
break;
case 3:
case 2:
case 4:
_250+=node.childNodes[i].nodeValue;
break;
default:
break;
}
}
return _250;
}
};
dojo.dom.hasParent=function(node){
return Boolean(node&amp;&amp;node.parentNode&amp;&amp;dojo.dom.isNode(node.parentNode));
};
dojo.dom.isTag=function(node){
if(node&amp;&amp;node.tagName){
for(var i=1;i&lt;arguments.length;i++){
if(node.tagName==String(arguments[i])){
return String(arguments[i]);
}
}
}
return "";
};
dojo.dom.setAttributeNS=function(elem,_256,_257,_258){
if(elem==null||((elem==undefined)&amp;&amp;(typeof elem=="undefined"))){
dojo.raise("No element given to dojo.dom.setAttributeNS");
}
if(!((elem.setAttributeNS==undefined)&amp;&amp;(typeof elem.setAttributeNS=="undefined"))){
elem.setAttributeNS(_256,_257,_258);
}else{
var _259=elem.ownerDocument;
var _25a=_259.createNode(2,_257,_256);
_25a.nodeValue=_258;
elem.setAttributeNode(_25a);
}
};
dojo.provide("dojo.undo.browser");
try{
if((!djConfig["preventBackButtonFix"])&amp;&amp;(!dojo.hostenv.post_load_)){
document.write("&lt;iframe style='border: 0px; width: 1px; height: 1px; position: absolute; bottom: 0px; right: 0px; visibility: visible;' name='djhistory' id='djhistory' src='"+(djConfig["dojoIframeHistoryUrl"]||dojo.hostenv.getBaseScriptUri()+"iframe_history.html")+"'&gt;&lt;/iframe&gt;");
}
}
catch(e){
}
if(dojo.render.html.opera){
dojo.debug("Opera is not supported with dojo.undo.browser, so back/forward detection will not work.");
}
dojo.undo.browser={initialHref:(!dj_undef("window"))?window.location.href:"",initialHash:(!dj_undef("window"))?window.location.hash:"",moveForward:false,historyStack:[],forwardStack:[],historyIframe:null,bookmarkAnchor:null,locationTimer:null,setInitialState:function(args){
this.initialState=this._createState(this.initialHref,args,this.initialHash);
},addToHistory:function(args){
this.forwardStack=[];
var hash=null;
var url=null;
if(!this.historyIframe){
if(djConfig["useXDomain"]&amp;&amp;!djConfig["dojoIframeHistoryUrl"]){
dojo.debug("dojo.undo.browser: When using cross-domain Dojo builds,"+" please save iframe_history.html to your domain and set djConfig.dojoIframeHistoryUrl"+" to the path on your domain to iframe_history.html");
}
this.historyIframe=window.frames["djhistory"];
}
if(!this.bookmarkAnchor){
this.bookmarkAnchor=document.createElement("a");
dojo.body().appendChild(this.bookmarkAnchor);
this.bookmarkAnchor.style.display="none";
}
if(args["changeUrl"]){
hash="#"+((args["changeUrl"]!==true)?args["changeUrl"]:(new Date()).getTime());
if(this.historyStack.length==0&amp;&amp;this.initialState.urlHash==hash){
this.initialState=this._createState(url,args,hash);
return;
}else{
if(this.historyStack.length&gt;0&amp;&amp;this.historyStack[this.historyStack.length-1].urlHash==hash){
this.historyStack[this.historyStack.length-1]=this._createState(url,args,hash);
return;
}
}
this.changingUrl=true;
setTimeout("window.location.href = '"+hash+"'; dojo.undo.browser.changingUrl = false;",1);
this.bookmarkAnchor.href=hash;
if(dojo.render.html.ie){
url=this._loadIframeHistory();
var _25f=args["back"]||args["backButton"]||args["handle"];
var tcb=function(_261){
if(window.location.hash!=""){
setTimeout("window.location.href = '"+hash+"';",1);
}
_25f.apply(this,[_261]);
};
if(args["back"]){
args.back=tcb;
}else{
if(args["backButton"]){
args.backButton=tcb;
}else{
if(args["handle"]){
args.handle=tcb;
}
}
}
var _262=args["forward"]||args["forwardButton"]||args["handle"];
var tfw=function(_264){
if(window.location.hash!=""){
window.location.href=hash;
}
if(_262){
_262.apply(this,[_264]);
}
};
if(args["forward"]){
args.forward=tfw;
}else{
if(args["forwardButton"]){
args.forwardButton=tfw;
}else{
if(args["handle"]){
args.handle=tfw;
}
}
}
}else{
if(dojo.render.html.moz){
if(!this.locationTimer){
this.locationTimer=setInterval("dojo.undo.browser.checkLocation();",200);
}
}
}
}else{
url=this._loadIframeHistory();
}
this.historyStack.push(this._createState(url,args,hash));
},checkLocation:function(){
if(!this.changingUrl){
var hsl=this.historyStack.length;
if((window.location.hash==this.initialHash||window.location.href==this.initialHref)&amp;&amp;(hsl==1)){
this.handleBackButton();
return;
}
if(this.forwardStack.length&gt;0){
if(this.forwardStack[this.forwardStack.length-1].urlHash==window.location.hash){
this.handleForwardButton();
return;
}
}
if((hsl&gt;=2)&amp;&amp;(this.historyStack[hsl-2])){
if(this.historyStack[hsl-2].urlHash==window.location.hash){
this.handleBackButton();
return;
}
}
}
},iframeLoaded:function(evt,_267){
if(!dojo.render.html.opera){
var _268=this._getUrlQuery(_267.href);
if(_268==null){
if(this.historyStack.length==1){
this.handleBackButton();
}
return;
}
if(this.moveForward){
this.moveForward=false;
return;
}
if(this.historyStack.length&gt;=2&amp;&amp;_268==this._getUrlQuery(this.historyStack[this.historyStack.length-2].url)){
this.handleBackButton();
}else{
if(this.forwardStack.length&gt;0&amp;&amp;_268==this._getUrlQuery(this.forwardStack[this.forwardStack.length-1].url)){
this.handleForwardButton();
}
}
}
},handleBackButton:function(){
var _269=this.historyStack.pop();
if(!_269){
return;
}
var last=this.historyStack[this.historyStack.length-1];
if(!last&amp;&amp;this.historyStack.length==0){
last=this.initialState;
}
if(last){
if(last.kwArgs["back"]){
last.kwArgs["back"]();
}else{
if(last.kwArgs["backButton"]){
last.kwArgs["backButton"]();
}else{
if(last.kwArgs["handle"]){
last.kwArgs.handle("back");
}
}
}
}
this.forwardStack.push(_269);
},handleForwardButton:function(){
var last=this.forwardStack.pop();
if(!last){
return;
}
if(last.kwArgs["forward"]){
last.kwArgs.forward();
}else{
if(last.kwArgs["forwardButton"]){
last.kwArgs.forwardButton();
}else{
if(last.kwArgs["handle"]){
last.kwArgs.handle("forward");
}
}
}
this.historyStack.push(last);
},_createState:function(url,args,hash){
return {"url":url,"kwArgs":args,"urlHash":hash};
},_getUrlQuery:function(url){
var _270=url.split("?");
if(_270.length&lt;2){
return null;
}else{
return _270[1];
}
},_loadIframeHistory:function(){
var url=(djConfig["dojoIframeHistoryUrl"]||dojo.hostenv.getBaseScriptUri()+"iframe_history.html")+"?"+(new Date()).getTime();
this.moveForward=true;
dojo.io.setIFrameSrc(this.historyIframe,url,false);
return url;
}};
dojo.provide("dojo.io.BrowserIO");
if(!dj_undef("window")){
dojo.io.checkChildrenForFile=function(node){
var _273=false;
var _274=node.getElementsByTagName("input");
dojo.lang.forEach(_274,function(_275){
if(_273){
return;
}
if(_275.getAttribute("type")=="file"){
_273=true;
}
});
return _273;
};
dojo.io.formHasFile=function(_276){
return dojo.io.checkChildrenForFile(_276);
};
dojo.io.updateNode=function(node,_278){
node=dojo.byId(node);
var args=_278;
if(dojo.lang.isString(_278)){
args={url:_278};
}
args.mimetype="text/html";
args.load=function(t,d,e){
while(node.firstChild){
dojo.dom.destroyNode(node.firstChild);
}
node.innerHTML=d;
};
dojo.io.bind(args);
};
dojo.io.formFilter=function(node){
var type=(node.type||"").toLowerCase();
return !node.disabled&amp;&amp;node.name&amp;&amp;!dojo.lang.inArray(["file","submit","image","reset","button"],type);
};
dojo.io.encodeForm=function(_27f,_280,_281){
if((!_27f)||(!_27f.tagName)||(!_27f.tagName.toLowerCase()=="form")){
dojo.raise("Attempted to encode a non-form element.");
}
if(!_281){
_281=dojo.io.formFilter;
}
var enc=/utf/i.test(_280||"")?encodeURIComponent:dojo.string.encodeAscii;
var _283=[];
for(var i=0;i&lt;_27f.elements.length;i++){
var elm=_27f.elements[i];
if(!elm||elm.tagName.toLowerCase()=="fieldset"||!_281(elm)){
continue;
}
var name=enc(elm.name);
var type=elm.type.toLowerCase();
if(type=="select-multiple"){
for(var j=0;j&lt;elm.options.length;j++){
if(elm.options[j].selected){
_283.push(name+"="+enc(elm.options[j].value));
}
}
}else{
if(dojo.lang.inArray(["radio","checkbox"],type)){
if(elm.checked){
_283.push(name+"="+enc(elm.value));
}
}else{
_283.push(name+"="+enc(elm.value));
}
}
}
var _289=_27f.getElementsByTagName("input");
for(var i=0;i&lt;_289.length;i++){
var _28a=_289[i];
if(_28a.type.toLowerCase()=="image"&amp;&amp;_28a.form==_27f&amp;&amp;_281(_28a)){
var name=enc(_28a.name);
_283.push(name+"="+enc(_28a.value));
_283.push(name+".x=0");
_283.push(name+".y=0");
}
}
return _283.join("&amp;")+"&amp;";
};
dojo.io.FormBind=function(args){
this.bindArgs={};
if(args&amp;&amp;args.formNode){
this.init(args);
}else{
if(args){
this.init({formNode:args});
}
}
};
dojo.lang.extend(dojo.io.FormBind,{form:null,bindArgs:null,clickedButton:null,init:function(args){
var form=dojo.byId(args.formNode);
if(!form||!form.tagName||form.tagName.toLowerCase()!="form"){
throw new Error("FormBind: Couldn't apply, invalid form");
}else{
if(this.form==form){
return;
}else{
if(this.form){
throw new Error("FormBind: Already applied to a form");
}
}
}
dojo.lang.mixin(this.bindArgs,args);
this.form=form;
this.connect(form,"onsubmit","submit");
for(var i=0;i&lt;form.elements.length;i++){
var node=form.elements[i];
if(node&amp;&amp;node.type&amp;&amp;dojo.lang.inArray(["submit","button"],node.type.toLowerCase())){
this.connect(node,"onclick","click");
}
}
var _290=form.getElementsByTagName("input");
for(var i=0;i&lt;_290.length;i++){
var _291=_290[i];
if(_291.type.toLowerCase()=="image"&amp;&amp;_291.form==form){
this.connect(_291,"onclick","click");
}
}
},onSubmit:function(form){
return true;
},submit:function(e){
e.preventDefault();
if(this.onSubmit(this.form)){
dojo.io.bind(dojo.lang.mixin(this.bindArgs,{formFilter:dojo.lang.hitch(this,"formFilter")}));
}
},click:function(e){
var node=e.currentTarget;
if(node.disabled){
return;
}
this.clickedButton=node;
},formFilter:function(node){
var type=(node.type||"").toLowerCase();
var _298=false;
if(node.disabled||!node.name){
_298=false;
}else{
if(dojo.lang.inArray(["submit","button","image"],type)){
if(!this.clickedButton){
this.clickedButton=node;
}
_298=node==this.clickedButton;
}else{
_298=!dojo.lang.inArray(["file","submit","reset","button"],type);
}
}
return _298;
},connect:function(_299,_29a,_29b){
if(dojo.evalObjPath("dojo.event.connect")){
dojo.event.connect(_299,_29a,this,_29b);
}else{
var fcn=dojo.lang.hitch(this,_29b);
_299[_29a]=function(e){
if(!e){
e=window.event;
}
if(!e.currentTarget){
e.currentTarget=e.srcElement;
}
if(!e.preventDefault){
e.preventDefault=function(){
window.event.returnValue=false;
};
}
fcn(e);
};
}
}});
dojo.io.XMLHTTPTransport=new function(){
var _29e=this;
var _29f={};
this.useCache=false;
this.preventCache=false;
function getCacheKey(url,_2a1,_2a2){
return url+"|"+_2a1+"|"+_2a2.toLowerCase();
}
function addToCache(url,_2a4,_2a5,http){
_29f[getCacheKey(url,_2a4,_2a5)]=http;
}
function getFromCache(url,_2a8,_2a9){
return _29f[getCacheKey(url,_2a8,_2a9)];
}
this.clearCache=function(){
_29f={};
};
function doLoad(_2aa,http,url,_2ad,_2ae){
if(((http.status&gt;=200)&amp;&amp;(http.status&lt;300))||(http.status==304)||(http.status==1223)||(location.protocol=="file:"&amp;&amp;(http.status==0||http.status==undefined))||(location.protocol=="chrome:"&amp;&amp;(http.status==0||http.status==undefined))){
var ret;
if(_2aa.method.toLowerCase()=="head"){
var _2b0=http.getAllResponseHeaders();
ret={};
ret.toString=function(){
return _2b0;
};
var _2b1=_2b0.split(/[\r\n]+/g);
for(var i=0;i&lt;_2b1.length;i++){
var pair=_2b1[i].match(/^([^:]+)\s*:\s*(.+)$/i);
if(pair){
ret[pair[1]]=pair[2];
}
}
}else{
if(_2aa.mimetype=="text/javascript"){
try{
ret=dj_eval(http.responseText);
}
catch(e){
dojo.debug(e);
dojo.debug(http.responseText);
ret=null;
}
}else{
if(_2aa.mimetype.substr(0,9)=="text/json"||_2aa.mimetype.substr(0,16)=="application/json"){
try{
ret=dj_eval("("+_2aa.jsonFilter(http.responseText)+")");
}
catch(e){
dojo.debug(e);
dojo.debug(http.responseText);
ret=false;
}
}else{
if((_2aa.mimetype=="application/xml")||(_2aa.mimetype=="text/xml")){
ret=http.responseXML;
if(!ret||typeof ret=="string"||!http.getResponseHeader("Content-Type")){
ret=dojo.dom.createDocumentFromText(http.responseText);
}
}else{
ret=http.responseText;
}
}
}
}
if(_2ae){
addToCache(url,_2ad,_2aa.method,http);
}
_2aa[(typeof _2aa.load=="function")?"load":"handle"]("load",ret,http,_2aa);
}else{
var _2b4=new dojo.io.Error("XMLHttpTransport Error: "+http.status+" "+http.statusText);
_2aa[(typeof _2aa.error=="function")?"error":"handle"]("error",_2b4,http,_2aa);
}
}
function setHeaders(http,_2b6){
if(_2b6["headers"]){
for(var _2b7 in _2b6["headers"]){
if(_2b7.toLowerCase()=="content-type"&amp;&amp;!_2b6["contentType"]){
_2b6["contentType"]=_2b6["headers"][_2b7];
}else{
http.setRequestHeader(_2b7,_2b6["headers"][_2b7]);
}
}
}
}
this.inFlight=[];
this.inFlightTimer=null;
this.startWatchingInFlight=function(){
if(!this.inFlightTimer){
this.inFlightTimer=setTimeout("dojo.io.XMLHTTPTransport.watchInFlight();",10);
}
};
this.watchInFlight=function(){
var now=null;
if(!dojo.hostenv._blockAsync&amp;&amp;!_29e._blockAsync){
for(var x=this.inFlight.length-1;x&gt;=0;x--){
try{
var tif=this.inFlight[x];
if(!tif||tif.http._aborted||!tif.http.readyState){
this.inFlight.splice(x,1);
continue;
}
if(4==tif.http.readyState){
this.inFlight.splice(x,1);
doLoad(tif.req,tif.http,tif.url,tif.query,tif.useCache);
}else{
if(tif.startTime){
if(!now){
now=(new Date()).getTime();
}
if(tif.startTime+(tif.req.timeoutSeconds*1000)&lt;now){
if(typeof tif.http.abort=="function"){
tif.http.abort();
}
this.inFlight.splice(x,1);
tif.req[(typeof tif.req.timeout=="function")?"timeout":"handle"]("timeout",null,tif.http,tif.req);
}
}
}
}
catch(e){
try{
var _2bb=new dojo.io.Error("XMLHttpTransport.watchInFlight Error: "+e);
tif.req[(typeof tif.req.error=="function")?"error":"handle"]("error",_2bb,tif.http,tif.req);
}
catch(e2){
dojo.debug("XMLHttpTransport error callback failed: "+e2);
}
}
}
}
clearTimeout(this.inFlightTimer);
if(this.inFlight.length==0){
this.inFlightTimer=null;
return;
}
this.inFlightTimer=setTimeout("dojo.io.XMLHTTPTransport.watchInFlight();",10);
};
var _2bc=dojo.hostenv.getXmlhttpObject()?true:false;
this.canHandle=function(_2bd){
var mlc=_2bd["mimetype"].toLowerCase()||"";
return _2bc&amp;&amp;((dojo.lang.inArray(["text/plain","text/html","application/xml","text/xml","text/javascript"],mlc))||(mlc.substr(0,9)=="text/json"||mlc.substr(0,16)=="application/json"))&amp;&amp;!(_2bd["formNode"]&amp;&amp;dojo.io.formHasFile(_2bd["formNode"]));
};
this.multipartBoundary="45309FFF-BD65-4d50-99C9-36986896A96F";
this.bind=function(_2bf){
if(!_2bf["url"]){
if(!_2bf["formNode"]&amp;&amp;(_2bf["backButton"]||_2bf["back"]||_2bf["changeUrl"]||_2bf["watchForURL"])&amp;&amp;(!djConfig.preventBackButtonFix)){
dojo.deprecated("Using dojo.io.XMLHTTPTransport.bind() to add to browser history without doing an IO request","Use dojo.undo.browser.addToHistory() instead.","0.4");
dojo.undo.browser.addToHistory(_2bf);
return true;
}
}
var url=_2bf.url;
var _2c1="";
if(_2bf["formNode"]){
var ta=_2bf.formNode.getAttribute("action");
if((ta)&amp;&amp;(!_2bf["url"])){
url=ta;
}
var tp=_2bf.formNode.getAttribute("method");
if((tp)&amp;&amp;(!_2bf["method"])){
_2bf.method=tp;
}
_2c1+=dojo.io.encodeForm(_2bf.formNode,_2bf.encoding,_2bf["formFilter"]);
}
if(url.indexOf("#")&gt;-1){
dojo.debug("Warning: dojo.io.bind: stripping hash values from url:",url);
url=url.split("#")[0];
}
if(_2bf["file"]){
_2bf.method="post";
}
if(!_2bf["method"]){
_2bf.method="get";
}
if(_2bf.method.toLowerCase()=="get"){
_2bf.multipart=false;
}else{
if(_2bf["file"]){
_2bf.multipart=true;
}else{
if(!_2bf["multipart"]){
_2bf.multipart=false;
}
}
}
if(_2bf["backButton"]||_2bf["back"]||_2bf["changeUrl"]){
dojo.undo.browser.addToHistory(_2bf);
}
var _2c4=_2bf["content"]||{};
if(_2bf.sendTransport){
_2c4["dojo.transport"]="xmlhttp";
}
do{
if(_2bf.postContent){
_2c1=_2bf.postContent;
break;
}
if(_2c4){
_2c1+=dojo.io.argsFromMap(_2c4,_2bf.encoding);
}
if(_2bf.method.toLowerCase()=="get"||!_2bf.multipart){
break;
}
var t=[];
if(_2c1.length){
var q=_2c1.split("&amp;");
for(var i=0;i&lt;q.length;++i){
if(q[i].length){
var p=q[i].split("=");
t.push("--"+this.multipartBoundary,"Content-Disposition: form-data; name=\""+p[0]+"\"","",p[1]);
}
}
}
if(_2bf.file){
if(dojo.lang.isArray(_2bf.file)){
for(var i=0;i&lt;_2bf.file.length;++i){
var o=_2bf.file[i];
t.push("--"+this.multipartBoundary,"Content-Disposition: form-data; name=\""+o.name+"\"; filename=\""+("fileName" in o?o.fileName:o.name)+"\"","Content-Type: "+("contentType" in o?o.contentType:"application/octet-stream"),"",o.content);
}
}else{
var o=_2bf.file;
t.push("--"+this.multipartBoundary,"Content-Disposition: form-data; name=\""+o.name+"\"; filename=\""+("fileName" in o?o.fileName:o.name)+"\"","Content-Type: "+("contentType" in o?o.contentType:"application/octet-stream"),"",o.content);
}
}
if(t.length){
t.push("--"+this.multipartBoundary+"--","");
_2c1=t.join("\r\n");
}
}while(false);
var _2ca=_2bf["sync"]?false:true;
var _2cb=_2bf["preventCache"]||(this.preventCache==true&amp;&amp;_2bf["preventCache"]!=false);
var _2cc=_2bf["useCache"]==true||(this.useCache==true&amp;&amp;_2bf["useCache"]!=false);
if(!_2cb&amp;&amp;_2cc){
var _2cd=getFromCache(url,_2c1,_2bf.method);
if(_2cd){
doLoad(_2bf,_2cd,url,_2c1,false);
return;
}
}
var http=dojo.hostenv.getXmlhttpObject(_2bf);
var _2cf=false;
if(_2ca){
var _2d0=this.inFlight.push({"req":_2bf,"http":http,"url":url,"query":_2c1,"useCache":_2cc,"startTime":_2bf.timeoutSeconds?(new Date()).getTime():0});
this.startWatchingInFlight();
}else{
_29e._blockAsync=true;
}
if(_2bf.method.toLowerCase()=="post"){
if(!_2bf.user){
http.open("POST",url,_2ca);
}else{
http.open("POST",url,_2ca,_2bf.user,_2bf.password);
}
setHeaders(http,_2bf);
http.setRequestHeader("Content-Type",_2bf.multipart?("multipart/form-data; boundary="+this.multipartBoundary):(_2bf.contentType||"application/x-www-form-urlencoded"));
try{
http.send(_2c1);
}
catch(e){
if(typeof http.abort=="function"){
http.abort();
}
doLoad(_2bf,{status:404},url,_2c1,_2cc);
}
}else{
var _2d1=url;
if(_2c1!=""){
_2d1+=(_2d1.indexOf("?")&gt;-1?"&amp;":"?")+_2c1;
}
if(_2cb){
_2d1+=(dojo.string.endsWithAny(_2d1,"?","&amp;")?"":(_2d1.indexOf("?")&gt;-1?"&amp;":"?"))+"dojo.preventCache="+new Date().valueOf();
}
if(!_2bf.user){
http.open(_2bf.method.toUpperCase(),_2d1,_2ca);
}else{
http.open(_2bf.method.toUpperCase(),_2d1,_2ca,_2bf.user,_2bf.password);
}
setHeaders(http,_2bf);
try{
http.send(null);
}
catch(e){
if(typeof http.abort=="function"){
http.abort();
}
doLoad(_2bf,{status:404},url,_2c1,_2cc);
}
}
if(!_2ca){
doLoad(_2bf,http,url,_2c1,_2cc);
_29e._blockAsync=false;
}
_2bf.abort=function(){
try{
http._aborted=true;
}
catch(e){
}
return http.abort();
};
return;
};
dojo.io.transports.addTransport("XMLHTTPTransport");
};
}
dojo.provide("dojo.io.cookie");
dojo.io.cookie.setCookie=function(name,_2d3,days,path,_2d6,_2d7){
var _2d8=-1;
if((typeof days=="number")&amp;&amp;(days&gt;=0)){
var d=new Date();
d.setTime(d.getTime()+(days*24*60*60*1000));
_2d8=d.toGMTString();
}
_2d3=escape(_2d3);
document.cookie=name+"="+_2d3+";"+(_2d8!=-1?" expires="+_2d8+";":"")+(path?"path="+path:"")+(_2d6?"; domain="+_2d6:"")+(_2d7?"; secure":"");
};
dojo.io.cookie.set=dojo.io.cookie.setCookie;
dojo.io.cookie.getCookie=function(name){
var idx=document.cookie.lastIndexOf(name+"=");
if(idx==-1){
return null;
}
var _2dc=document.cookie.substring(idx+name.length+1);
var end=_2dc.indexOf(";");
if(end==-1){
end=_2dc.length;
}
_2dc=_2dc.substring(0,end);
_2dc=unescape(_2dc);
return _2dc;
};
dojo.io.cookie.get=dojo.io.cookie.getCookie;
dojo.io.cookie.deleteCookie=function(name){
dojo.io.cookie.setCookie(name,"-",0);
};
dojo.io.cookie.setObjectCookie=function(name,obj,days,path,_2e3,_2e4,_2e5){
if(arguments.length==5){
_2e5=_2e3;
_2e3=null;
_2e4=null;
}
var _2e6=[],_2e7,_2e8="";
if(!_2e5){
_2e7=dojo.io.cookie.getObjectCookie(name);
}
if(days&gt;=0){
if(!_2e7){
_2e7={};
}
for(var prop in obj){
if(obj[prop]==null){
delete _2e7[prop];
}else{
if((typeof obj[prop]=="string")||(typeof obj[prop]=="number")){
_2e7[prop]=obj[prop];
}
}
}
prop=null;
for(var prop in _2e7){
_2e6.push(escape(prop)+"="+escape(_2e7[prop]));
}
_2e8=_2e6.join("&amp;");
}
dojo.io.cookie.setCookie(name,_2e8,days,path,_2e3,_2e4);
};
dojo.io.cookie.getObjectCookie=function(name){
var _2eb=null,_2ec=dojo.io.cookie.getCookie(name);
if(_2ec){
_2eb={};
var _2ed=_2ec.split("&amp;");
for(var i=0;i&lt;_2ed.length;i++){
var pair=_2ed[i].split("=");
var _2f0=pair[1];
if(isNaN(_2f0)){
_2f0=unescape(pair[1]);
}
_2eb[unescape(pair[0])]=_2f0;
}
}
return _2eb;
};
dojo.io.cookie.isSupported=function(){
if(typeof navigator.cookieEnabled!="boolean"){
dojo.io.cookie.setCookie("__TestingYourBrowserForCookieSupport__","CookiesAllowed",90,null);
var _2f1=dojo.io.cookie.getCookie("__TestingYourBrowserForCookieSupport__");
navigator.cookieEnabled=(_2f1=="CookiesAllowed");
if(navigator.cookieEnabled){
this.deleteCookie("__TestingYourBrowserForCookieSupport__");
}
}
return navigator.cookieEnabled;
};
if(!dojo.io.cookies){
dojo.io.cookies=dojo.io.cookie;
}
dojo.kwCompoundRequire({common:["dojo.io.common"],rhino:["dojo.io.RhinoIO"],browser:["dojo.io.BrowserIO","dojo.io.cookie"],dashboard:["dojo.io.BrowserIO","dojo.io.cookie"]});
dojo.provide("dojo.io.*");
dojo.provide("dojo.event.common");
dojo.event=new function(){
this._canTimeout=dojo.lang.isFunction(dj_global["setTimeout"])||dojo.lang.isAlien(dj_global["setTimeout"]);
function interpolateArgs(args,_2f3){
var dl=dojo.lang;
var ao={srcObj:dj_global,srcFunc:null,adviceObj:dj_global,adviceFunc:null,aroundObj:null,aroundFunc:null,adviceType:(args.length&gt;2)?args[0]:"after",precedence:"last",once:false,delay:null,rate:0,adviceMsg:false,maxCalls:-1};
switch(args.length){
case 0:
return;
case 1:
return;
case 2:
ao.srcFunc=args[0];
ao.adviceFunc=args[1];
break;
case 3:
if((dl.isObject(args[0]))&amp;&amp;(dl.isString(args[1]))&amp;&amp;(dl.isString(args[2]))){
ao.adviceType="after";
ao.srcObj=args[0];
ao.srcFunc=args[1];
ao.adviceFunc=args[2];
}else{
if((dl.isString(args[1]))&amp;&amp;(dl.isString(args[2]))){
ao.srcFunc=args[1];
ao.adviceFunc=args[2];
}else{
if((dl.isObject(args[0]))&amp;&amp;(dl.isString(args[1]))&amp;&amp;(dl.isFunction(args[2]))){
ao.adviceType="after";
ao.srcObj=args[0];
ao.srcFunc=args[1];
var _2f6=dl.nameAnonFunc(args[2],ao.adviceObj,_2f3);
ao.adviceFunc=_2f6;
}else{
if((dl.isFunction(args[0]))&amp;&amp;(dl.isObject(args[1]))&amp;&amp;(dl.isString(args[2]))){
ao.adviceType="after";
ao.srcObj=dj_global;
var _2f6=dl.nameAnonFunc(args[0],ao.srcObj,_2f3);
ao.srcFunc=_2f6;
ao.adviceObj=args[1];
ao.adviceFunc=args[2];
}
}
}
}
break;
case 4:
if((dl.isObject(args[0]))&amp;&amp;(dl.isObject(args[2]))){
ao.adviceType="after";
ao.srcObj=args[0];
ao.srcFunc=args[1];
ao.adviceObj=args[2];
ao.adviceFunc=args[3];
}else{
if((dl.isString(args[0]))&amp;&amp;(dl.isString(args[1]))&amp;&amp;(dl.isObject(args[2]))){
ao.adviceType=args[0];
ao.srcObj=dj_global;
ao.srcFunc=args[1];
ao.adviceObj=args[2];
ao.adviceFunc=args[3];
}else{
if((dl.isString(args[0]))&amp;&amp;(dl.isFunction(args[1]))&amp;&amp;(dl.isObject(args[2]))){
ao.adviceType=args[0];
ao.srcObj=dj_global;
var _2f6=dl.nameAnonFunc(args[1],dj_global,_2f3);
ao.srcFunc=_2f6;
ao.adviceObj=args[2];
ao.adviceFunc=args[3];
}else{
if((dl.isString(args[0]))&amp;&amp;(dl.isObject(args[1]))&amp;&amp;(dl.isString(args[2]))&amp;&amp;(dl.isFunction(args[3]))){
ao.srcObj=args[1];
ao.srcFunc=args[2];
var _2f6=dl.nameAnonFunc(args[3],dj_global,_2f3);
ao.adviceObj=dj_global;
ao.adviceFunc=_2f6;
}else{
if(dl.isObject(args[1])){
ao.srcObj=args[1];
ao.srcFunc=args[2];
ao.adviceObj=dj_global;
ao.adviceFunc=args[3];
}else{
if(dl.isObject(args[2])){
ao.srcObj=dj_global;
ao.srcFunc=args[1];
ao.adviceObj=args[2];
ao.adviceFunc=args[3];
}else{
ao.srcObj=ao.adviceObj=ao.aroundObj=dj_global;
ao.srcFunc=args[1];
ao.adviceFunc=args[2];
ao.aroundFunc=args[3];
}
}
}
}
}
}
break;
case 6:
ao.srcObj=args[1];
ao.srcFunc=args[2];
ao.adviceObj=args[3];
ao.adviceFunc=args[4];
ao.aroundFunc=args[5];
ao.aroundObj=dj_global;
break;
default:
ao.srcObj=args[1];
ao.srcFunc=args[2];
ao.adviceObj=args[3];
ao.adviceFunc=args[4];
ao.aroundObj=args[5];
ao.aroundFunc=args[6];
ao.once=args[7];
ao.delay=args[8];
ao.rate=args[9];
ao.adviceMsg=args[10];
ao.maxCalls=(!isNaN(parseInt(args[11])))?args[11]:-1;
break;
}
if(dl.isFunction(ao.aroundFunc)){
var _2f6=dl.nameAnonFunc(ao.aroundFunc,ao.aroundObj,_2f3);
ao.aroundFunc=_2f6;
}
if(dl.isFunction(ao.srcFunc)){
ao.srcFunc=dl.getNameInObj(ao.srcObj,ao.srcFunc);
}
if(dl.isFunction(ao.adviceFunc)){
ao.adviceFunc=dl.getNameInObj(ao.adviceObj,ao.adviceFunc);
}
if((ao.aroundObj)&amp;&amp;(dl.isFunction(ao.aroundFunc))){
ao.aroundFunc=dl.getNameInObj(ao.aroundObj,ao.aroundFunc);
}
if(!ao.srcObj){
dojo.raise("bad srcObj for srcFunc: "+ao.srcFunc);
}
if(!ao.adviceObj){
dojo.raise("bad adviceObj for adviceFunc: "+ao.adviceFunc);
}
if(!ao.adviceFunc){
dojo.debug("bad adviceFunc for srcFunc: "+ao.srcFunc);
dojo.debugShallow(ao);
}
return ao;
}
this.connect=function(){
if(arguments.length==1){
var ao=arguments[0];
}else{
var ao=interpolateArgs(arguments,true);
}
if(dojo.lang.isString(ao.srcFunc)&amp;&amp;(ao.srcFunc.toLowerCase()=="onkey")){
if(dojo.render.html.ie){
ao.srcFunc="onkeydown";
this.connect(ao);
}
ao.srcFunc="onkeypress";
}
if(dojo.lang.isArray(ao.srcObj)&amp;&amp;ao.srcObj!=""){
var _2f8={};
for(var x in ao){
_2f8[x]=ao[x];
}
var mjps=[];
dojo.lang.forEach(ao.srcObj,function(src){
if((dojo.render.html.capable)&amp;&amp;(dojo.lang.isString(src))){
src=dojo.byId(src);
}
_2f8.srcObj=src;
mjps.push(dojo.event.connect.call(dojo.event,_2f8));
});
return mjps;
}
var mjp=dojo.event.MethodJoinPoint.getForMethod(ao.srcObj,ao.srcFunc);
if(ao.adviceFunc){
var mjp2=dojo.event.MethodJoinPoint.getForMethod(ao.adviceObj,ao.adviceFunc);
}
mjp.kwAddAdvice(ao);
return mjp;
};
this.log=function(a1,a2){
var _300;
if((arguments.length==1)&amp;&amp;(typeof a1=="object")){
_300=a1;
}else{
_300={srcObj:a1,srcFunc:a2};
}
_300.adviceFunc=function(){
var _301=[];
for(var x=0;x&lt;arguments.length;x++){
_301.push(arguments[x]);
}
dojo.debug("("+_300.srcObj+")."+_300.srcFunc,":",_301.join(", "));
};
this.kwConnect(_300);
};
this.connectBefore=function(){
var args=["before"];
for(var i=0;i&lt;arguments.length;i++){
args.push(arguments[i]);
}
return this.connect.apply(this,args);
};
this.connectAround=function(){
var args=["around"];
for(var i=0;i&lt;arguments.length;i++){
args.push(arguments[i]);
}
return this.connect.apply(this,args);
};
this.connectOnce=function(){
var ao=interpolateArgs(arguments,true);
ao.once=true;
return this.connect(ao);
};
this.connectRunOnce=function(){
var ao=interpolateArgs(arguments,true);
ao.maxCalls=1;
return this.connect(ao);
};
this._kwConnectImpl=function(_309,_30a){
var fn=(_30a)?"disconnect":"connect";
if(typeof _309["srcFunc"]=="function"){
_309.srcObj=_309["srcObj"]||dj_global;
var _30c=dojo.lang.nameAnonFunc(_309.srcFunc,_309.srcObj,true);
_309.srcFunc=_30c;
}
if(typeof _309["adviceFunc"]=="function"){
_309.adviceObj=_309["adviceObj"]||dj_global;
var _30c=dojo.lang.nameAnonFunc(_309.adviceFunc,_309.adviceObj,true);
_309.adviceFunc=_30c;
}
_309.srcObj=_309["srcObj"]||dj_global;
_309.adviceObj=_309["adviceObj"]||_309["targetObj"]||dj_global;
_309.adviceFunc=_309["adviceFunc"]||_309["targetFunc"];
return dojo.event[fn](_309);
};
this.kwConnect=function(_30d){
return this._kwConnectImpl(_30d,false);
};
this.disconnect=function(){
if(arguments.length==1){
var ao=arguments[0];
}else{
var ao=interpolateArgs(arguments,true);
}
if(!ao.adviceFunc){
return;
}
if(dojo.lang.isString(ao.srcFunc)&amp;&amp;(ao.srcFunc.toLowerCase()=="onkey")){
if(dojo.render.html.ie){
ao.srcFunc="onkeydown";
this.disconnect(ao);
}
ao.srcFunc="onkeypress";
}
if(!ao.srcObj[ao.srcFunc]){
return null;
}
var mjp=dojo.event.MethodJoinPoint.getForMethod(ao.srcObj,ao.srcFunc,true);
mjp.removeAdvice(ao.adviceObj,ao.adviceFunc,ao.adviceType,ao.once);
return mjp;
};
this.kwDisconnect=function(_310){
return this._kwConnectImpl(_310,true);
};
};
dojo.event.MethodInvocation=function(_311,obj,args){
this.jp_=_311;
this.object=obj;
this.args=[];
for(var x=0;x&lt;args.length;x++){
this.args[x]=args[x];
}
this.around_index=-1;
};
dojo.event.MethodInvocation.prototype.proceed=function(){
this.around_index++;
if(this.around_index&gt;=this.jp_.around.length){
return this.jp_.object[this.jp_.methodname].apply(this.jp_.object,this.args);
}else{
var ti=this.jp_.around[this.around_index];
var mobj=ti[0]||dj_global;
var meth=ti[1];
return mobj[meth].call(mobj,this);
}
};
dojo.event.MethodJoinPoint=function(obj,_319){
this.object=obj||dj_global;
this.methodname=_319;
this.methodfunc=this.object[_319];
this.squelch=false;
};
dojo.event.MethodJoinPoint.getForMethod=function(obj,_31b){
if(!obj){
obj=dj_global;
}
var ofn=obj[_31b];
if(!ofn){
ofn=obj[_31b]=function(){
};
if(!obj[_31b]){
dojo.raise("Cannot set do-nothing method on that object "+_31b);
}
}else{
if((typeof ofn!="function")&amp;&amp;(!dojo.lang.isFunction(ofn))&amp;&amp;(!dojo.lang.isAlien(ofn))){
return null;
}
}
var _31d=_31b+"$joinpoint";
var _31e=_31b+"$joinpoint$method";
var _31f=obj[_31d];
if(!_31f){
var _320=false;
if(dojo.event["browser"]){
if((obj["attachEvent"])||(obj["nodeType"])||(obj["addEventListener"])){
_320=true;
dojo.event.browser.addClobberNodeAttrs(obj,[_31d,_31e,_31b]);
}
}
var _321=ofn.length;
obj[_31e]=ofn;
_31f=obj[_31d]=new dojo.event.MethodJoinPoint(obj,_31e);
if(!_320){
obj[_31b]=function(){
return _31f.run.apply(_31f,arguments);
};
}else{
obj[_31b]=function(){
var args=[];
if(!arguments.length){
var evt=null;
try{
if(obj.ownerDocument){
evt=obj.ownerDocument.parentWindow.event;
}else{
if(obj.documentElement){
evt=obj.documentElement.ownerDocument.parentWindow.event;
}else{
if(obj.event){
evt=obj.event;
}else{
evt=window.event;
}
}
}
}
catch(e){
evt=window.event;
}
if(evt){
args.push(dojo.event.browser.fixEvent(evt,this));
}
}else{
for(var x=0;x&lt;arguments.length;x++){
if((x==0)&amp;&amp;(dojo.event.browser.isEvent(arguments[x]))){
args.push(dojo.event.browser.fixEvent(arguments[x],this));
}else{
args.push(arguments[x]);
}
}
}
return _31f.run.apply(_31f,args);
};
}
obj[_31b].__preJoinArity=_321;
}
return _31f;
};
dojo.lang.extend(dojo.event.MethodJoinPoint,{squelch:false,unintercept:function(){
this.object[this.methodname]=this.methodfunc;
this.before=[];
this.after=[];
this.around=[];
},disconnect:dojo.lang.forward("unintercept"),run:function(){
var obj=this.object||dj_global;
var args=arguments;
var _327=[];
for(var x=0;x&lt;args.length;x++){
_327[x]=args[x];
}
var _329=function(marr){
if(!marr){
dojo.debug("Null argument to unrollAdvice()");
return;
}
var _32b=marr[0]||dj_global;
var _32c=marr[1];
if(!_32b[_32c]){
dojo.raise("function \""+_32c+"\" does not exist on \""+_32b+"\"");
}
var _32d=marr[2]||dj_global;
var _32e=marr[3];
var msg=marr[6];
var _330=marr[7];
if(_330&gt;-1){
if(_330==0){
return;
}
marr[7]--;
}
var _331;
var to={args:[],jp_:this,object:obj,proceed:function(){
return _32b[_32c].apply(_32b,to.args);
}};
to.args=_327;
var _333=parseInt(marr[4]);
var _334=((!isNaN(_333))&amp;&amp;(marr[4]!==null)&amp;&amp;(typeof marr[4]!="undefined"));
if(marr[5]){
var rate=parseInt(marr[5]);
var cur=new Date();
var _337=false;
if((marr["last"])&amp;&amp;((cur-marr.last)&lt;=rate)){
if(dojo.event._canTimeout){
if(marr["delayTimer"]){
clearTimeout(marr.delayTimer);
}
var tod=parseInt(rate*2);
var mcpy=dojo.lang.shallowCopy(marr);
marr.delayTimer=setTimeout(function(){
mcpy[5]=0;
_329(mcpy);
},tod);
}
return;
}else{
marr.last=cur;
}
}
if(_32e){
_32d[_32e].call(_32d,to);
}else{
if((_334)&amp;&amp;((dojo.render.html)||(dojo.render.svg))){
dj_global["setTimeout"](function(){
if(msg){
_32b[_32c].call(_32b,to);
}else{
_32b[_32c].apply(_32b,args);
}
},_333);
}else{
if(msg){
_32b[_32c].call(_32b,to);
}else{
_32b[_32c].apply(_32b,args);
}
}
}
};
var _33a=function(){
if(this.squelch){
try{
return _329.apply(this,arguments);
}
catch(e){
dojo.debug(e);
}
}else{
return _329.apply(this,arguments);
}
};
if((this["before"])&amp;&amp;(this.before.length&gt;0)){
dojo.lang.forEach(this.before.concat(new Array()),_33a);
}
var _33b;
try{
if((this["around"])&amp;&amp;(this.around.length&gt;0)){
var mi=new dojo.event.MethodInvocation(this,obj,args);
_33b=mi.proceed();
}else{
if(this.methodfunc){
_33b=this.object[this.methodname].apply(this.object,args);
}
}
}
catch(e){
if(!this.squelch){
dojo.debug(e,"when calling",this.methodname,"on",this.object,"with arguments",args);
dojo.raise(e);
}
}
if((this["after"])&amp;&amp;(this.after.length&gt;0)){
dojo.lang.forEach(this.after.concat(new Array()),_33a);
}
return (this.methodfunc)?_33b:null;
},getArr:function(kind){
var type="after";
if((typeof kind=="string")&amp;&amp;(kind.indexOf("before")!=-1)){
type="before";
}else{
if(kind=="around"){
type="around";
}
}
if(!this[type]){
this[type]=[];
}
return this[type];
},kwAddAdvice:function(args){
this.addAdvice(args["adviceObj"],args["adviceFunc"],args["aroundObj"],args["aroundFunc"],args["adviceType"],args["precedence"],args["once"],args["delay"],args["rate"],args["adviceMsg"],args["maxCalls"]);
},addAdvice:function(_340,_341,_342,_343,_344,_345,once,_347,rate,_349,_34a){
var arr=this.getArr(_344);
if(!arr){
dojo.raise("bad this: "+this);
}
var ao=[_340,_341,_342,_343,_347,rate,_349,_34a];
if(once){
if(this.hasAdvice(_340,_341,_344,arr)&gt;=0){
return;
}
}
if(_345=="first"){
arr.unshift(ao);
}else{
arr.push(ao);
}
},hasAdvice:function(_34d,_34e,_34f,arr){
if(!arr){
arr=this.getArr(_34f);
}
var ind=-1;
for(var x=0;x&lt;arr.length;x++){
var aao=(typeof _34e=="object")?(new String(_34e)).toString():_34e;
var a1o=(typeof arr[x][1]=="object")?(new String(arr[x][1])).toString():arr[x][1];
if((arr[x][0]==_34d)&amp;&amp;(a1o==aao)){
ind=x;
}
}
return ind;
},removeAdvice:function(_355,_356,_357,once){
var arr=this.getArr(_357);
var ind=this.hasAdvice(_355,_356,_357,arr);
if(ind==-1){
return false;
}
while(ind!=-1){
arr.splice(ind,1);
if(once){
break;
}
ind=this.hasAdvice(_355,_356,_357,arr);
}
return true;
}});
dojo.provide("dojo.event.topic");
dojo.event.topic=new function(){
this.topics={};
this.getTopic=function(_35b){
if(!this.topics[_35b]){
this.topics[_35b]=new this.TopicImpl(_35b);
}
return this.topics[_35b];
};
this.registerPublisher=function(_35c,obj,_35e){
var _35c=this.getTopic(_35c);
_35c.registerPublisher(obj,_35e);
};
this.subscribe=function(_35f,obj,_361){
var _35f=this.getTopic(_35f);
_35f.subscribe(obj,_361);
};
this.unsubscribe=function(_362,obj,_364){
var _362=this.getTopic(_362);
_362.unsubscribe(obj,_364);
};
this.destroy=function(_365){
this.getTopic(_365).destroy();
delete this.topics[_365];
};
this.publishApply=function(_366,args){
var _366=this.getTopic(_366);
_366.sendMessage.apply(_366,args);
};
this.publish=function(_368,_369){
var _368=this.getTopic(_368);
var args=[];
for(var x=1;x&lt;arguments.length;x++){
args.push(arguments[x]);
}
_368.sendMessage.apply(_368,args);
};
};
dojo.event.topic.TopicImpl=function(_36c){
this.topicName=_36c;
this.subscribe=function(_36d,_36e){
var tf=_36e||_36d;
var to=(!_36e)?dj_global:_36d;
return dojo.event.kwConnect({srcObj:this,srcFunc:"sendMessage",adviceObj:to,adviceFunc:tf});
};
this.unsubscribe=function(_371,_372){
var tf=(!_372)?_371:_372;
var to=(!_372)?null:_371;
return dojo.event.kwDisconnect({srcObj:this,srcFunc:"sendMessage",adviceObj:to,adviceFunc:tf});
};
this._getJoinPoint=function(){
return dojo.event.MethodJoinPoint.getForMethod(this,"sendMessage");
};
this.setSquelch=function(_375){
this._getJoinPoint().squelch=_375;
};
this.destroy=function(){
this._getJoinPoint().disconnect();
};
this.registerPublisher=function(_376,_377){
dojo.event.connect(_376,_377,this,"sendMessage");
};
this.sendMessage=function(_378){
};
};
dojo.provide("dojo.event.browser");
dojo._ie_clobber=new function(){
this.clobberNodes=[];
function nukeProp(node,prop){
try{
node[prop]=null;
}
catch(e){
}
try{
delete node[prop];
}
catch(e){
}
try{
node.removeAttribute(prop);
}
catch(e){
}
}
this.clobber=function(_37b){
var na;
var tna;
if(_37b){
tna=_37b.all||_37b.getElementsByTagName("*");
na=[_37b];
for(var x=0;x&lt;tna.length;x++){
if(tna[x]["__doClobber__"]){
na.push(tna[x]);
}
}
}else{
try{
window.onload=null;
}
catch(e){
}
na=(this.clobberNodes.length)?this.clobberNodes:document.all;
}
tna=null;
var _37f={};
for(var i=na.length-1;i&gt;=0;i=i-1){
var el=na[i];
try{
if(el&amp;&amp;el["__clobberAttrs__"]){
for(var j=0;j&lt;el.__clobberAttrs__.length;j++){
nukeProp(el,el.__clobberAttrs__[j]);
}
nukeProp(el,"__clobberAttrs__");
nukeProp(el,"__doClobber__");
}
}
catch(e){
}
}
na=null;
};
};
if(dojo.render.html.ie){
dojo.addOnUnload(function(){
dojo._ie_clobber.clobber();
try{
if((dojo["widget"])&amp;&amp;(dojo.widget["manager"])){
dojo.widget.manager.destroyAll();
}
}
catch(e){
}
if(dojo.widget){
for(var name in dojo.widget._templateCache){
if(dojo.widget._templateCache[name].node){
dojo.dom.destroyNode(dojo.widget._templateCache[name].node);
dojo.widget._templateCache[name].node=null;
delete dojo.widget._templateCache[name].node;
}
}
}
try{
window.onload=null;
}
catch(e){
}
try{
window.onunload=null;
}
catch(e){
}
dojo._ie_clobber.clobberNodes=[];
});
}
dojo.event.browser=new function(){
var _384=0;
this.normalizedEventName=function(_385){
switch(_385){
case "CheckboxStateChange":
case "DOMAttrModified":
case "DOMMenuItemActive":
case "DOMMenuItemInactive":
case "DOMMouseScroll":
case "DOMNodeInserted":
case "DOMNodeRemoved":
case "RadioStateChange":
return _385;
break;
default:
var lcn=_385.toLowerCase();
return (lcn.indexOf("on")==0)?lcn.substr(2):lcn;
break;
}
};
this.clean=function(node){
if(dojo.render.html.ie){
dojo._ie_clobber.clobber(node);
}
};
this.addClobberNode=function(node){
if(!dojo.render.html.ie){
return;
}
if(!node["__doClobber__"]){
node.__doClobber__=true;
dojo._ie_clobber.clobberNodes.push(node);
node.__clobberAttrs__=[];
}
};
this.addClobberNodeAttrs=function(node,_38a){
if(!dojo.render.html.ie){
return;
}
this.addClobberNode(node);
for(var x=0;x&lt;_38a.length;x++){
node.__clobberAttrs__.push(_38a[x]);
}
};
this.removeListener=function(node,_38d,fp,_38f){
if(!_38f){
var _38f=false;
}
_38d=dojo.event.browser.normalizedEventName(_38d);
if(_38d=="key"){
if(dojo.render.html.ie){
this.removeListener(node,"onkeydown",fp,_38f);
}
_38d="keypress";
}
if(node.removeEventListener){
node.removeEventListener(_38d,fp,_38f);
}
};
this.addListener=function(node,_391,fp,_393,_394){
if(!node){
return;
}
if(!_393){
var _393=false;
}
_391=dojo.event.browser.normalizedEventName(_391);
if(_391=="key"){
if(dojo.render.html.ie){
this.addListener(node,"onkeydown",fp,_393,_394);
}
_391="keypress";
}
if(!_394){
var _395=function(evt){
if(!evt){
evt=window.event;
}
var ret=fp(dojo.event.browser.fixEvent(evt,this));
if(_393){
dojo.event.browser.stopEvent(evt);
}
return ret;
};
}else{
_395=fp;
}
if(node.addEventListener){
node.addEventListener(_391,_395,_393);
return _395;
}else{
_391="on"+_391;
if(typeof node[_391]=="function"){
var _398=node[_391];
node[_391]=function(e){
_398(e);
return _395(e);
};
}else{
node[_391]=_395;
}
if(dojo.render.html.ie){
this.addClobberNodeAttrs(node,[_391]);
}
return _395;
}
};
this.isEvent=function(obj){
return (typeof obj!="undefined")&amp;&amp;(obj)&amp;&amp;(typeof Event!="undefined")&amp;&amp;(obj.eventPhase);
};
this.currentEvent=null;
this.callListener=function(_39b,_39c){
if(typeof _39b!="function"){
dojo.raise("listener not a function: "+_39b);
}
dojo.event.browser.currentEvent.currentTarget=_39c;
return _39b.call(_39c,dojo.event.browser.currentEvent);
};
this._stopPropagation=function(){
dojo.event.browser.currentEvent.cancelBubble=true;
};
this._preventDefault=function(){
dojo.event.browser.currentEvent.returnValue=false;
};
this.keys={KEY_BACKSPACE:8,KEY_TAB:9,KEY_CLEAR:12,KEY_ENTER:13,KEY_SHIFT:16,KEY_CTRL:17,KEY_ALT:18,KEY_PAUSE:19,KEY_CAPS_LOCK:20,KEY_ESCAPE:27,KEY_SPACE:32,KEY_PAGE_UP:33,KEY_PAGE_DOWN:34,KEY_END:35,KEY_HOME:36,KEY_LEFT_ARROW:37,KEY_UP_ARROW:38,KEY_RIGHT_ARROW:39,KEY_DOWN_ARROW:40,KEY_INSERT:45,KEY_DELETE:46,KEY_HELP:47,KEY_LEFT_WINDOW:91,KEY_RIGHT_WINDOW:92,KEY_SELECT:93,KEY_NUMPAD_0:96,KEY_NUMPAD_1:97,KEY_NUMPAD_2:98,KEY_NUMPAD_3:99,KEY_NUMPAD_4:100,KEY_NUMPAD_5:101,KEY_NUMPAD_6:102,KEY_NUMPAD_7:103,KEY_NUMPAD_8:104,KEY_NUMPAD_9:105,KEY_NUMPAD_MULTIPLY:106,KEY_NUMPAD_PLUS:107,KEY_NUMPAD_ENTER:108,KEY_NUMPAD_MINUS:109,KEY_NUMPAD_PERIOD:110,KEY_NUMPAD_DIVIDE:111,KEY_F1:112,KEY_F2:113,KEY_F3:114,KEY_F4:115,KEY_F5:116,KEY_F6:117,KEY_F7:118,KEY_F8:119,KEY_F9:120,KEY_F10:121,KEY_F11:122,KEY_F12:123,KEY_F13:124,KEY_F14:125,KEY_F15:126,KEY_NUM_LOCK:144,KEY_SCROLL_LOCK:145};
this.revKeys=[];
for(var key in this.keys){
this.revKeys[this.keys[key]]=key;
}
this.fixEvent=function(evt,_39f){
if(!evt){
if(window["event"]){
evt=window.event;
}
}
if((evt["type"])&amp;&amp;(evt["type"].indexOf("key")==0)){
evt.keys=this.revKeys;
for(var key in this.keys){
evt[key]=this.keys[key];
}
if(evt["type"]=="keydown"&amp;&amp;dojo.render.html.ie){
switch(evt.keyCode){
case evt.KEY_SHIFT:
case evt.KEY_CTRL:
case evt.KEY_ALT:
case evt.KEY_CAPS_LOCK:
case evt.KEY_LEFT_WINDOW:
case evt.KEY_RIGHT_WINDOW:
case evt.KEY_SELECT:
case evt.KEY_NUM_LOCK:
case evt.KEY_SCROLL_LOCK:
case evt.KEY_NUMPAD_0:
case evt.KEY_NUMPAD_1:
case evt.KEY_NUMPAD_2:
case evt.KEY_NUMPAD_3:
case evt.KEY_NUMPAD_4:
case evt.KEY_NUMPAD_5:
case evt.KEY_NUMPAD_6:
case evt.KEY_NUMPAD_7:
case evt.KEY_NUMPAD_8:
case evt.KEY_NUMPAD_9:
case evt.KEY_NUMPAD_PERIOD:
break;
case evt.KEY_NUMPAD_MULTIPLY:
case evt.KEY_NUMPAD_PLUS:
case evt.KEY_NUMPAD_ENTER:
case evt.KEY_NUMPAD_MINUS:
case evt.KEY_NUMPAD_DIVIDE:
break;
case evt.KEY_PAUSE:
case evt.KEY_TAB:
case evt.KEY_BACKSPACE:
case evt.KEY_ENTER:
case evt.KEY_ESCAPE:
case evt.KEY_PAGE_UP:
case evt.KEY_PAGE_DOWN:
case evt.KEY_END:
case evt.KEY_HOME:
case evt.KEY_LEFT_ARROW:
case evt.KEY_UP_ARROW:
case evt.KEY_RIGHT_ARROW:
case evt.KEY_DOWN_ARROW:
case evt.KEY_INSERT:
case evt.KEY_DELETE:
case evt.KEY_F1:
case evt.KEY_F2:
case evt.KEY_F3:
case evt.KEY_F4:
case evt.KEY_F5:
case evt.KEY_F6:
case evt.KEY_F7:
case evt.KEY_F8:
case evt.KEY_F9:
case evt.KEY_F10:
case evt.KEY_F11:
case evt.KEY_F12:
case evt.KEY_F12:
case evt.KEY_F13:
case evt.KEY_F14:
case evt.KEY_F15:
case evt.KEY_CLEAR:
case evt.KEY_HELP:
evt.key=evt.keyCode;
break;
default:
if(evt.ctrlKey||evt.altKey){
var _3a1=evt.keyCode;
if(_3a1&gt;=65&amp;&amp;_3a1&lt;=90&amp;&amp;evt.shiftKey==false){
_3a1+=32;
}
if(_3a1&gt;=1&amp;&amp;_3a1&lt;=26&amp;&amp;evt.ctrlKey){
_3a1+=96;
}
evt.key=String.fromCharCode(_3a1);
}
}
}else{
if(evt["type"]=="keypress"){
if(dojo.render.html.opera){
if(evt.which==0){
evt.key=evt.keyCode;
}else{
if(evt.which&gt;0){
switch(evt.which){
case evt.KEY_SHIFT:
case evt.KEY_CTRL:
case evt.KEY_ALT:
case evt.KEY_CAPS_LOCK:
case evt.KEY_NUM_LOCK:
case evt.KEY_SCROLL_LOCK:
break;
case evt.KEY_PAUSE:
case evt.KEY_TAB:
case evt.KEY_BACKSPACE:
case evt.KEY_ENTER:
case evt.KEY_ESCAPE:
evt.key=evt.which;
break;
default:
var _3a1=evt.which;
if((evt.ctrlKey||evt.altKey||evt.metaKey)&amp;&amp;(evt.which&gt;=65&amp;&amp;evt.which&lt;=90&amp;&amp;evt.shiftKey==false)){
_3a1+=32;
}
evt.key=String.fromCharCode(_3a1);
}
}
}
}else{
if(dojo.render.html.ie){
if(!evt.ctrlKey&amp;&amp;!evt.altKey&amp;&amp;evt.keyCode&gt;=evt.KEY_SPACE){
evt.key=String.fromCharCode(evt.keyCode);
}
}else{
if(dojo.render.html.safari){
switch(evt.keyCode){
case 25:
evt.key=evt.KEY_TAB;
evt.shift=true;
break;
case 63232:
evt.key=evt.KEY_UP_ARROW;
break;
case 63233:
evt.key=evt.KEY_DOWN_ARROW;
break;
case 63234:
evt.key=evt.KEY_LEFT_ARROW;
break;
case 63235:
evt.key=evt.KEY_RIGHT_ARROW;
break;
case 63236:
evt.key=evt.KEY_F1;
break;
case 63237:
evt.key=evt.KEY_F2;
break;
case 63238:
evt.key=evt.KEY_F3;
break;
case 63239:
evt.key=evt.KEY_F4;
break;
case 63240:
evt.key=evt.KEY_F5;
break;
case 63241:
evt.key=evt.KEY_F6;
break;
case 63242:
evt.key=evt.KEY_F7;
break;
case 63243:
evt.key=evt.KEY_F8;
break;
case 63244:
evt.key=evt.KEY_F9;
break;
case 63245:
evt.key=evt.KEY_F10;
break;
case 63246:
evt.key=evt.KEY_F11;
break;
case 63247:
evt.key=evt.KEY_F12;
break;
case 63250:
evt.key=evt.KEY_PAUSE;
break;
case 63272:
evt.key=evt.KEY_DELETE;
break;
case 63273:
evt.key=evt.KEY_HOME;
break;
case 63275:
evt.key=evt.KEY_END;
break;
case 63276:
evt.key=evt.KEY_PAGE_UP;
break;
case 63277:
evt.key=evt.KEY_PAGE_DOWN;
break;
case 63302:
evt.key=evt.KEY_INSERT;
break;
case 63248:
case 63249:
case 63289:
break;
default:
evt.key=evt.charCode&gt;=evt.KEY_SPACE?String.fromCharCode(evt.charCode):evt.keyCode;
}
}else{
evt.key=evt.charCode&gt;0?String.fromCharCode(evt.charCode):evt.keyCode;
}
}
}
}
}
}
if(dojo.render.html.ie){
if(!evt.target){
evt.target=evt.srcElement;
}
if(!evt.currentTarget){
evt.currentTarget=(_39f?_39f:evt.srcElement);
}
if(!evt.layerX){
evt.layerX=evt.offsetX;
}
if(!evt.layerY){
evt.layerY=evt.offsetY;
}
var doc=(evt.srcElement&amp;&amp;evt.srcElement.ownerDocument)?evt.srcElement.ownerDocument:document;
var _3a3=((dojo.render.html.ie55)||(doc["compatMode"]=="BackCompat"))?doc.body:doc.documentElement;
if(!evt.pageX){
evt.pageX=evt.clientX+(_3a3.scrollLeft||0);
}
if(!evt.pageY){
evt.pageY=evt.clientY+(_3a3.scrollTop||0);
}
if(evt.type=="mouseover"){
evt.relatedTarget=evt.fromElement;
}
if(evt.type=="mouseout"){
evt.relatedTarget=evt.toElement;
}
this.currentEvent=evt;
evt.callListener=this.callListener;
evt.stopPropagation=this._stopPropagation;
evt.preventDefault=this._preventDefault;
}
return evt;
};
this.stopEvent=function(evt){
if(window.event){
evt.cancelBubble=true;
evt.returnValue=false;
}else{
evt.preventDefault();
evt.stopPropagation();
}
};
};
dojo.kwCompoundRequire({common:["dojo.event.common","dojo.event.topic"],browser:["dojo.event.browser"],dashboard:["dojo.event.browser"]});
dojo.provide("dojo.event.*");
dojo.provide("dojo.gfx.color");
dojo.gfx.color.Color=function(r,g,b,a){
if(dojo.lang.isArray(r)){
this.r=r[0];
this.g=r[1];
this.b=r[2];
this.a=r[3]||1;
}else{
if(dojo.lang.isString(r)){
var rgb=dojo.gfx.color.extractRGB(r);
this.r=rgb[0];
this.g=rgb[1];
this.b=rgb[2];
this.a=g||1;
}else{
if(r instanceof dojo.gfx.color.Color){
this.r=r.r;
this.b=r.b;
this.g=r.g;
this.a=r.a;
}else{
this.r=r;
this.g=g;
this.b=b;
this.a=a;
}
}
}
};
dojo.gfx.color.Color.fromArray=function(arr){
return new dojo.gfx.color.Color(arr[0],arr[1],arr[2],arr[3]);
};
dojo.extend(dojo.gfx.color.Color,{toRgb:function(_3ab){
if(_3ab){
return this.toRgba();
}else{
return [this.r,this.g,this.b];
}
},toRgba:function(){
return [this.r,this.g,this.b,this.a];
},toHex:function(){
return dojo.gfx.color.rgb2hex(this.toRgb());
},toCss:function(){
return "rgb("+this.toRgb().join()+")";
},toString:function(){
return this.toHex();
},blend:function(_3ac,_3ad){
var rgb=null;
if(dojo.lang.isArray(_3ac)){
rgb=_3ac;
}else{
if(_3ac instanceof dojo.gfx.color.Color){
rgb=_3ac.toRgb();
}else{
rgb=new dojo.gfx.color.Color(_3ac).toRgb();
}
}
return dojo.gfx.color.blend(this.toRgb(),rgb,_3ad);
}});
dojo.gfx.color.named={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,255,0],lime:[0,255,0],blue:[0,0,255],navy:[0,0,128],gray:[128,128,128],silver:[192,192,192]};
dojo.gfx.color.blend=function(a,b,_3b1){
if(typeof a=="string"){
return dojo.gfx.color.blendHex(a,b,_3b1);
}
if(!_3b1){
_3b1=0;
}
_3b1=Math.min(Math.max(-1,_3b1),1);
_3b1=((_3b1+1)/2);
var c=[];
for(var x=0;x&lt;3;x++){
c[x]=parseInt(b[x]+((a[x]-b[x])*_3b1));
}
return c;
};
dojo.gfx.color.blendHex=function(a,b,_3b6){
return dojo.gfx.color.rgb2hex(dojo.gfx.color.blend(dojo.gfx.color.hex2rgb(a),dojo.gfx.color.hex2rgb(b),_3b6));
};
dojo.gfx.color.extractRGB=function(_3b7){
var hex="0123456789abcdef";
_3b7=_3b7.toLowerCase();
if(_3b7.indexOf("rgb")==0){
var _3b9=_3b7.match(/rgba*\((\d+), *(\d+), *(\d+)/i);
var ret=_3b9.splice(1,3);
return ret;
}else{
var _3bb=dojo.gfx.color.hex2rgb(_3b7);
if(_3bb){
return _3bb;
}else{
return dojo.gfx.color.named[_3b7]||[255,255,255];
}
}
};
dojo.gfx.color.hex2rgb=function(hex){
var _3bd="0123456789ABCDEF";
var rgb=new Array(3);
if(hex.indexOf("#")==0){
hex=hex.substring(1);
}
hex=hex.toUpperCase();
if(hex.replace(new RegExp("["+_3bd+"]","g"),"")!=""){
return null;
}
if(hex.length==3){
rgb[0]=hex.charAt(0)+hex.charAt(0);
rgb[1]=hex.charAt(1)+hex.charAt(1);
rgb[2]=hex.charAt(2)+hex.charAt(2);
}else{
rgb[0]=hex.substring(0,2);
rgb[1]=hex.substring(2,4);
rgb[2]=hex.substring(4);
}
for(var i=0;i&lt;rgb.length;i++){
rgb[i]=_3bd.indexOf(rgb[i].charAt(0))*16+_3bd.indexOf(rgb[i].charAt(1));
}
return rgb;
};
dojo.gfx.color.rgb2hex=function(r,g,b){
if(dojo.lang.isArray(r)){
g=r[1]||0;
b=r[2]||0;
r=r[0]||0;
}
var ret=dojo.lang.map([r,g,b],function(x){
x=new Number(x);
var s=x.toString(16);
while(s.length&lt;2){
s="0"+s;
}
return s;
});
ret.unshift("#");
return ret.join("");
};
dojo.provide("dojo.lfx.Animation");
dojo.lfx.Line=function(_3c6,end){
this.start=_3c6;
this.end=end;
if(dojo.lang.isArray(_3c6)){
var diff=[];
dojo.lang.forEach(this.start,function(s,i){
diff[i]=this.end[i]-s;
},this);
this.getValue=function(n){
var res=[];
dojo.lang.forEach(this.start,function(s,i){
res[i]=(diff[i]*n)+s;
},this);
return res;
};
}else{
var diff=end-_3c6;
this.getValue=function(n){
return (diff*n)+this.start;
};
}
};
if((dojo.render.html.khtml)&amp;&amp;(!dojo.render.html.safari)){
dojo.lfx.easeDefault=function(n){
return (parseFloat("0.5")+((Math.sin((n+parseFloat("1.5"))*Math.PI))/2));
};
}else{
dojo.lfx.easeDefault=function(n){
return (0.5+((Math.sin((n+1.5)*Math.PI))/2));
};
}
dojo.lfx.easeIn=function(n){
return Math.pow(n,3);
};
dojo.lfx.easeOut=function(n){
return (1-Math.pow(1-n,3));
};
dojo.lfx.easeInOut=function(n){
return ((3*Math.pow(n,2))-(2*Math.pow(n,3)));
};
dojo.lfx.IAnimation=function(){
};
dojo.lang.extend(dojo.lfx.IAnimation,{curve:null,duration:1000,easing:null,repeatCount:0,rate:10,handler:null,beforeBegin:null,onBegin:null,onAnimate:null,onEnd:null,onPlay:null,onPause:null,onStop:null,play:null,pause:null,stop:null,connect:function(evt,_3d6,_3d7){
if(!_3d7){
_3d7=_3d6;
_3d6=this;
}
_3d7=dojo.lang.hitch(_3d6,_3d7);
var _3d8=this[evt]||function(){
};
this[evt]=function(){
var ret=_3d8.apply(this,arguments);
_3d7.apply(this,arguments);
return ret;
};
return this;
},fire:function(evt,args){
if(this[evt]){
this[evt].apply(this,(args||[]));
}
return this;
},repeat:function(_3dc){
this.repeatCount=_3dc;
return this;
},_active:false,_paused:false});
dojo.lfx.Animation=function(_3dd,_3de,_3df,_3e0,_3e1,rate){
dojo.lfx.IAnimation.call(this);
if(dojo.lang.isNumber(_3dd)||(!_3dd&amp;&amp;_3de.getValue)){
rate=_3e1;
_3e1=_3e0;
_3e0=_3df;
_3df=_3de;
_3de=_3dd;
_3dd=null;
}else{
if(_3dd.getValue||dojo.lang.isArray(_3dd)){
rate=_3e0;
_3e1=_3df;
_3e0=_3de;
_3df=_3dd;
_3de=null;
_3dd=null;
}
}
if(dojo.lang.isArray(_3df)){
this.curve=new dojo.lfx.Line(_3df[0],_3df[1]);
}else{
this.curve=_3df;
}
if(_3de!=null&amp;&amp;_3de&gt;0){
this.duration=_3de;
}
if(_3e1){
this.repeatCount=_3e1;
}
if(rate){
this.rate=rate;
}
if(_3dd){
dojo.lang.forEach(["handler","beforeBegin","onBegin","onEnd","onPlay","onStop","onAnimate"],function(item){
if(_3dd[item]){
this.connect(item,_3dd[item]);
}
},this);
}
if(_3e0&amp;&amp;dojo.lang.isFunction(_3e0)){
this.easing=_3e0;
}
};
dojo.inherits(dojo.lfx.Animation,dojo.lfx.IAnimation);
dojo.lang.extend(dojo.lfx.Animation,{_startTime:null,_endTime:null,_timer:null,_percent:0,_startRepeatCount:0,play:function(_3e4,_3e5){
if(_3e5){
clearTimeout(this._timer);
this._active=false;
this._paused=false;
this._percent=0;
}else{
if(this._active&amp;&amp;!this._paused){
return this;
}
}
this.fire("handler",["beforeBegin"]);
this.fire("beforeBegin");
if(_3e4&gt;0){
setTimeout(dojo.lang.hitch(this,function(){
this.play(null,_3e5);
}),_3e4);
return this;
}
this._startTime=new Date().valueOf();
if(this._paused){
this._startTime-=(this.duration*this._percent/100);
}
this._endTime=this._startTime+this.duration;
this._active=true;
this._paused=false;
var step=this._percent/100;
var _3e7=this.curve.getValue(step);
if(this._percent==0){
if(!this._startRepeatCount){
this._startRepeatCount=this.repeatCount;
}
this.fire("handler",["begin",_3e7]);
this.fire("onBegin",[_3e7]);
}
this.fire("handler",["play",_3e7]);
this.fire("onPlay",[_3e7]);
this._cycle();
return this;
},pause:function(){
clearTimeout(this._timer);
if(!this._active){
return this;
}
this._paused=true;
var _3e8=this.curve.getValue(this._percent/100);
this.fire("handler",["pause",_3e8]);
this.fire("onPause",[_3e8]);
return this;
},gotoPercent:function(pct,_3ea){
clearTimeout(this._timer);
this._active=true;
this._paused=true;
this._percent=pct;
if(_3ea){
this.play();
}
return this;
},stop:function(_3eb){
clearTimeout(this._timer);
var step=this._percent/100;
if(_3eb){
step=1;
}
var _3ed=this.curve.getValue(step);
this.fire("handler",["stop",_3ed]);
this.fire("onStop",[_3ed]);
this._active=false;
this._paused=false;
return this;
},status:function(){
if(this._active){
return this._paused?"paused":"playing";
}else{
return "stopped";
}
return this;
},_cycle:function(){
clearTimeout(this._timer);
if(this._active){
var curr=new Date().valueOf();
var step=(curr-this._startTime)/(this._endTime-this._startTime);
if(step&gt;=1){
step=1;
this._percent=100;
}else{
this._percent=step*100;
}
if((this.easing)&amp;&amp;(dojo.lang.isFunction(this.easing))){
step=this.easing(step);
}
var _3f0=this.curve.getValue(step);
this.fire("handler",["animate",_3f0]);
this.fire("onAnimate",[_3f0]);
if(step&lt;1){
this._timer=setTimeout(dojo.lang.hitch(this,"_cycle"),this.rate);
}else{
this._active=false;
this.fire("handler",["end"]);
this.fire("onEnd");
if(this.repeatCount&gt;0){
this.repeatCount--;
this.play(null,true);
}else{
if(this.repeatCount==-1){
this.play(null,true);
}else{
if(this._startRepeatCount){
this.repeatCount=this._startRepeatCount;
this._startRepeatCount=0;
}
}
}
}
}
return this;
}});
dojo.lfx.Combine=function(_3f1){
dojo.lfx.IAnimation.call(this);
this._anims=[];
this._animsEnded=0;
var _3f2=arguments;
if(_3f2.length==1&amp;&amp;(dojo.lang.isArray(_3f2[0])||dojo.lang.isArrayLike(_3f2[0]))){
_3f2=_3f2[0];
}
dojo.lang.forEach(_3f2,function(anim){
this._anims.push(anim);
anim.connect("onEnd",dojo.lang.hitch(this,"_onAnimsEnded"));
},this);
};
dojo.inherits(dojo.lfx.Combine,dojo.lfx.IAnimation);
dojo.lang.extend(dojo.lfx.Combine,{_animsEnded:0,play:function(_3f4,_3f5){
if(!this._anims.length){
return this;
}
this.fire("beforeBegin");
if(_3f4&gt;0){
setTimeout(dojo.lang.hitch(this,function(){
this.play(null,_3f5);
}),_3f4);
return this;
}
if(_3f5||this._anims[0].percent==0){
this.fire("onBegin");
}
this.fire("onPlay");
this._animsCall("play",null,_3f5);
return this;
},pause:function(){
this.fire("onPause");
this._animsCall("pause");
return this;
},stop:function(_3f6){
this.fire("onStop");
this._animsCall("stop",_3f6);
return this;
},_onAnimsEnded:function(){
this._animsEnded++;
if(this._animsEnded&gt;=this._anims.length){
this.fire("onEnd");
}
return this;
},_animsCall:function(_3f7){
var args=[];
if(arguments.length&gt;1){
for(var i=1;i&lt;arguments.length;i++){
args.push(arguments[i]);
}
}
var _3fa=this;
dojo.lang.forEach(this._anims,function(anim){
anim[_3f7](args);
},_3fa);
return this;
}});
dojo.lfx.Chain=function(_3fc){
dojo.lfx.IAnimation.call(this);
this._anims=[];
this._currAnim=-1;
var _3fd=arguments;
if(_3fd.length==1&amp;&amp;(dojo.lang.isArray(_3fd[0])||dojo.lang.isArrayLike(_3fd[0]))){
_3fd=_3fd[0];
}
var _3fe=this;
dojo.lang.forEach(_3fd,function(anim,i,_401){
this._anims.push(anim);
if(i&lt;_401.length-1){
anim.connect("onEnd",dojo.lang.hitch(this,"_playNext"));
}else{
anim.connect("onEnd",dojo.lang.hitch(this,function(){
this.fire("onEnd");
}));
}
},this);
};
dojo.inherits(dojo.lfx.Chain,dojo.lfx.IAnimation);
dojo.lang.extend(dojo.lfx.Chain,{_currAnim:-1,play:function(_402,_403){
if(!this._anims.length){
return this;
}
if(_403||!this._anims[this._currAnim]){
this._currAnim=0;
}
var _404=this._anims[this._currAnim];
this.fire("beforeBegin");
if(_402&gt;0){
setTimeout(dojo.lang.hitch(this,function(){
this.play(null,_403);
}),_402);
return this;
}
if(_404){
if(this._currAnim==0){
this.fire("handler",["begin",this._currAnim]);
this.fire("onBegin",[this._currAnim]);
}
this.fire("onPlay",[this._currAnim]);
_404.play(null,_403);
}
return this;
},pause:function(){
if(this._anims[this._currAnim]){
this._anims[this._currAnim].pause();
this.fire("onPause",[this._currAnim]);
}
return this;
},playPause:function(){
if(this._anims.length==0){
return this;
}
if(this._currAnim==-1){
this._currAnim=0;
}
var _405=this._anims[this._currAnim];
if(_405){
if(!_405._active||_405._paused){
this.play();
}else{
this.pause();
}
}
return this;
},stop:function(){
var _406=this._anims[this._currAnim];
if(_406){
_406.stop();
this.fire("onStop",[this._currAnim]);
}
return _406;
},_playNext:function(){
if(this._currAnim==-1||this._anims.length==0){
return this;
}
this._currAnim++;
if(this._anims[this._currAnim]){
this._anims[this._currAnim].play(null,true);
}
return this;
}});
dojo.lfx.combine=function(_407){
var _408=arguments;
if(dojo.lang.isArray(arguments[0])){
_408=arguments[0];
}
if(_408.length==1){
return _408[0];
}
return new dojo.lfx.Combine(_408);
};
dojo.lfx.chain=function(_409){
var _40a=arguments;
if(dojo.lang.isArray(arguments[0])){
_40a=arguments[0];
}
if(_40a.length==1){
return _40a[0];
}
return new dojo.lfx.Chain(_40a);
};
dojo.provide("dojo.html.common");
dojo.lang.mixin(dojo.html,dojo.dom);
dojo.html.body=function(){
dojo.deprecated("dojo.html.body() moved to dojo.body()","0.5");
return dojo.body();
};
dojo.html.getEventTarget=function(evt){
if(!evt){
evt=dojo.global().event||{};
}
var t=(evt.srcElement?evt.srcElement:(evt.target?evt.target:null));
while((t)&amp;&amp;(t.nodeType!=1)){
t=t.parentNode;
}
return t;
};
dojo.html.getViewport=function(){
var _40d=dojo.global();
var _40e=dojo.doc();
var w=0;
var h=0;
if(dojo.render.html.mozilla){
w=_40e.documentElement.clientWidth;
h=_40d.innerHeight;
}else{
if(!dojo.render.html.opera&amp;&amp;_40d.innerWidth){
w=_40d.innerWidth;
h=_40d.innerHeight;
}else{
if(!dojo.render.html.opera&amp;&amp;dojo.exists(_40e,"documentElement.clientWidth")){
var w2=_40e.documentElement.clientWidth;
if(!w||w2&amp;&amp;w2&lt;w){
w=w2;
}
h=_40e.documentElement.clientHeight;
}else{
if(dojo.body().clientWidth){
w=dojo.body().clientWidth;
h=dojo.body().clientHeight;
}
}
}
}
return {width:w,height:h};
};
dojo.html.getScroll=function(){
var _412=dojo.global();
var _413=dojo.doc();
var top=_412.pageYOffset||_413.documentElement.scrollTop||dojo.body().scrollTop||0;
var left=_412.pageXOffset||_413.documentElement.scrollLeft||dojo.body().scrollLeft||0;
return {top:top,left:left,offset:{x:left,y:top}};
};
dojo.html.getParentByType=function(node,type){
var _418=dojo.doc();
var _419=dojo.byId(node);
type=type.toLowerCase();
while((_419)&amp;&amp;(_419.nodeName.toLowerCase()!=type)){
if(_419==(_418["body"]||_418["documentElement"])){
return null;
}
_419=_419.parentNode;
}
return _419;
};
dojo.html.getAttribute=function(node,attr){
node=dojo.byId(node);
if((!node)||(!node.getAttribute)){
return null;
}
var ta=typeof attr=="string"?attr:new String(attr);
var v=node.getAttribute(ta.toUpperCase());
if((v)&amp;&amp;(typeof v=="string")&amp;&amp;(v!="")){
return v;
}
if(v&amp;&amp;v.value){
return v.value;
}
if((node.getAttributeNode)&amp;&amp;(node.getAttributeNode(ta))){
return (node.getAttributeNode(ta)).value;
}else{
if(node.getAttribute(ta)){
return node.getAttribute(ta);
}else{
if(node.getAttribute(ta.toLowerCase())){
return node.getAttribute(ta.toLowerCase());
}
}
}
return null;
};
dojo.html.hasAttribute=function(node,attr){
return dojo.html.getAttribute(dojo.byId(node),attr)?true:false;
};
dojo.html.getCursorPosition=function(e){
e=e||dojo.global().event;
var _421={x:0,y:0};
if(e.pageX||e.pageY){
_421.x=e.pageX;
_421.y=e.pageY;
}else{
var de=dojo.doc().documentElement;
var db=dojo.body();
_421.x=e.clientX+((de||db)["scrollLeft"])-((de||db)["clientLeft"]);
_421.y=e.clientY+((de||db)["scrollTop"])-((de||db)["clientTop"]);
}
return _421;
};
dojo.html.isTag=function(node){
node=dojo.byId(node);
if(node&amp;&amp;node.tagName){
for(var i=1;i&lt;arguments.length;i++){
if(node.tagName.toLowerCase()==String(arguments[i]).toLowerCase()){
return String(arguments[i]).toLowerCase();
}
}
}
return "";
};
if(dojo.render.html.ie&amp;&amp;!dojo.render.html.ie70){
if(window.location.href.substr(0,6).toLowerCase()!="https:"){
(function(){
var _426=dojo.doc().createElement("script");
_426.src="javascript:'dojo.html.createExternalElement=function(doc, tag){ return doc.createElement(tag); }'";
dojo.doc().getElementsByTagName("head")[0].appendChild(_426);
})();
}
}else{
dojo.html.createExternalElement=function(doc,tag){
return doc.createElement(tag);
};
}
dojo.html._callDeprecated=function(_429,_42a,args,_42c,_42d){
dojo.deprecated("dojo.html."+_429,"replaced by dojo.html."+_42a+"("+(_42c?"node, {"+_42c+": "+_42c+"}":"")+")"+(_42d?"."+_42d:""),"0.5");
var _42e=[];
if(_42c){
var _42f={};
_42f[_42c]=args[1];
_42e.push(args[0]);
_42e.push(_42f);
}else{
_42e=args;
}
var ret=dojo.html[_42a].apply(dojo.html,args);
if(_42d){
return ret[_42d];
}else{
return ret;
}
};
dojo.html.getViewportWidth=function(){
return dojo.html._callDeprecated("getViewportWidth","getViewport",arguments,null,"width");
};
dojo.html.getViewportHeight=function(){
return dojo.html._callDeprecated("getViewportHeight","getViewport",arguments,null,"height");
};
dojo.html.getViewportSize=function(){
return dojo.html._callDeprecated("getViewportSize","getViewport",arguments);
};
dojo.html.getScrollTop=function(){
return dojo.html._callDeprecated("getScrollTop","getScroll",arguments,null,"top");
};
dojo.html.getScrollLeft=function(){
return dojo.html._callDeprecated("getScrollLeft","getScroll",arguments,null,"left");
};
dojo.html.getScrollOffset=function(){
return dojo.html._callDeprecated("getScrollOffset","getScroll",arguments,null,"offset");
};
dojo.provide("dojo.uri.Uri");
dojo.uri=new function(){
this.dojoUri=function(uri){
return new dojo.uri.Uri(dojo.hostenv.getBaseScriptUri(),uri);
};
this.moduleUri=function(_432,uri){
var loc=dojo.hostenv.getModuleSymbols(_432).join("/");
if(!loc){
return null;
}
if(loc.lastIndexOf("/")!=loc.length-1){
loc+="/";
}
var _435=loc.indexOf(":");
var _436=loc.indexOf("/");
if(loc.charAt(0)!="/"&amp;&amp;(_435==-1||_435&gt;_436)){
loc=dojo.hostenv.getBaseScriptUri()+loc;
}
return new dojo.uri.Uri(loc,uri);
};
this.Uri=function(){
var uri=arguments[0];
for(var i=1;i&lt;arguments.length;i++){
if(!arguments[i]){
continue;
}
var _439=new dojo.uri.Uri(arguments[i].toString());
var _43a=new dojo.uri.Uri(uri.toString());
if((_439.path=="")&amp;&amp;(_439.scheme==null)&amp;&amp;(_439.authority==null)&amp;&amp;(_439.query==null)){
if(_439.fragment!=null){
_43a.fragment=_439.fragment;
}
_439=_43a;
}else{
if(_439.scheme==null){
_439.scheme=_43a.scheme;
if(_439.authority==null){
_439.authority=_43a.authority;
if(_439.path.charAt(0)!="/"){
var path=_43a.path.substring(0,_43a.path.lastIndexOf("/")+1)+_439.path;
var segs=path.split("/");
for(var j=0;j&lt;segs.length;j++){
if(segs[j]=="."){
if(j==segs.length-1){
segs[j]="";
}else{
segs.splice(j,1);
j--;
}
}else{
if(j&gt;0&amp;&amp;!(j==1&amp;&amp;segs[0]=="")&amp;&amp;segs[j]==".."&amp;&amp;segs[j-1]!=".."){
if(j==segs.length-1){
segs.splice(j,1);
segs[j-1]="";
}else{
segs.splice(j-1,2);
j-=2;
}
}
}
}
_439.path=segs.join("/");
}
}
}
}
uri="";
if(_439.scheme!=null){
uri+=_439.scheme+":";
}
if(_439.authority!=null){
uri+="//"+_439.authority;
}
uri+=_439.path;
if(_439.query!=null){
uri+="?"+_439.query;
}
if(_439.fragment!=null){
uri+="#"+_439.fragment;
}
}
this.uri=uri.toString();
var _43e="^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$";
var r=this.uri.match(new RegExp(_43e));
this.scheme=r[2]||(r[1]?"":null);
this.authority=r[4]||(r[3]?"":null);
this.path=r[5];
this.query=r[7]||(r[6]?"":null);
this.fragment=r[9]||(r[8]?"":null);
if(this.authority!=null){
_43e="^((([^:]+:)?([^@]+))@)?([^:]*)(:([0-9]+))?$";
r=this.authority.match(new RegExp(_43e));
this.user=r[3]||null;
this.password=r[4]||null;
this.host=r[5];
this.port=r[7]||null;
}
this.toString=function(){
return this.uri;
};
};
};
dojo.provide("dojo.html.style");
dojo.html.getClass=function(node){
node=dojo.byId(node);
if(!node){
return "";
}
var cs="";
if(node.className){
cs=node.className;
}else{
if(dojo.html.hasAttribute(node,"class")){
cs=dojo.html.getAttribute(node,"class");
}
}
return cs.replace(/^\s+|\s+$/g,"");
};
dojo.html.getClasses=function(node){
var c=dojo.html.getClass(node);
return (c=="")?[]:c.split(/\s+/g);
};
dojo.html.hasClass=function(node,_445){
return (new RegExp("(^|\\s+)"+_445+"(\\s+|$)")).test(dojo.html.getClass(node));
};
dojo.html.prependClass=function(node,_447){
_447+=" "+dojo.html.getClass(node);
return dojo.html.setClass(node,_447);
};
dojo.html.addClass=function(node,_449){
if(dojo.html.hasClass(node,_449)){
return false;
}
_449=(dojo.html.getClass(node)+" "+_449).replace(/^\s+|\s+$/g,"");
return dojo.html.setClass(node,_449);
};
dojo.html.setClass=function(node,_44b){
node=dojo.byId(node);
var cs=new String(_44b);
try{
if(typeof node.className=="string"){
node.className=cs;
}else{
if(node.setAttribute){
node.setAttribute("class",_44b);
node.className=cs;
}else{
return false;
}
}
}
catch(e){
dojo.debug("dojo.html.setClass() failed",e);
}
return true;
};
dojo.html.removeClass=function(node,_44e,_44f){
try{
if(!_44f){
var _450=dojo.html.getClass(node).replace(new RegExp("(^|\\s+)"+_44e+"(\\s+|$)"),"$1$2");
}else{
var _450=dojo.html.getClass(node).replace(_44e,"");
}
dojo.html.setClass(node,_450);
}
catch(e){
dojo.debug("dojo.html.removeClass() failed",e);
}
return true;
};
dojo.html.replaceClass=function(node,_452,_453){
dojo.html.removeClass(node,_453);
dojo.html.addClass(node,_452);
};
dojo.html.classMatchType={ContainsAll:0,ContainsAny:1,IsOnly:2};
dojo.html.getElementsByClass=function(_454,_455,_456,_457,_458){
_458=false;
var _459=dojo.doc();
_455=dojo.byId(_455)||_459;
var _45a=_454.split(/\s+/g);
var _45b=[];
if(_457!=1&amp;&amp;_457!=2){
_457=0;
}
var _45c=new RegExp("(\\s|^)(("+_45a.join(")|(")+"))(\\s|$)");
var _45d=_45a.join(" ").length;
var _45e=[];
if(!_458&amp;&amp;_459.evaluate){
var _45f=".//"+(_456||"*")+"[contains(";
if(_457!=dojo.html.classMatchType.ContainsAny){
_45f+="concat(' ',@class,' '), ' "+_45a.join(" ') and contains(concat(' ',@class,' '), ' ")+" ')";
if(_457==2){
_45f+=" and string-length(@class)="+_45d+"]";
}else{
_45f+="]";
}
}else{
_45f+="concat(' ',@class,' '), ' "+_45a.join(" ') or contains(concat(' ',@class,' '), ' ")+" ')]";
}
var _460=_459.evaluate(_45f,_455,null,XPathResult.ANY_TYPE,null);
var _461=_460.iterateNext();
while(_461){
try{
_45e.push(_461);
_461=_460.iterateNext();
}
catch(e){
break;
}
}
return _45e;
}else{
if(!_456){
_456="*";
}
_45e=_455.getElementsByTagName(_456);
var node,i=0;
outer:
while(node=_45e[i++]){
var _464=dojo.html.getClasses(node);
if(_464.length==0){
continue outer;
}
var _465=0;
for(var j=0;j&lt;_464.length;j++){
if(_45c.test(_464[j])){
if(_457==dojo.html.classMatchType.ContainsAny){
_45b.push(node);
continue outer;
}else{
_465++;
}
}else{
if(_457==dojo.html.classMatchType.IsOnly){
continue outer;
}
}
}
if(_465==_45a.length){
if((_457==dojo.html.classMatchType.IsOnly)&amp;&amp;(_465==_464.length)){
_45b.push(node);
}else{
if(_457==dojo.html.classMatchType.ContainsAll){
_45b.push(node);
}
}
}
}
return _45b;
}
};
dojo.html.getElementsByClassName=dojo.html.getElementsByClass;
dojo.html.toCamelCase=function(_467){
var arr=_467.split("-"),cc=arr[0];
for(var i=1;i&lt;arr.length;i++){
cc+=arr[i].charAt(0).toUpperCase()+arr[i].substring(1);
}
return cc;
};
dojo.html.toSelectorCase=function(_46b){
return _46b.replace(/([A-Z])/g,"-$1").toLowerCase();
};
if(dojo.render.html.ie){
dojo.html.getComputedStyle=function(node,_46d,_46e){
node=dojo.byId(node);
if(!node||!node.currentStyle){
return _46e;
}
return node.currentStyle[dojo.html.toCamelCase(_46d)];
};
dojo.html.getComputedStyles=function(node){
return node.currentStyle;
};
}else{
dojo.html.getComputedStyle=function(node,_471,_472){
node=dojo.byId(node);
if(!node||!node.style){
return _472;
}
var s=document.defaultView.getComputedStyle(node,null);
return (s&amp;&amp;s[dojo.html.toCamelCase(_471)])||"";
};
dojo.html.getComputedStyles=function(node){
return document.defaultView.getComputedStyle(node,null);
};
}
dojo.html.getStyleProperty=function(node,_476){
node=dojo.byId(node);
return (node&amp;&amp;node.style?node.style[dojo.html.toCamelCase(_476)]:undefined);
};
dojo.html.getStyle=function(node,_478){
var _479=dojo.html.getStyleProperty(node,_478);
return (_479?_479:dojo.html.getComputedStyle(node,_478));
};
dojo.html.setStyle=function(node,_47b,_47c){
node=dojo.byId(node);
if(node&amp;&amp;node.style){
var _47d=dojo.html.toCamelCase(_47b);
node.style[_47d]=_47c;
}
};
dojo.html.setStyleText=function(_47e,text){
try{
_47e.style.cssText=text;
}
catch(e){
_47e.setAttribute("style",text);
}
};
dojo.html.copyStyle=function(_480,_481){
if(!_481.style.cssText){
_480.setAttribute("style",_481.getAttribute("style"));
}else{
_480.style.cssText=_481.style.cssText;
}
dojo.html.addClass(_480,dojo.html.getClass(_481));
};
dojo.html.getUnitValue=function(node,_483,_484){
var s=dojo.html.getComputedStyle(node,_483);
if((!s)||((s=="auto")&amp;&amp;(_484))){
return {value:0,units:"px"};
}
var _486=s.match(/(\-?[\d.]+)([a-z%]*)/i);
if(!_486){
return dojo.html.getUnitValue.bad;
}
return {value:Number(_486[1]),units:_486[2].toLowerCase()};
};
dojo.html.getUnitValue.bad={value:NaN,units:""};
if(dojo.render.html.ie){
dojo.html.toPixelValue=function(_487,_488){
if(!_488){
return 0;
}
if(_488.slice(-2)=="px"){
return parseFloat(_488);
}
var _489=0;
with(_487){
var _48a=style.left;
var _48b=runtimeStyle.left;
runtimeStyle.left=currentStyle.left;
try{
style.left=_488||0;
_489=style.pixelLeft;
style.left=_48a;
runtimeStyle.left=_48b;
}
catch(e){
}
}
return _489;
};
}else{
dojo.html.toPixelValue=function(_48c,_48d){
return (_48d&amp;&amp;(_48d.slice(-2)=="px")?parseFloat(_48d):0);
};
}
dojo.html.getPixelValue=function(node,_48f,_490){
return dojo.html.toPixelValue(node,dojo.html.getComputedStyle(node,_48f));
};
dojo.html.setPositivePixelValue=function(node,_492,_493){
if(isNaN(_493)){
return false;
}
node.style[_492]=Math.max(0,_493)+"px";
return true;
};
dojo.html.styleSheet=null;
dojo.html.insertCssRule=function(_494,_495,_496){
if(!dojo.html.styleSheet){
if(document.createStyleSheet){
dojo.html.styleSheet=document.createStyleSheet();
}else{
if(document.styleSheets[0]){
dojo.html.styleSheet=document.styleSheets[0];
}else{
return null;
}
}
}
if(arguments.length&lt;3){
if(dojo.html.styleSheet.cssRules){
_496=dojo.html.styleSheet.cssRules.length;
}else{
if(dojo.html.styleSheet.rules){
_496=dojo.html.styleSheet.rules.length;
}else{
return null;
}
}
}
if(dojo.html.styleSheet.insertRule){
var rule=_494+" { "+_495+" }";
return dojo.html.styleSheet.insertRule(rule,_496);
}else{
if(dojo.html.styleSheet.addRule){
return dojo.html.styleSheet.addRule(_494,_495,_496);
}else{
return null;
}
}
};
dojo.html.removeCssRule=function(_498){
if(!dojo.html.styleSheet){
dojo.debug("no stylesheet defined for removing rules");
return false;
}
if(dojo.render.html.ie){
if(!_498){
_498=dojo.html.styleSheet.rules.length;
dojo.html.styleSheet.removeRule(_498);
}
}else{
if(document.styleSheets[0]){
if(!_498){
_498=dojo.html.styleSheet.cssRules.length;
}
dojo.html.styleSheet.deleteRule(_498);
}
}
return true;
};
dojo.html._insertedCssFiles=[];
dojo.html.insertCssFile=function(URI,doc,_49b,_49c){
if(!URI){
return;
}
if(!doc){
doc=document;
}
var _49d=dojo.hostenv.getText(URI,false,_49c);
if(_49d===null){
return;
}
_49d=dojo.html.fixPathsInCssText(_49d,URI);
if(_49b){
var idx=-1,node,ent=dojo.html._insertedCssFiles;
for(var i=0;i&lt;ent.length;i++){
if((ent[i].doc==doc)&amp;&amp;(ent[i].cssText==_49d)){
idx=i;
node=ent[i].nodeRef;
break;
}
}
if(node){
var _4a2=doc.getElementsByTagName("style");
for(var i=0;i&lt;_4a2.length;i++){
if(_4a2[i]==node){
return;
}
}
dojo.html._insertedCssFiles.shift(idx,1);
}
}
var _4a3=dojo.html.insertCssText(_49d,doc);
dojo.html._insertedCssFiles.push({"doc":doc,"cssText":_49d,"nodeRef":_4a3});
if(_4a3&amp;&amp;djConfig.isDebug){
_4a3.setAttribute("dbgHref",URI);
}
return _4a3;
};
dojo.html.insertCssText=function(_4a4,doc,URI){
if(!_4a4){
return;
}
if(!doc){
doc=document;
}
if(URI){
_4a4=dojo.html.fixPathsInCssText(_4a4,URI);
}
var _4a7=doc.createElement("style");
_4a7.setAttribute("type","text/css");
var head=doc.getElementsByTagName("head")[0];
if(!head){
dojo.debug("No head tag in document, aborting styles");
return;
}else{
head.appendChild(_4a7);
}
if(_4a7.styleSheet){
var _4a9=function(){
try{
_4a7.styleSheet.cssText=_4a4;
}
catch(e){
dojo.debug(e);
}
};
if(_4a7.styleSheet.disabled){
setTimeout(_4a9,10);
}else{
_4a9();
}
}else{
var _4aa=doc.createTextNode(_4a4);
_4a7.appendChild(_4aa);
}
return _4a7;
};
dojo.html.fixPathsInCssText=function(_4ab,URI){
if(!_4ab||!URI){
return;
}
var _4ad,str="",url="",_4b0="[\\t\\s\\w\\(\\)\\/\\.\\\\'\"-:#=&amp;?~]+";
var _4b1=new RegExp("url\\(\\s*("+_4b0+")\\s*\\)");
var _4b2=/(file|https?|ftps?):\/\//;
regexTrim=new RegExp("^[\\s]*(['\"]?)("+_4b0+")\\1[\\s]*?$");
if(dojo.render.html.ie55||dojo.render.html.ie60){
var _4b3=new RegExp("AlphaImageLoader\\((.*)src=['\"]("+_4b0+")['\"]");
while(_4ad=_4b3.exec(_4ab)){
url=_4ad[2].replace(regexTrim,"$2");
if(!_4b2.exec(url)){
url=(new dojo.uri.Uri(URI,url).toString());
}
str+=_4ab.substring(0,_4ad.index)+"AlphaImageLoader("+_4ad[1]+"src='"+url+"'";
_4ab=_4ab.substr(_4ad.index+_4ad[0].length);
}
_4ab=str+_4ab;
str="";
}
while(_4ad=_4b1.exec(_4ab)){
url=_4ad[1].replace(regexTrim,"$2");
if(!_4b2.exec(url)){
url=(new dojo.uri.Uri(URI,url).toString());
}
str+=_4ab.substring(0,_4ad.index)+"url("+url+")";
_4ab=_4ab.substr(_4ad.index+_4ad[0].length);
}
return str+_4ab;
};
dojo.html.setActiveStyleSheet=function(_4b4){
var i=0,a,els=dojo.doc().getElementsByTagName("link");
while(a=els[i++]){
if(a.getAttribute("rel").indexOf("style")!=-1&amp;&amp;a.getAttribute("title")){
a.disabled=true;
if(a.getAttribute("title")==_4b4){
a.disabled=false;
}
}
}
};
dojo.html.getActiveStyleSheet=function(){
var i=0,a,els=dojo.doc().getElementsByTagName("link");
while(a=els[i++]){
if(a.getAttribute("rel").indexOf("style")!=-1&amp;&amp;a.getAttribute("title")&amp;&amp;!a.disabled){
return a.getAttribute("title");
}
}
return null;
};
dojo.html.getPreferredStyleSheet=function(){
var i=0,a,els=dojo.doc().getElementsByTagName("link");
while(a=els[i++]){
if(a.getAttribute("rel").indexOf("style")!=-1&amp;&amp;a.getAttribute("rel").indexOf("alt")==-1&amp;&amp;a.getAttribute("title")){
return a.getAttribute("title");
}
}
return null;
};
dojo.html.applyBrowserClass=function(node){
var drh=dojo.render.html;
var _4c0={dj_ie:drh.ie,dj_ie55:drh.ie55,dj_ie6:drh.ie60,dj_ie7:drh.ie70,dj_iequirks:drh.ie&amp;&amp;drh.quirks,dj_opera:drh.opera,dj_opera8:drh.opera&amp;&amp;(Math.floor(dojo.render.version)==8),dj_opera9:drh.opera&amp;&amp;(Math.floor(dojo.render.version)==9),dj_khtml:drh.khtml,dj_safari:drh.safari,dj_gecko:drh.mozilla};
for(var p in _4c0){
if(_4c0[p]){
dojo.html.addClass(node,p);
}
}
};
dojo.provide("dojo.html.display");
dojo.html._toggle=function(node,_4c3,_4c4){
node=dojo.byId(node);
_4c4(node,!_4c3(node));
return _4c3(node);
};
dojo.html.show=function(node){
node=dojo.byId(node);
if(dojo.html.getStyleProperty(node,"display")=="none"){
dojo.html.setStyle(node,"display",(node.dojoDisplayCache||""));
node.dojoDisplayCache=undefined;
}
};
dojo.html.hide=function(node){
node=dojo.byId(node);
if(typeof node["dojoDisplayCache"]=="undefined"){
var d=dojo.html.getStyleProperty(node,"display");
if(d!="none"){
node.dojoDisplayCache=d;
}
}
dojo.html.setStyle(node,"display","none");
};
dojo.html.setShowing=function(node,_4c9){
dojo.html[(_4c9?"show":"hide")](node);
};
dojo.html.isShowing=function(node){
return (dojo.html.getStyleProperty(node,"display")!="none");
};
dojo.html.toggleShowing=function(node){
return dojo.html._toggle(node,dojo.html.isShowing,dojo.html.setShowing);
};
dojo.html.displayMap={tr:"",td:"",th:"",img:"inline",span:"inline",input:"inline",button:"inline"};
dojo.html.suggestDisplayByTagName=function(node){
node=dojo.byId(node);
if(node&amp;&amp;node.tagName){
var tag=node.tagName.toLowerCase();
return (tag in dojo.html.displayMap?dojo.html.displayMap[tag]:"block");
}
};
dojo.html.setDisplay=function(node,_4cf){
dojo.html.setStyle(node,"display",((_4cf instanceof String||typeof _4cf=="string")?_4cf:(_4cf?dojo.html.suggestDisplayByTagName(node):"none")));
};
dojo.html.isDisplayed=function(node){
return (dojo.html.getComputedStyle(node,"display")!="none");
};
dojo.html.toggleDisplay=function(node){
return dojo.html._toggle(node,dojo.html.isDisplayed,dojo.html.setDisplay);
};
dojo.html.setVisibility=function(node,_4d3){
dojo.html.setStyle(node,"visibility",((_4d3 instanceof String||typeof _4d3=="string")?_4d3:(_4d3?"visible":"hidden")));
};
dojo.html.isVisible=function(node){
return (dojo.html.getComputedStyle(node,"visibility")!="hidden");
};
dojo.html.toggleVisibility=function(node){
return dojo.html._toggle(node,dojo.html.isVisible,dojo.html.setVisibility);
};
dojo.html.setOpacity=function(node,_4d7,_4d8){
node=dojo.byId(node);
var h=dojo.render.html;
if(!_4d8){
if(_4d7&gt;=1){
if(h.ie){
dojo.html.clearOpacity(node);
return;
}else{
_4d7=0.999999;
}
}else{
if(_4d7&lt;0){
_4d7=0;
}
}
}
if(h.ie){
if(node.nodeName.toLowerCase()=="tr"){
var tds=node.getElementsByTagName("td");
for(var x=0;x&lt;tds.length;x++){
tds[x].style.filter="Alpha(Opacity="+_4d7*100+")";
}
}
node.style.filter="Alpha(Opacity="+_4d7*100+")";
}else{
if(h.moz){
node.style.opacity=_4d7;
node.style.MozOpacity=_4d7;
}else{
if(h.safari){
node.style.opacity=_4d7;
node.style.KhtmlOpacity=_4d7;
}else{
node.style.opacity=_4d7;
}
}
}
};
dojo.html.clearOpacity=function(node){
node=dojo.byId(node);
var ns=node.style;
var h=dojo.render.html;
if(h.ie){
try{
if(node.filters&amp;&amp;node.filters.alpha){
ns.filter="";
}
}
catch(e){
}
}else{
if(h.moz){
ns.opacity=1;
ns.MozOpacity=1;
}else{
if(h.safari){
ns.opacity=1;
ns.KhtmlOpacity=1;
}else{
ns.opacity=1;
}
}
}
};
dojo.html.getOpacity=function(node){
node=dojo.byId(node);
var h=dojo.render.html;
if(h.ie){
var opac=(node.filters&amp;&amp;node.filters.alpha&amp;&amp;typeof node.filters.alpha.opacity=="number"?node.filters.alpha.opacity:100)/100;
}else{
var opac=node.style.opacity||node.style.MozOpacity||node.style.KhtmlOpacity||1;
}
return opac&gt;=0.999999?1:Number(opac);
};
dojo.provide("dojo.html.color");
dojo.html.getBackgroundColor=function(node){
node=dojo.byId(node);
var _4e3;
do{
_4e3=dojo.html.getStyle(node,"background-color");
if(_4e3.toLowerCase()=="rgba(0, 0, 0, 0)"){
_4e3="transparent";
}
if(node==document.getElementsByTagName("body")[0]){
node=null;
break;
}
node=node.parentNode;
}while(node&amp;&amp;dojo.lang.inArray(["transparent",""],_4e3));
if(_4e3=="transparent"){
_4e3=[255,255,255,0];
}else{
_4e3=dojo.gfx.color.extractRGB(_4e3);
}
return _4e3;
};
dojo.provide("dojo.html.layout");
dojo.html.sumAncestorProperties=function(node,prop){
node=dojo.byId(node);
if(!node){
return 0;
}
var _4e6=0;
while(node){
if(dojo.html.getComputedStyle(node,"position")=="fixed"){
return 0;
}
var val=node[prop];
if(val){
_4e6+=val-0;
if(node==dojo.body()){
break;
}
}
node=node.parentNode;
}
return _4e6;
};
dojo.html.setStyleAttributes=function(node,_4e9){
node=dojo.byId(node);
var _4ea=_4e9.replace(/(;)?\s*$/,"").split(";");
for(var i=0;i&lt;_4ea.length;i++){
var _4ec=_4ea[i].split(":");
var name=_4ec[0].replace(/\s*$/,"").replace(/^\s*/,"").toLowerCase();
var _4ee=_4ec[1].replace(/\s*$/,"").replace(/^\s*/,"");
switch(name){
case "opacity":
dojo.html.setOpacity(node,_4ee);
break;
case "content-height":
dojo.html.setContentBox(node,{height:_4ee});
break;
case "content-width":
dojo.html.setContentBox(node,{width:_4ee});
break;
case "outer-height":
dojo.html.setMarginBox(node,{height:_4ee});
break;
case "outer-width":
dojo.html.setMarginBox(node,{width:_4ee});
break;
default:
node.style[dojo.html.toCamelCase(name)]=_4ee;
}
}
};
dojo.html.boxSizing={MARGIN_BOX:"margin-box",BORDER_BOX:"border-box",PADDING_BOX:"padding-box",CONTENT_BOX:"content-box"};
dojo.html.getAbsolutePosition=dojo.html.abs=function(node,_4f0,_4f1){
node=dojo.byId(node,node.ownerDocument);
var ret={x:0,y:0};
var bs=dojo.html.boxSizing;
if(!_4f1){
_4f1=bs.CONTENT_BOX;
}
var _4f4=2;
var _4f5;
switch(_4f1){
case bs.MARGIN_BOX:
_4f5=3;
break;
case bs.BORDER_BOX:
_4f5=2;
break;
case bs.PADDING_BOX:
default:
_4f5=1;
break;
case bs.CONTENT_BOX:
_4f5=0;
break;
}
var h=dojo.render.html;
var db=document["body"]||document["documentElement"];
if(h.ie){
with(node.getBoundingClientRect()){
ret.x=left-2;
ret.y=top-2;
}
}else{
if(document.getBoxObjectFor){
_4f4=1;
try{
var bo=document.getBoxObjectFor(node);
ret.x=bo.x-dojo.html.sumAncestorProperties(node,"scrollLeft");
ret.y=bo.y-dojo.html.sumAncestorProperties(node,"scrollTop");
}
catch(e){
}
}else{
if(node["offsetParent"]){
var _4f9;
if((h.safari)&amp;&amp;(node.style.getPropertyValue("position")=="absolute")&amp;&amp;(node.parentNode==db)){
_4f9=db;
}else{
_4f9=db.parentNode;
}
if(node.parentNode!=db){
var nd=node;
if(dojo.render.html.opera){
nd=db;
}
ret.x-=dojo.html.sumAncestorProperties(nd,"scrollLeft");
ret.y-=dojo.html.sumAncestorProperties(nd,"scrollTop");
}
var _4fb=node;
do{
var n=_4fb["offsetLeft"];
if(!h.opera||n&gt;0){
ret.x+=isNaN(n)?0:n;
}
var m=_4fb["offsetTop"];
ret.y+=isNaN(m)?0:m;
_4fb=_4fb.offsetParent;
}while((_4fb!=_4f9)&amp;&amp;(_4fb!=null));
}else{
if(node["x"]&amp;&amp;node["y"]){
ret.x+=isNaN(node.x)?0:node.x;
ret.y+=isNaN(node.y)?0:node.y;
}
}
}
}
if(_4f0){
var _4fe=dojo.html.getScroll();
ret.y+=_4fe.top;
ret.x+=_4fe.left;
}
var _4ff=[dojo.html.getPaddingExtent,dojo.html.getBorderExtent,dojo.html.getMarginExtent];
if(_4f4&gt;_4f5){
for(var i=_4f5;i&lt;_4f4;++i){
ret.y+=_4ff[i](node,"top");
ret.x+=_4ff[i](node,"left");
}
}else{
if(_4f4&lt;_4f5){
for(var i=_4f5;i&gt;_4f4;--i){
ret.y-=_4ff[i-1](node,"top");
ret.x-=_4ff[i-1](node,"left");
}
}
}
ret.top=ret.y;
ret.left=ret.x;
return ret;
};
dojo.html.isPositionAbsolute=function(node){
return (dojo.html.getComputedStyle(node,"position")=="absolute");
};
dojo.html._sumPixelValues=function(node,_503,_504){
var _505=0;
for(var x=0;x&lt;_503.length;x++){
_505+=dojo.html.getPixelValue(node,_503[x],_504);
}
return _505;
};
dojo.html.getMargin=function(node){
return {width:dojo.html._sumPixelValues(node,["margin-left","margin-right"],(dojo.html.getComputedStyle(node,"position")=="absolute")),height:dojo.html._sumPixelValues(node,["margin-top","margin-bottom"],(dojo.html.getComputedStyle(node,"position")=="absolute"))};
};
dojo.html.getBorder=function(node){
return {width:dojo.html.getBorderExtent(node,"left")+dojo.html.getBorderExtent(node,"right"),height:dojo.html.getBorderExtent(node,"top")+dojo.html.getBorderExtent(node,"bottom")};
};
dojo.html.getBorderExtent=function(node,side){
return (dojo.html.getStyle(node,"border-"+side+"-style")=="none"?0:dojo.html.getPixelValue(node,"border-"+side+"-width"));
};
dojo.html.getMarginExtent=function(node,side){
return dojo.html._sumPixelValues(node,["margin-"+side],dojo.html.isPositionAbsolute(node));
};
dojo.html.getPaddingExtent=function(node,side){
return dojo.html._sumPixelValues(node,["padding-"+side],true);
};
dojo.html.getPadding=function(node){
return {width:dojo.html._sumPixelValues(node,["padding-left","padding-right"],true),height:dojo.html._sumPixelValues(node,["padding-top","padding-bottom"],true)};
};
dojo.html.getPadBorder=function(node){
var pad=dojo.html.getPadding(node);
var _512=dojo.html.getBorder(node);
return {width:pad.width+_512.width,height:pad.height+_512.height};
};
dojo.html.getBoxSizing=function(node){
var h=dojo.render.html;
var bs=dojo.html.boxSizing;
if(((h.ie)||(h.opera))&amp;&amp;node.nodeName.toLowerCase()!="img"){
var cm=document["compatMode"];
if((cm=="BackCompat")||(cm=="QuirksMode")){
return bs.BORDER_BOX;
}else{
return bs.CONTENT_BOX;
}
}else{
if(arguments.length==0){
node=document.documentElement;
}
var _517;
if(!h.ie){
_517=dojo.html.getStyle(node,"-moz-box-sizing");
if(!_517){
_517=dojo.html.getStyle(node,"box-sizing");
}
}
return (_517?_517:bs.CONTENT_BOX);
}
};
dojo.html.isBorderBox=function(node){
return (dojo.html.getBoxSizing(node)==dojo.html.boxSizing.BORDER_BOX);
};
dojo.html.getBorderBox=function(node){
node=dojo.byId(node);
return {width:node.offsetWidth,height:node.offsetHeight};
};
dojo.html.getPaddingBox=function(node){
var box=dojo.html.getBorderBox(node);
var _51c=dojo.html.getBorder(node);
return {width:box.width-_51c.width,height:box.height-_51c.height};
};
dojo.html.getContentBox=function(node){
node=dojo.byId(node);
var _51e=dojo.html.getPadBorder(node);
return {width:node.offsetWidth-_51e.width,height:node.offsetHeight-_51e.height};
};
dojo.html.setContentBox=function(node,args){
node=dojo.byId(node);
var _521=0;
var _522=0;
var isbb=dojo.html.isBorderBox(node);
var _524=(isbb?dojo.html.getPadBorder(node):{width:0,height:0});
var ret={};
if(typeof args.width!="undefined"){
_521=args.width+_524.width;
ret.width=dojo.html.setPositivePixelValue(node,"width",_521);
}
if(typeof args.height!="undefined"){
_522=args.height+_524.height;
ret.height=dojo.html.setPositivePixelValue(node,"height",_522);
}
return ret;
};
dojo.html.getMarginBox=function(node){
var _527=dojo.html.getBorderBox(node);
var _528=dojo.html.getMargin(node);
return {width:_527.width+_528.width,height:_527.height+_528.height};
};
dojo.html.setMarginBox=function(node,args){
node=dojo.byId(node);
var _52b=0;
var _52c=0;
var isbb=dojo.html.isBorderBox(node);
var _52e=(!isbb?dojo.html.getPadBorder(node):{width:0,height:0});
var _52f=dojo.html.getMargin(node);
var ret={};
if(typeof args.width!="undefined"){
_52b=args.width-_52e.width;
_52b-=_52f.width;
ret.width=dojo.html.setPositivePixelValue(node,"width",_52b);
}
if(typeof args.height!="undefined"){
_52c=args.height-_52e.height;
_52c-=_52f.height;
ret.height=dojo.html.setPositivePixelValue(node,"height",_52c);
}
return ret;
};
dojo.html.getElementBox=function(node,type){
var bs=dojo.html.boxSizing;
switch(type){
case bs.MARGIN_BOX:
return dojo.html.getMarginBox(node);
case bs.BORDER_BOX:
return dojo.html.getBorderBox(node);
case bs.PADDING_BOX:
return dojo.html.getPaddingBox(node);
case bs.CONTENT_BOX:
default:
return dojo.html.getContentBox(node);
}
};
dojo.html.toCoordinateObject=dojo.html.toCoordinateArray=function(_534,_535,_536){
if(_534 instanceof Array||typeof _534=="array"){
dojo.deprecated("dojo.html.toCoordinateArray","use dojo.html.toCoordinateObject({left: , top: , width: , height: }) instead","0.5");
while(_534.length&lt;4){
_534.push(0);
}
while(_534.length&gt;4){
_534.pop();
}
var ret={left:_534[0],top:_534[1],width:_534[2],height:_534[3]};
}else{
if(!_534.nodeType&amp;&amp;!(_534 instanceof String||typeof _534=="string")&amp;&amp;("width" in _534||"height" in _534||"left" in _534||"x" in _534||"top" in _534||"y" in _534)){
var ret={left:_534.left||_534.x||0,top:_534.top||_534.y||0,width:_534.width||0,height:_534.height||0};
}else{
var node=dojo.byId(_534);
var pos=dojo.html.abs(node,_535,_536);
var _53a=dojo.html.getMarginBox(node);
var ret={left:pos.left,top:pos.top,width:_53a.width,height:_53a.height};
}
}
ret.x=ret.left;
ret.y=ret.top;
return ret;
};
dojo.html.setMarginBoxWidth=dojo.html.setOuterWidth=function(node,_53c){
return dojo.html._callDeprecated("setMarginBoxWidth","setMarginBox",arguments,"width");
};
dojo.html.setMarginBoxHeight=dojo.html.setOuterHeight=function(){
return dojo.html._callDeprecated("setMarginBoxHeight","setMarginBox",arguments,"height");
};
dojo.html.getMarginBoxWidth=dojo.html.getOuterWidth=function(){
return dojo.html._callDeprecated("getMarginBoxWidth","getMarginBox",arguments,null,"width");
};
dojo.html.getMarginBoxHeight=dojo.html.getOuterHeight=function(){
return dojo.html._callDeprecated("getMarginBoxHeight","getMarginBox",arguments,null,"height");
};
dojo.html.getTotalOffset=function(node,type,_53f){
return dojo.html._callDeprecated("getTotalOffset","getAbsolutePosition",arguments,null,type);
};
dojo.html.getAbsoluteX=function(node,_541){
return dojo.html._callDeprecated("getAbsoluteX","getAbsolutePosition",arguments,null,"x");
};
dojo.html.getAbsoluteY=function(node,_543){
return dojo.html._callDeprecated("getAbsoluteY","getAbsolutePosition",arguments,null,"y");
};
dojo.html.totalOffsetLeft=function(node,_545){
return dojo.html._callDeprecated("totalOffsetLeft","getAbsolutePosition",arguments,null,"left");
};
dojo.html.totalOffsetTop=function(node,_547){
return dojo.html._callDeprecated("totalOffsetTop","getAbsolutePosition",arguments,null,"top");
};
dojo.html.getMarginWidth=function(node){
return dojo.html._callDeprecated("getMarginWidth","getMargin",arguments,null,"width");
};
dojo.html.getMarginHeight=function(node){
return dojo.html._callDeprecated("getMarginHeight","getMargin",arguments,null,"height");
};
dojo.html.getBorderWidth=function(node){
return dojo.html._callDeprecated("getBorderWidth","getBorder",arguments,null,"width");
};
dojo.html.getBorderHeight=function(node){
return dojo.html._callDeprecated("getBorderHeight","getBorder",arguments,null,"height");
};
dojo.html.getPaddingWidth=function(node){
return dojo.html._callDeprecated("getPaddingWidth","getPadding",arguments,null,"width");
};
dojo.html.getPaddingHeight=function(node){
return dojo.html._callDeprecated("getPaddingHeight","getPadding",arguments,null,"height");
};
dojo.html.getPadBorderWidth=function(node){
return dojo.html._callDeprecated("getPadBorderWidth","getPadBorder",arguments,null,"width");
};
dojo.html.getPadBorderHeight=function(node){
return dojo.html._callDeprecated("getPadBorderHeight","getPadBorder",arguments,null,"height");
};
dojo.html.getBorderBoxWidth=dojo.html.getInnerWidth=function(){
return dojo.html._callDeprecated("getBorderBoxWidth","getBorderBox",arguments,null,"width");
};
dojo.html.getBorderBoxHeight=dojo.html.getInnerHeight=function(){
return dojo.html._callDeprecated("getBorderBoxHeight","getBorderBox",arguments,null,"height");
};
dojo.html.getContentBoxWidth=dojo.html.getContentWidth=function(){
return dojo.html._callDeprecated("getContentBoxWidth","getContentBox",arguments,null,"width");
};
dojo.html.getContentBoxHeight=dojo.html.getContentHeight=function(){
return dojo.html._callDeprecated("getContentBoxHeight","getContentBox",arguments,null,"height");
};
dojo.html.setContentBoxWidth=dojo.html.setContentWidth=function(node,_551){
return dojo.html._callDeprecated("setContentBoxWidth","setContentBox",arguments,"width");
};
dojo.html.setContentBoxHeight=dojo.html.setContentHeight=function(node,_553){
return dojo.html._callDeprecated("setContentBoxHeight","setContentBox",arguments,"height");
};
dojo.provide("dojo.lfx.html");
dojo.lfx.html._byId=function(_554){
if(!_554){
return [];
}
if(dojo.lang.isArrayLike(_554)){
if(!_554.alreadyChecked){
var n=[];
dojo.lang.forEach(_554,function(node){
n.push(dojo.byId(node));
});
n.alreadyChecked=true;
return n;
}else{
return _554;
}
}else{
var n=[];
n.push(dojo.byId(_554));
n.alreadyChecked=true;
return n;
}
};
dojo.lfx.html.propertyAnimation=function(_557,_558,_559,_55a,_55b){
_557=dojo.lfx.html._byId(_557);
var _55c={"propertyMap":_558,"nodes":_557,"duration":_559,"easing":_55a||dojo.lfx.easeDefault};
var _55d=function(args){
if(args.nodes.length==1){
var pm=args.propertyMap;
if(!dojo.lang.isArray(args.propertyMap)){
var parr=[];
for(var _561 in pm){
pm[_561].property=_561;
parr.push(pm[_561]);
}
pm=args.propertyMap=parr;
}
dojo.lang.forEach(pm,function(prop){
if(dj_undef("start",prop)){
if(prop.property!="opacity"){
prop.start=parseInt(dojo.html.getComputedStyle(args.nodes[0],prop.property));
}else{
prop.start=dojo.html.getOpacity(args.nodes[0]);
}
}
});
}
};
var _563=function(_564){
var _565=[];
dojo.lang.forEach(_564,function(c){
_565.push(Math.round(c));
});
return _565;
};
var _567=function(n,_569){
n=dojo.byId(n);
if(!n||!n.style){
return;
}
for(var s in _569){
try{
if(s=="opacity"){
dojo.html.setOpacity(n,_569[s]);
}else{
n.style[s]=_569[s];
}
}
catch(e){
dojo.debug(e);
}
}
};
var _56b=function(_56c){
this._properties=_56c;
this.diffs=new Array(_56c.length);
dojo.lang.forEach(_56c,function(prop,i){
if(dojo.lang.isFunction(prop.start)){
prop.start=prop.start(prop,i);
}
if(dojo.lang.isFunction(prop.end)){
prop.end=prop.end(prop,i);
}
if(dojo.lang.isArray(prop.start)){
this.diffs[i]=null;
}else{
if(prop.start instanceof dojo.gfx.color.Color){
prop.startRgb=prop.start.toRgb();
prop.endRgb=prop.end.toRgb();
}else{
this.diffs[i]=prop.end-prop.start;
}
}
},this);
this.getValue=function(n){
var ret={};
dojo.lang.forEach(this._properties,function(prop,i){
var _573=null;
if(dojo.lang.isArray(prop.start)){
}else{
if(prop.start instanceof dojo.gfx.color.Color){
_573=(prop.units||"rgb")+"(";
for(var j=0;j&lt;prop.startRgb.length;j++){
_573+=Math.round(((prop.endRgb[j]-prop.startRgb[j])*n)+prop.startRgb[j])+(j&lt;prop.startRgb.length-1?",":"");
}
_573+=")";
}else{
_573=((this.diffs[i])*n)+prop.start+(prop.property!="opacity"?prop.units||"px":"");
}
}
ret[dojo.html.toCamelCase(prop.property)]=_573;
},this);
return ret;
};
};
var anim=new dojo.lfx.Animation({beforeBegin:function(){
_55d(_55c);
anim.curve=new _56b(_55c.propertyMap);
},onAnimate:function(_576){
dojo.lang.forEach(_55c.nodes,function(node){
_567(node,_576);
});
}},_55c.duration,null,_55c.easing);
if(_55b){
for(var x in _55b){
if(dojo.lang.isFunction(_55b[x])){
anim.connect(x,anim,_55b[x]);
}
}
}
return anim;
};
dojo.lfx.html._makeFadeable=function(_579){
var _57a=function(node){
if(dojo.render.html.ie){
if((node.style.zoom.length==0)&amp;&amp;(dojo.html.getStyle(node,"zoom")=="normal")){
node.style.zoom="1";
}
if((node.style.width.length==0)&amp;&amp;(dojo.html.getStyle(node,"width")=="auto")){
node.style.width="auto";
}
}
};
if(dojo.lang.isArrayLike(_579)){
dojo.lang.forEach(_579,_57a);
}else{
_57a(_579);
}
};
dojo.lfx.html.fade=function(_57c,_57d,_57e,_57f,_580){
_57c=dojo.lfx.html._byId(_57c);
var _581={property:"opacity"};
if(!dj_undef("start",_57d)){
_581.start=_57d.start;
}else{
_581.start=function(){
return dojo.html.getOpacity(_57c[0]);
};
}
if(!dj_undef("end",_57d)){
_581.end=_57d.end;
}else{
dojo.raise("dojo.lfx.html.fade needs an end value");
}
var anim=dojo.lfx.propertyAnimation(_57c,[_581],_57e,_57f);
anim.connect("beforeBegin",function(){
dojo.lfx.html._makeFadeable(_57c);
});
if(_580){
anim.connect("onEnd",function(){
_580(_57c,anim);
});
}
return anim;
};
dojo.lfx.html.fadeIn=function(_583,_584,_585,_586){
return dojo.lfx.html.fade(_583,{end:1},_584,_585,_586);
};
dojo.lfx.html.fadeOut=function(_587,_588,_589,_58a){
return dojo.lfx.html.fade(_587,{end:0},_588,_589,_58a);
};
dojo.lfx.html.fadeShow=function(_58b,_58c,_58d,_58e){
_58b=dojo.lfx.html._byId(_58b);
dojo.lang.forEach(_58b,function(node){
dojo.html.setOpacity(node,0);
});
var anim=dojo.lfx.html.fadeIn(_58b,_58c,_58d,_58e);
anim.connect("beforeBegin",function(){
if(dojo.lang.isArrayLike(_58b)){
dojo.lang.forEach(_58b,dojo.html.show);
}else{
dojo.html.show(_58b);
}
});
return anim;
};
dojo.lfx.html.fadeHide=function(_591,_592,_593,_594){
var anim=dojo.lfx.html.fadeOut(_591,_592,_593,function(){
if(dojo.lang.isArrayLike(_591)){
dojo.lang.forEach(_591,dojo.html.hide);
}else{
dojo.html.hide(_591);
}
if(_594){
_594(_591,anim);
}
});
return anim;
};
dojo.lfx.html.wipeIn=function(_596,_597,_598,_599){
_596=dojo.lfx.html._byId(_596);
var _59a=[];
dojo.lang.forEach(_596,function(node){
var _59c={};
var _59d,_59e,_59f;
with(node.style){
_59d=top;
_59e=left;
_59f=position;
top="-9999px";
left="-9999px";
position="absolute";
display="";
}
var _5a0=dojo.html.getBorderBox(node).height;
with(node.style){
top=_59d;
left=_59e;
position=_59f;
display="none";
}
var anim=dojo.lfx.propertyAnimation(node,{"height":{start:1,end:function(){
return _5a0;
}}},_597,_598);
anim.connect("beforeBegin",function(){
_59c.overflow=node.style.overflow;
_59c.height=node.style.height;
with(node.style){
overflow="hidden";
height="1px";
}
dojo.html.show(node);
});
anim.connect("onEnd",function(){
with(node.style){
overflow=_59c.overflow;
height=_59c.height;
}
if(_599){
_599(node,anim);
}
});
_59a.push(anim);
});
return dojo.lfx.combine(_59a);
};
dojo.lfx.html.wipeOut=function(_5a2,_5a3,_5a4,_5a5){
_5a2=dojo.lfx.html._byId(_5a2);
var _5a6=[];
dojo.lang.forEach(_5a2,function(node){
var _5a8={};
var anim=dojo.lfx.propertyAnimation(node,{"height":{start:function(){
return dojo.html.getContentBox(node).height;
},end:1}},_5a3,_5a4,{"beforeBegin":function(){
_5a8.overflow=node.style.overflow;
_5a8.height=node.style.height;
with(node.style){
overflow="hidden";
}
dojo.html.show(node);
},"onEnd":function(){
dojo.html.hide(node);
with(node.style){
overflow=_5a8.overflow;
height=_5a8.height;
}
if(_5a5){
_5a5(node,anim);
}
}});
_5a6.push(anim);
});
return dojo.lfx.combine(_5a6);
};
dojo.lfx.html.slideTo=function(_5aa,_5ab,_5ac,_5ad,_5ae){
_5aa=dojo.lfx.html._byId(_5aa);
var _5af=[];
var _5b0=dojo.html.getComputedStyle;
if(dojo.lang.isArray(_5ab)){
dojo.deprecated("dojo.lfx.html.slideTo(node, array)","use dojo.lfx.html.slideTo(node, {top: value, left: value});","0.5");
_5ab={top:_5ab[0],left:_5ab[1]};
}
dojo.lang.forEach(_5aa,function(node){
var top=null;
var left=null;
var init=(function(){
var _5b5=node;
return function(){
var pos=_5b0(_5b5,"position");
top=(pos=="absolute"?node.offsetTop:parseInt(_5b0(node,"top"))||0);
left=(pos=="absolute"?node.offsetLeft:parseInt(_5b0(node,"left"))||0);
if(!dojo.lang.inArray(["absolute","relative"],pos)){
var ret=dojo.html.abs(_5b5,true);
dojo.html.setStyleAttributes(_5b5,"position:absolute;top:"+ret.y+"px;left:"+ret.x+"px;");
top=ret.y;
left=ret.x;
}
};
})();
init();
var anim=dojo.lfx.propertyAnimation(node,{"top":{start:top,end:(_5ab.top||0)},"left":{start:left,end:(_5ab.left||0)}},_5ac,_5ad,{"beforeBegin":init});
if(_5ae){
anim.connect("onEnd",function(){
_5ae(_5aa,anim);
});
}
_5af.push(anim);
});
return dojo.lfx.combine(_5af);
};
dojo.lfx.html.slideBy=function(_5b9,_5ba,_5bb,_5bc,_5bd){
_5b9=dojo.lfx.html._byId(_5b9);
var _5be=[];
var _5bf=dojo.html.getComputedStyle;
if(dojo.lang.isArray(_5ba)){
dojo.deprecated("dojo.lfx.html.slideBy(node, array)","use dojo.lfx.html.slideBy(node, {top: value, left: value});","0.5");
_5ba={top:_5ba[0],left:_5ba[1]};
}
dojo.lang.forEach(_5b9,function(node){
var top=null;
var left=null;
var init=(function(){
var _5c4=node;
return function(){
var pos=_5bf(_5c4,"position");
top=(pos=="absolute"?node.offsetTop:parseInt(_5bf(node,"top"))||0);
left=(pos=="absolute"?node.offsetLeft:parseInt(_5bf(node,"left"))||0);
if(!dojo.lang.inArray(["absolute","relative"],pos)){
var ret=dojo.html.abs(_5c4,true);
dojo.html.setStyleAttributes(_5c4,"position:absolute;top:"+ret.y+"px;left:"+ret.x+"px;");
top=ret.y;
left=ret.x;
}
};
})();
init();
var anim=dojo.lfx.propertyAnimation(node,{"top":{start:top,end:top+(_5ba.top||0)},"left":{start:left,end:left+(_5ba.left||0)}},_5bb,_5bc).connect("beforeBegin",init);
if(_5bd){
anim.connect("onEnd",function(){
_5bd(_5b9,anim);
});
}
_5be.push(anim);
});
return dojo.lfx.combine(_5be);
};
dojo.lfx.html.explode=function(_5c8,_5c9,_5ca,_5cb,_5cc){
var h=dojo.html;
_5c8=dojo.byId(_5c8);
_5c9=dojo.byId(_5c9);
var _5ce=h.toCoordinateObject(_5c8,true);
var _5cf=document.createElement("div");
h.copyStyle(_5cf,_5c9);
if(_5c9.explodeClassName){
_5cf.className=_5c9.explodeClassName;
}
with(_5cf.style){
position="absolute";
display="none";
var _5d0=h.getStyle(_5c8,"background-color");
backgroundColor=_5d0?_5d0.toLowerCase():"transparent";
backgroundColor=(backgroundColor=="transparent")?"rgb(221, 221, 221)":backgroundColor;
}
dojo.body().appendChild(_5cf);
with(_5c9.style){
visibility="hidden";
display="block";
}
var _5d1=h.toCoordinateObject(_5c9,true);
with(_5c9.style){
display="none";
visibility="visible";
}
var _5d2={opacity:{start:0.5,end:1}};
dojo.lang.forEach(["height","width","top","left"],function(type){
_5d2[type]={start:_5ce[type],end:_5d1[type]};
});
var anim=new dojo.lfx.propertyAnimation(_5cf,_5d2,_5ca,_5cb,{"beforeBegin":function(){
h.setDisplay(_5cf,"block");
},"onEnd":function(){
h.setDisplay(_5c9,"block");
_5cf.parentNode.removeChild(_5cf);
}});
if(_5cc){
anim.connect("onEnd",function(){
_5cc(_5c9,anim);
});
}
return anim;
};
dojo.lfx.html.implode=function(_5d5,end,_5d7,_5d8,_5d9){
var h=dojo.html;
_5d5=dojo.byId(_5d5);
end=dojo.byId(end);
var _5db=dojo.html.toCoordinateObject(_5d5,true);
var _5dc=dojo.html.toCoordinateObject(end,true);
var _5dd=document.createElement("div");
dojo.html.copyStyle(_5dd,_5d5);
if(_5d5.explodeClassName){
_5dd.className=_5d5.explodeClassName;
}
dojo.html.setOpacity(_5dd,0.3);
with(_5dd.style){
position="absolute";
display="none";
backgroundColor=h.getStyle(_5d5,"background-color").toLowerCase();
}
dojo.body().appendChild(_5dd);
var _5de={opacity:{start:1,end:0.5}};
dojo.lang.forEach(["height","width","top","left"],function(type){
_5de[type]={start:_5db[type],end:_5dc[type]};
});
var anim=new dojo.lfx.propertyAnimation(_5dd,_5de,_5d7,_5d8,{"beforeBegin":function(){
dojo.html.hide(_5d5);
dojo.html.show(_5dd);
},"onEnd":function(){
_5dd.parentNode.removeChild(_5dd);
}});
if(_5d9){
anim.connect("onEnd",function(){
_5d9(_5d5,anim);
});
}
return anim;
};
dojo.lfx.html.highlight=function(_5e1,_5e2,_5e3,_5e4,_5e5){
_5e1=dojo.lfx.html._byId(_5e1);
var _5e6=[];
dojo.lang.forEach(_5e1,function(node){
var _5e8=dojo.html.getBackgroundColor(node);
var bg=dojo.html.getStyle(node,"background-color").toLowerCase();
var _5ea=dojo.html.getStyle(node,"background-image");
var _5eb=(bg=="transparent"||bg=="rgba(0, 0, 0, 0)");
while(_5e8.length&gt;3){
_5e8.pop();
}
var rgb=new dojo.gfx.color.Color(_5e2);
var _5ed=new dojo.gfx.color.Color(_5e8);
var anim=dojo.lfx.propertyAnimation(node,{"background-color":{start:rgb,end:_5ed}},_5e3,_5e4,{"beforeBegin":function(){
if(_5ea){
node.style.backgroundImage="none";
}
node.style.backgroundColor="rgb("+rgb.toRgb().join(",")+")";
},"onEnd":function(){
if(_5ea){
node.style.backgroundImage=_5ea;
}
if(_5eb){
node.style.backgroundColor="transparent";
}
if(_5e5){
_5e5(node,anim);
}
}});
_5e6.push(anim);
});
return dojo.lfx.combine(_5e6);
};
dojo.lfx.html.unhighlight=function(_5ef,_5f0,_5f1,_5f2,_5f3){
_5ef=dojo.lfx.html._byId(_5ef);
var _5f4=[];
dojo.lang.forEach(_5ef,function(node){
var _5f6=new dojo.gfx.color.Color(dojo.html.getBackgroundColor(node));
var rgb=new dojo.gfx.color.Color(_5f0);
var _5f8=dojo.html.getStyle(node,"background-image");
var anim=dojo.lfx.propertyAnimation(node,{"background-color":{start:_5f6,end:rgb}},_5f1,_5f2,{"beforeBegin":function(){
if(_5f8){
node.style.backgroundImage="none";
}
node.style.backgroundColor="rgb("+_5f6.toRgb().join(",")+")";
},"onEnd":function(){
if(_5f3){
_5f3(node,anim);
}
}});
_5f4.push(anim);
});
return dojo.lfx.combine(_5f4);
};
dojo.lang.mixin(dojo.lfx,dojo.lfx.html);
dojo.kwCompoundRequire({browser:["dojo.lfx.html"],dashboard:["dojo.lfx.html"]});
dojo.provide("dojo.lfx.*");

;$(function(){
  
	 $("#item_count_minus").click(function(){
	 	
		var current_count = $("#item_count").val();
		var new_count = 0;
		if(!isNaN(current_count))
		{
			if(current_count &gt; 0)
			{
				new_count = current_count - 1;
			}	
		}
		
		$("#item_count").val(new_count);
		
		return false;
	 });
	 
	 $("#item_count_plus").click(function(){
	 	
		var current_count = $("#item_count").val();
		var new_count = 0;
		if(!isNaN(parseInt(current_count)))
		{
	
			new_count = parseInt(current_count) + 1;
				
		}
		
		$("#item_count").val(new_count);
		
		return false;
	 });


	$("#basket_add").click(function(){
		
		//alert($(this).attr('pid'));
		
		var id = $(this).attr('pid');
		var buyer = new buyProduct( id, false, false);
		buyer.execute();
		if(ProductCheckForm != false){
		
			/*
			var main_height = $("#main").height();
			$("#basket_wrrap").css("display", "block");
			$("#basket_wrrap").height(main_height);
			
			var html_width = $("html").width();
			var dialog_left = (html_width - $("#basket_dialog").width())/2;
			
			var body_height = $("body").height();
			var dialog_top = (body_height - $("#basket_dialog").height())/2;
			
			var item_price = parseFloat($("#item_price").val());
			var item_count = parseInt($("#item_count").val());
			var price = item_price * item_count;
	
			$("#basket_dialog").css({display:"block", left: dialog_left, top: "200px"});		
			$("#basket_dialog_count").text(item_count);
			$("#basket_dialog_price").text(price+"zÅ‚");
			*/
			
		}

		return false;
		
	});
	
	$("#basket_addNow").click(function(){
	
		var id = $(this).attr('pid');
		//var buyer = new buyProduct( id, true, false);
		var buyer = new buyProduct( id, false, false);
		buyer.execute();	

		return false;
	
	});
	
	$("#basket_back").click(function(){
		$("#basket_wrrap").css("display", "none");
		return false;
	});
	$("#basket_goto").click(function(){

		location.href = '/koszyk';		
		return false;
	});
	
	
	$("#basket_dialog &gt; h1 &gt;a ").click(function(){
		$("#basket_wrrap").css("display", "none");
		
		//alert('test');
		
		return false;
	});
}); ;
;(function(){

/**
 * Require the module at `name`.
 *
 * @param {String} name
 * @return {Object} exports
 * @api public
 */

function require(name) {
  var module = require.modules[name];
  if (!module) throw new Error('failed to require "' + name + '"');

  if (!('exports' in module) &amp;&amp; typeof module.definition === 'function') {
    module.client = module.component = true;
    module.definition.call(this, module.exports = {}, module);
    delete module.definition;
  }

  return module.exports;
}

/**
 * Registered modules.
 */

require.modules = {};

/**
 * Register module at `name` with callback `definition`.
 *
 * @param {String} name
 * @param {Function} definition
 * @api private
 */

require.register = function (name, definition) {
  require.modules[name] = {
    definition: definition
  };
};

/**
 * Define a module's exports immediately with `exports`.
 *
 * @param {String} name
 * @param {Generic} exports
 * @api private
 */

require.define = function (name, exports) {
  require.modules[name] = {
    exports: exports
  };
};
require.register("component~emitter@1.1.2", function (exports, module) {

/**
 * Expose `Emitter`.
 */

module.exports = Emitter;

/**
 * Initialize a new `Emitter`.
 *
 * @api public
 */

function Emitter(obj) {
  if (obj) return mixin(obj);
};

/**
 * Mixin the emitter properties.
 *
 * @param {Object} obj
 * @return {Object}
 * @api private
 */

function mixin(obj) {
  for (var key in Emitter.prototype) {
    obj[key] = Emitter.prototype[key];
  }
  return obj;
}

/**
 * Listen on the given `event` with `fn`.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */

Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
  this._callbacks = this._callbacks || {};
  (this._callbacks[event] = this._callbacks[event] || [])
    .push(fn);
  return this;
};

/**
 * Adds an `event` listener that will be invoked a single
 * time then automatically removed.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */

Emitter.prototype.once = function(event, fn){
  var self = this;
  this._callbacks = this._callbacks || {};

  function on() {
    self.off(event, on);
    fn.apply(this, arguments);
  }

  on.fn = fn;
  this.on(event, on);
  return this;
};

/**
 * Remove the given callback for `event` or all
 * registered callbacks.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */

Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
  this._callbacks = this._callbacks || {};

  // all
  if (0 == arguments.length) {
    this._callbacks = {};
    return this;
  }

  // specific event
  var callbacks = this._callbacks[event];
  if (!callbacks) return this;

  // remove all handlers
  if (1 == arguments.length) {
    delete this._callbacks[event];
    return this;
  }

  // remove specific handler
  var cb;
  for (var i = 0; i &lt; callbacks.length; i++) {
    cb = callbacks[i];
    if (cb === fn || cb.fn === fn) {
      callbacks.splice(i, 1);
      break;
    }
  }
  return this;
};

/**
 * Emit `event` with the given args.
 *
 * @param {String} event
 * @param {Mixed} ...
 * @return {Emitter}
 */

Emitter.prototype.emit = function(event){
  this._callbacks = this._callbacks || {};
  var args = [].slice.call(arguments, 1)
    , callbacks = this._callbacks[event];

  if (callbacks) {
    callbacks = callbacks.slice(0);
    for (var i = 0, len = callbacks.length; i &lt; len; ++i) {
      callbacks[i].apply(this, args);
    }
  }

  return this;
};

/**
 * Return array of callbacks for `event`.
 *
 * @param {String} event
 * @return {Array}
 * @api public
 */

Emitter.prototype.listeners = function(event){
  this._callbacks = this._callbacks || {};
  return this._callbacks[event] || [];
};

/**
 * Check if this emitter has `event` handlers.
 *
 * @param {String} event
 * @return {Boolean}
 * @api public
 */

Emitter.prototype.hasListeners = function(event){
  return !! this.listeners(event).length;
};

});

require.register("dropzone", function (exports, module) {


/**
 * Exposing dropzone
 */
module.exports = require("dropzone/lib/dropzone.js");

});

require.register("dropzone/lib/dropzone.js", function (exports, module) {

/*
 *
 * More info at [www.dropzonejs.com](http://www.dropzonejs.com)
 *
 * Copyright (c) 2012, Matias Meno
 *
 * 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.
 *
 */

(function() {
  var Dropzone, Em, camelize, contentLoaded, detectVerticalSquash, drawImageIOSFix, noop, without,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    __slice = [].slice;

  Em = typeof Emitter !== "undefined" &amp;&amp; Emitter !== null ? Emitter : require("component~emitter@1.1.2");

  noop = function() {};

  Dropzone = (function(_super) {
    var extend;

    __extends(Dropzone, _super);


    /*
    This is a list of all available events you can register on a dropzone object.
    
    You can register an event handler like this:
    
        dropzone.on("dragEnter", function() { });
     */

    Dropzone.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "addedfile", "removedfile", "thumbnail", "error", "errormultiple", "processing", "processingmultiple", "uploadprogress", "totaluploadprogress", "sending", "sendingmultiple", "success", "successmultiple", "canceled", "canceledmultiple", "complete", "completemultiple", "reset", "maxfilesexceeded", "maxfilesreached"];

    Dropzone.prototype.defaultOptions = {
      url: null,
      method: "post",
      withCredentials: false,
      parallelUploads: 2,
      uploadMultiple: false,
      maxFilesize: 256,
      paramName: "file",
      createImageThumbnails: true,
      maxThumbnailFilesize: 10,
      thumbnailWidth: 100,
      thumbnailHeight: 100,
      maxFiles: null,
      params: {},
      clickable: true,
      ignoreHiddenFiles: true,
      acceptedFiles: null,
      acceptedMimeTypes: null,
      autoProcessQueue: true,
      autoQueue: true,
      addRemoveLinks: false,
      previewsContainer: null,
      dictDefaultMessage: "Drop files here to upload",
      dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.",
      dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.",
      dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.",
      dictInvalidFileType: "You can't upload files of this type.",
      dictResponseError: "Server responded with {{statusCode}} code.",
      dictCancelUpload: "Cancel upload",
      dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?",
      dictRemoveFile: "Remove file",
      dictRemoveFileConfirmation: null,
      dictMaxFilesExceeded: "You can not upload any more files.",
      accept: function(file, done) {
        return done();
      },
      init: function() {
        return noop;
      },
      forceFallback: false,
      fallback: function() {
        var child, messageElement, span, _i, _len, _ref;
        this.element.className = "" + this.element.className + " dz-browser-not-supported";
        _ref = this.element.getElementsByTagName("div");
        for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
          child = _ref[_i];
          if (/(^| )dz-message($| )/.test(child.className)) {
            messageElement = child;
            child.className = "dz-message";
            continue;
          }
        }
        if (!messageElement) {
          messageElement = Dropzone.createElement("&lt;div class=\"dz-message\"&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt;");
          this.element.appendChild(messageElement);
        }
        span = messageElement.getElementsByTagName("span")[0];
        if (span) {
          span.textContent = this.options.dictFallbackMessage;
        }
        return this.element.appendChild(this.getFallbackForm());
      },
      resize: function(file) {
        var info, srcRatio, trgRatio;
        info = {
          srcX: 0,
          srcY: 0,
          srcWidth: file.width,
          srcHeight: file.height
        };
        srcRatio = file.width / file.height;
        info.optWidth = this.options.thumbnailWidth;
        info.optHeight = this.options.thumbnailHeight;
        if ((info.optWidth == null) &amp;&amp; (info.optHeight == null)) {
          info.optWidth = info.srcWidth;
          info.optHeight = info.srcHeight;
        } else if (info.optWidth == null) {
          info.optWidth = srcRatio * info.optHeight;
        } else if (info.optHeight == null) {
          info.optHeight = (1 / srcRatio) * info.optWidth;
        }
        trgRatio = info.optWidth / info.optHeight;
        if (file.height &lt; info.optHeight || file.width &lt; info.optWidth) {
          info.trgHeight = info.srcHeight;
          info.trgWidth = info.srcWidth;
        } else {
          if (srcRatio &gt; trgRatio) {
            info.srcHeight = file.height;
            info.srcWidth = info.srcHeight * trgRatio;
          } else {
            info.srcWidth = file.width;
            info.srcHeight = info.srcWidth / trgRatio;
          }
        }
        info.srcX = (file.width - info.srcWidth) / 2;
        info.srcY = (file.height - info.srcHeight) / 2;
        return info;
      },

      /*
      Those functions register themselves to the events on init and handle all
      the user interface specific stuff. Overwriting them won't break the upload
      but can break the way it's displayed.
      You can overwrite them if you don't like the default behavior. If you just
      want to add an additional event handler, register it on the dropzone object
      and don't overwrite those options.
       */
      drop: function(e) {
        return this.element.classList.remove("dz-drag-hover");
      },
      dragstart: noop,
      dragend: function(e) {
        return this.element.classList.remove("dz-drag-hover");
      },
      dragenter: function(e) {
        return this.element.classList.add("dz-drag-hover");
      },
      dragover: function(e) {
        return this.element.classList.add("dz-drag-hover");
      },
      dragleave: function(e) {
        return this.element.classList.remove("dz-drag-hover");
      },
      paste: noop,
      reset: function() {
        return this.element.classList.remove("dz-started");
      },
      addedfile: function(file) {
        var node, removeFileEvent, removeLink, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results;
        if (this.element === this.previewsContainer) {
          this.element.classList.add("dz-started");
        }
        if (this.previewsContainer) {
          file.previewElement = Dropzone.createElement(this.options.previewTemplate.trim());
          file.previewTemplate = file.previewElement;
          this.previewsContainer.appendChild(file.previewElement);
          _ref = file.previewElement.querySelectorAll("[data-dz-name]");
          for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
            node = _ref[_i];
            node.textContent = file.name;
          }
          _ref1 = file.previewElement.querySelectorAll("[data-dz-size]");
          for (_j = 0, _len1 = _ref1.length; _j &lt; _len1; _j++) {
            node = _ref1[_j];
            node.innerHTML = this.filesize(file.size);
          }
          if (this.options.addRemoveLinks) {
            file._removeLink = Dropzone.createElement("&lt;a class=\"dz-remove\" href=\"javascript:undefined;\" data-dz-remove&gt;" + this.options.dictRemoveFile + "&lt;/a&gt;");
            file.previewElement.appendChild(file._removeLink);
          }
          removeFileEvent = (function(_this) {
            return function(e) {
              e.preventDefault();
              e.stopPropagation();
              if (file.status === Dropzone.UPLOADING) {
                return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() {
                  return _this.removeFile(file);
                });
              } else {
                if (_this.options.dictRemoveFileConfirmation) {
                  return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() {
                    return _this.removeFile(file);
                  });
                } else {
                  return _this.removeFile(file);
                }
              }
            };
          })(this);
          _ref2 = file.previewElement.querySelectorAll("[data-dz-remove]");
          _results = [];
          for (_k = 0, _len2 = _ref2.length; _k &lt; _len2; _k++) {
            removeLink = _ref2[_k];
            _results.push(removeLink.addEventListener("click", removeFileEvent));
          }
          return _results;
        }
      },
      removedfile: function(file) {
        var _ref;
        if (file.previewElement) {
          if ((_ref = file.previewElement) != null) {
            _ref.parentNode.removeChild(file.previewElement);
          }
        }
        return this._updateMaxFilesReachedClass();
      },
      thumbnail: function(file, dataUrl) {
        var thumbnailElement, _i, _len, _ref, _results;
        if (file.previewElement) {
          file.previewElement.classList.remove("dz-file-preview");
          file.previewElement.classList.add("dz-image-preview");
          _ref = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
          _results = [];
          for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
            thumbnailElement = _ref[_i];
            thumbnailElement.alt = file.name;
            _results.push(thumbnailElement.src = dataUrl);
          }
          return _results;
        }
      },
      error: function(file, message) {
        var node, _i, _len, _ref, _results;
        if (file.previewElement) {
          file.previewElement.classList.add("dz-error");
          if (typeof message !== "String" &amp;&amp; message.error) {
            message = message.error;
          }
          _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
          _results = [];
          for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
            node = _ref[_i];
            _results.push(node.textContent = message);
          }
          return _results;
        }
      },
      errormultiple: noop,
      processing: function(file) {
        if (file.previewElement) {
          file.previewElement.classList.add("dz-processing");
          if (file._removeLink) {
            return file._removeLink.textContent = this.options.dictCancelUpload;
          }
        }
      },
      processingmultiple: noop,
      uploadprogress: function(file, progress, bytesSent) {
        var node, _i, _len, _ref, _results;
        if (file.previewElement) {
          _ref = file.previewElement.querySelectorAll("[data-dz-uploadprogress]");
          _results = [];
          for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
            node = _ref[_i];
            _results.push(node.style.width = "" + progress + "%");
          }
          return _results;
        }
      },
      totaluploadprogress: noop,
      sending: noop,
      sendingmultiple: noop,
      success: function(file) {
        if (file.previewElement) {
          return file.previewElement.classList.add("dz-success");
        }
      },
      successmultiple: noop,
      canceled: function(file) {
        return this.emit("error", file, "Upload canceled.");
      },
      canceledmultiple: noop,
      complete: function(file) {
        if (file._removeLink) {
          return file._removeLink.textContent = this.options.dictRemoveFile;
        }
      },
      completemultiple: noop,
      maxfilesexceeded: noop,
      maxfilesreached: noop,
      previewTemplate: "&lt;div class=\"dz-preview dz-file-preview\"&gt;\n  &lt;div class=\"dz-details\"&gt;\n    &lt;div class=\"dz-filename\"&gt;&lt;span data-dz-name&gt;&lt;/span&gt;&lt;/div&gt;\n    &lt;div class=\"dz-size\" data-dz-size&gt;&lt;/div&gt;\n    &lt;img data-dz-thumbnail /&gt;\n  &lt;/div&gt;\n  &lt;div class=\"dz-progress\"&gt;&lt;span class=\"dz-upload\" data-dz-uploadprogress&gt;&lt;/span&gt;&lt;/div&gt;\n  &lt;div class=\"dz-success-mark\"&gt;&lt;span&gt;âœ”&lt;/span&gt;&lt;/div&gt;\n  &lt;div class=\"dz-error-mark\"&gt;&lt;span&gt;âœ˜&lt;/span&gt;&lt;/div&gt;\n  &lt;div class=\"dz-error-message\"&gt;&lt;span data-dz-errormessage&gt;&lt;/span&gt;&lt;/div&gt;\n&lt;/div&gt;"
    };

    extend = function() {
      var key, object, objects, target, val, _i, _len;
      target = arguments[0], objects = 2 &lt;= arguments.length ? __slice.call(arguments, 1) : [];
      for (_i = 0, _len = objects.length; _i &lt; _len; _i++) {
        object = objects[_i];
        for (key in object) {
          val = object[key];
          target[key] = val;
        }
      }
      return target;
    };

    function Dropzone(element, options) {
      var elementOptions, fallback, _ref;
      this.element = element;
      this.version = Dropzone.version;
      this.defaultOptions.previewTemplate = this.defaultOptions.previewTemplate.replace(/\n*/g, "");
      this.clickableElements = [];
      this.listeners = [];
      this.files = [];
      if (typeof this.element === "string") {
        this.element = document.querySelector(this.element);
      }
      if (!(this.element &amp;&amp; (this.element.nodeType != null))) {
        throw new Error("Invalid dropzone element.");
      }
      if (this.element.dropzone) {
        throw new Error("Dropzone already attached.");
      }
      Dropzone.instances.push(this);
      this.element.dropzone = this;
      elementOptions = (_ref = Dropzone.optionsForElement(this.element)) != null ? _ref : {};
      this.options = extend({}, this.defaultOptions, elementOptions, options != null ? options : {});
      if (this.options.forceFallback || !Dropzone.isBrowserSupported()) {
        return this.options.fallback.call(this);
      }
      if (this.options.url == null) {
        this.options.url = this.element.getAttribute("action");
      }
      if (!this.options.url) {
        throw new Error("No URL provided.");
      }
      if (this.options.acceptedFiles &amp;&amp; this.options.acceptedMimeTypes) {
        throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated.");
      }
      if (this.options.acceptedMimeTypes) {
        this.options.acceptedFiles = this.options.acceptedMimeTypes;
        delete this.options.acceptedMimeTypes;
      }
      this.options.method = this.options.method.toUpperCase();
      if ((fallback = this.getExistingFallback()) &amp;&amp; fallback.parentNode) {
        fallback.parentNode.removeChild(fallback);
      }
      if (this.options.previewsContainer !== false) {
        if (this.options.previewsContainer) {
          this.previewsContainer = Dropzone.getElement(this.options.previewsContainer, "previewsContainer");
        } else {
          this.previewsContainer = this.element;
        }
      }
      if (this.options.clickable) {
        if (this.options.clickable === true) {
          this.clickableElements = [this.element];
        } else {
          this.clickableElements = Dropzone.getElements(this.options.clickable, "clickable");
        }
      }
      this.init();
    }

    Dropzone.prototype.getAcceptedFiles = function() {
      var file, _i, _len, _ref, _results;
      _ref = this.files;
      _results = [];
      for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
        file = _ref[_i];
        if (file.accepted) {
          _results.push(file);
        }
      }
      return _results;
    };

    Dropzone.prototype.getRejectedFiles = function() {
      var file, _i, _len, _ref, _results;
      _ref = this.files;
      _results = [];
      for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
        file = _ref[_i];
        if (!file.accepted) {
          _results.push(file);
        }
      }
      return _results;
    };

    Dropzone.prototype.getFilesWithStatus = function(status) {
      var file, _i, _len, _ref, _results;
      _ref = this.files;
      _results = [];
      for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
        file = _ref[_i];
        if (file.status === status) {
          _results.push(file);
        }
      }
      return _results;
    };

    Dropzone.prototype.getQueuedFiles = function() {
      return this.getFilesWithStatus(Dropzone.QUEUED);
    };

    Dropzone.prototype.getUploadingFiles = function() {
      return this.getFilesWithStatus(Dropzone.UPLOADING);
    };

    Dropzone.prototype.getActiveFiles = function() {
      var file, _i, _len, _ref, _results;
      _ref = this.files;
      _results = [];
      for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
        file = _ref[_i];
        if (file.status === Dropzone.UPLOADING || file.status === Dropzone.QUEUED) {
          _results.push(file);
        }
      }
      return _results;
    };

    Dropzone.prototype.init = function() {
      var eventName, noPropagation, setupHiddenFileInput, _i, _len, _ref, _ref1;
      if (this.element.tagName === "form") {
        this.element.setAttribute("enctype", "multipart/form-data");
      }
      if (this.element.classList.contains("dropzone") &amp;&amp; !this.element.querySelector(".dz-message")) {
        this.element.appendChild(Dropzone.createElement("&lt;div class=\"dz-default dz-message\"&gt;&lt;span&gt;" + this.options.dictDefaultMessage + "&lt;/span&gt;&lt;/div&gt;"));
      }
      if (this.clickableElements.length) {
        setupHiddenFileInput = (function(_this) {
          return function() {
            if (_this.hiddenFileInput) {
              document.body.removeChild(_this.hiddenFileInput);
            }
            _this.hiddenFileInput = document.createElement("input");
            _this.hiddenFileInput.setAttribute("type", "file");
            if ((_this.options.maxFiles == null) || _this.options.maxFiles &gt; 1) {
              _this.hiddenFileInput.setAttribute("multiple", "multiple");
            }
            _this.hiddenFileInput.className = "dz-hidden-input";
            if (_this.options.acceptedFiles != null) {
              _this.hiddenFileInput.setAttribute("accept", _this.options.acceptedFiles);
            }
            _this.hiddenFileInput.style.visibility = "hidden";
            _this.hiddenFileInput.style.position = "absolute";
            _this.hiddenFileInput.style.top = "0";
            _this.hiddenFileInput.style.left = "0";
            _this.hiddenFileInput.style.height = "0";
            _this.hiddenFileInput.style.width = "0";
            document.body.appendChild(_this.hiddenFileInput);
            return _this.hiddenFileInput.addEventListener("change", function() {
              var file, files, _i, _len;
              files = _this.hiddenFileInput.files;
              if (files.length) {
                for (_i = 0, _len = files.length; _i &lt; _len; _i++) {
                  file = files[_i];
                  _this.addFile(file);
                }
              }
              return setupHiddenFileInput();
            });
          };
        })(this);
        setupHiddenFileInput();
      }
      this.URL = (_ref = window.URL) != null ? _ref : window.webkitURL;
      _ref1 = this.events;
      for (_i = 0, _len = _ref1.length; _i &lt; _len; _i++) {
        eventName = _ref1[_i];
        this.on(eventName, this.options[eventName]);
      }
      this.on("uploadprogress", (function(_this) {
        return function() {
          return _this.updateTotalUploadProgress();
        };
      })(this));
      this.on("removedfile", (function(_this) {
        return function() {
          return _this.updateTotalUploadProgress();
        };
      })(this));
      this.on("canceled", (function(_this) {
        return function(file) {
          return _this.emit("complete", file);
        };
      })(this));
      this.on("complete", (function(_this) {
        return function(file) {
          if (_this.getUploadingFiles().length === 0 &amp;&amp; _this.getQueuedFiles().length === 0) {
            return setTimeout((function() {
              return _this.emit("queuecomplete");
            }), 0);
          }
        };
      })(this));
      noPropagation = function(e) {
        e.stopPropagation();
        if (e.preventDefault) {
          return e.preventDefault();
        } else {
          return e.returnValue = false;
        }
      };
      this.listeners = [
        {
          element: this.element,
          events: {
            "dragstart": (function(_this) {
              return function(e) {
                return _this.emit("dragstart", e);
              };
            })(this),
            "dragenter": (function(_this) {
              return function(e) {
                noPropagation(e);
                return _this.emit("dragenter", e);
              };
            })(this),
            "dragover": (function(_this) {
              return function(e) {
                var efct;
                try {
                  efct = e.dataTransfer.effectAllowed;
                } catch (_error) {}
                e.dataTransfer.dropEffect = 'move' === efct || 'linkMove' === efct ? 'move' : 'copy';
                noPropagation(e);
                return _this.emit("dragover", e);
              };
            })(this),
            "dragleave": (function(_this) {
              return function(e) {
                return _this.emit("dragleave", e);
              };
            })(this),
            "drop": (function(_this) {
              return function(e) {
                noPropagation(e);
                return _this.drop(e);
              };
            })(this),
            "dragend": (function(_this) {
              return function(e) {
                return _this.emit("dragend", e);
              };
            })(this)
          }
        }
      ];
      this.clickableElements.forEach((function(_this) {
        return function(clickableElement) {
          return _this.listeners.push({
            element: clickableElement,
            events: {
              "click": function(evt) {
                if ((clickableElement !== _this.element) || (evt.target === _this.element || Dropzone.elementInside(evt.target, _this.element.querySelector(".dz-message")))) {
                  return _this.hiddenFileInput.click();
                }
              }
            }
          });
        };
      })(this));
      this.enable();
      return this.options.init.call(this);
    };

    Dropzone.prototype.destroy = function() {
      var _ref;
      this.disable();
      this.removeAllFiles(true);
      if ((_ref = this.hiddenFileInput) != null ? _ref.parentNode : void 0) {
        this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput);
        this.hiddenFileInput = null;
      }
      delete this.element.dropzone;
      return Dropzone.instances.splice(Dropzone.instances.indexOf(this), 1);
    };

    Dropzone.prototype.updateTotalUploadProgress = function() {
      var activeFiles, file, totalBytes, totalBytesSent, totalUploadProgress, _i, _len, _ref;
      totalBytesSent = 0;
      totalBytes = 0;
      activeFiles = this.getActiveFiles();
      if (activeFiles.length) {
        _ref = this.getActiveFiles();
        for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
          file = _ref[_i];
          totalBytesSent += file.upload.bytesSent;
          totalBytes += file.upload.total;
        }
        totalUploadProgress = 100 * totalBytesSent / totalBytes;
      } else {
        totalUploadProgress = 100;
      }
      return this.emit("totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent);
    };

    Dropzone.prototype._getParamName = function(n) {
      if (typeof this.options.paramName === "function") {
        return this.options.paramName(n);
      } else {
        return "" + this.options.paramName + (this.options.uploadMultiple ? "[" + n + "]" : "");
      }
    };

    Dropzone.prototype.getFallbackForm = function() {
      var existingFallback, fields, fieldsString, form;
      if (existingFallback = this.getExistingFallback()) {
        return existingFallback;
      }
      fieldsString = "&lt;div class=\"dz-fallback\"&gt;";
      if (this.options.dictFallbackText) {
        fieldsString += "&lt;p&gt;" + this.options.dictFallbackText + "&lt;/p&gt;";
      }
      fieldsString += "&lt;input type=\"file\" name=\"" + (this._getParamName(0)) + "\" " + (this.options.uploadMultiple ? 'multiple="multiple"' : void 0) + " /&gt;&lt;input type=\"submit\" value=\"Upload!\"&gt;&lt;/div&gt;";
      fields = Dropzone.createElement(fieldsString);
      if (this.element.tagName !== "FORM") {
        form = Dropzone.createElement("&lt;form action=\"" + this.options.url + "\" enctype=\"multipart/form-data\" method=\"" + this.options.method + "\"&gt;&lt;/form&gt;");
        form.appendChild(fields);
      } else {
        this.element.setAttribute("enctype", "multipart/form-data");
        this.element.setAttribute("method", this.options.method);
      }
      return form != null ? form : fields;
    };

    Dropzone.prototype.getExistingFallback = function() {
      var fallback, getFallback, tagName, _i, _len, _ref;
      getFallback = function(elements) {
        var el, _i, _len;
        for (_i = 0, _len = elements.length; _i &lt; _len; _i++) {
          el = elements[_i];
          if (/(^| )fallback($| )/.test(el.className)) {
            return el;
          }
        }
      };
      _ref = ["div", "form"];
      for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
        tagName = _ref[_i];
        if (fallback = getFallback(this.element.getElementsByTagName(tagName))) {
          return fallback;
        }
      }
    };

    Dropzone.prototype.setupEventListeners = function() {
      var elementListeners, event, listener, _i, _len, _ref, _results;
      _ref = this.listeners;
      _results = [];
      for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
        elementListeners = _ref[_i];
        _results.push((function() {
          var _ref1, _results1;
          _ref1 = elementListeners.events;
          _results1 = [];
          for (event in _ref1) {
            listener = _ref1[event];
            _results1.push(elementListeners.element.addEventListener(event, listener, false));
          }
          return _results1;
        })());
      }
      return _results;
    };

    Dropzone.prototype.removeEventListeners = function() {
      var elementListeners, event, listener, _i, _len, _ref, _results;
      _ref = this.listeners;
      _results = [];
      for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
        elementListeners = _ref[_i];
        _results.push((function() {
          var _ref1, _results1;
          _ref1 = elementListeners.events;
          _results1 = [];
          for (event in _ref1) {
            listener = _ref1[event];
            _results1.push(elementListeners.element.removeEventListener(event, listener, false));
          }
          return _results1;
        })());
      }
      return _results;
    };

    Dropzone.prototype.disable = function() {
      var file, _i, _len, _ref, _results;
      this.clickableElements.forEach(function(element) {
        return element.classList.remove("dz-clickable");
      });
      this.removeEventListeners();
      _ref = this.files;
      _results = [];
      for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
        file = _ref[_i];
        _results.push(this.cancelUpload(file));
      }
      return _results;
    };

    Dropzone.prototype.enable = function() {
      this.clickableElements.forEach(function(element) {
        return element.classList.add("dz-clickable");
      });
      return this.setupEventListeners();
    };

    Dropzone.prototype.filesize = function(size) {
      var string;
      if (size &gt;= 1024 * 1024 * 1024 * 1024 / 10) {
        size = size / (1024 * 1024 * 1024 * 1024 / 10);
        string = "TiB";
      } else if (size &gt;= 1024 * 1024 * 1024 / 10) {
        size = size / (1024 * 1024 * 1024 / 10);
        string = "GiB";
      } else if (size &gt;= 1024 * 1024 / 10) {
        size = size / (1024 * 1024 / 10);
        string = "MiB";
      } else if (size &gt;= 1024 / 10) {
        size = size / (1024 / 10);
        string = "KiB";
      } else {
        size = size * 10;
        string = "b";
      }
      return "&lt;strong&gt;" + (Math.round(size) / 10) + "&lt;/strong&gt; " + string;
    };

    Dropzone.prototype._updateMaxFilesReachedClass = function() {
      if ((this.options.maxFiles != null) &amp;&amp; this.getAcceptedFiles().length &gt;= this.options.maxFiles) {
        if (this.getAcceptedFiles().length === this.options.maxFiles) {
          this.emit('maxfilesreached', this.files);
        }
        return this.element.classList.add("dz-max-files-reached");
      } else {
        return this.element.classList.remove("dz-max-files-reached");
      }
    };

    Dropzone.prototype.drop = function(e) {
      var files, items;
      if (!e.dataTransfer) {
        return;
      }
      this.emit("drop", e);
      files = e.dataTransfer.files;
      if (files.length) {
        items = e.dataTransfer.items;
        if (items &amp;&amp; items.length &amp;&amp; (items[0].webkitGetAsEntry != null)) {
          this._addFilesFromItems(items);
        } else {
          this.handleFiles(files);
        }
      }
    };

    Dropzone.prototype.paste = function(e) {
      var items, _ref;
      if ((e != null ? (_ref = e.clipboardData) != null ? _ref.items : void 0 : void 0) == null) {
        return;
      }
      this.emit("paste", e);
      items = e.clipboardData.items;
      if (items.length) {
        return this._addFilesFromItems(items);
      }
    };

    Dropzone.prototype.handleFiles = function(files) {
      var file, _i, _len, _results;
      _results = [];
      for (_i = 0, _len = files.length; _i &lt; _len; _i++) {
        file = files[_i];
        _results.push(this.addFile(file));
      }
      return _results;
    };

    Dropzone.prototype._addFilesFromItems = function(items) {
      var entry, item, _i, _len, _results;
      _results = [];
      for (_i = 0, _len = items.length; _i &lt; _len; _i++) {
        item = items[_i];
        if ((item.webkitGetAsEntry != null) &amp;&amp; (entry = item.webkitGetAsEntry())) {
          if (entry.isFile) {
            _results.push(this.addFile(item.getAsFile()));
          } else if (entry.isDirectory) {
            _results.push(this._addFilesFromDirectory(entry, entry.name));
          } else {
            _results.push(void 0);
          }
        } else if (item.getAsFile != null) {
          if ((item.kind == null) || item.kind === "file") {
            _results.push(this.addFile(item.getAsFile()));
          } else {
            _results.push(void 0);
          }
        } else {
          _results.push(void 0);
        }
      }
      return _results;
    };

    Dropzone.prototype._addFilesFromDirectory = function(directory, path) {
      var dirReader, entriesReader;
      dirReader = directory.createReader();
      entriesReader = (function(_this) {
        return function(entries) {
          var entry, _i, _len;
          for (_i = 0, _len = entries.length; _i &lt; _len; _i++) {
            entry = entries[_i];
            if (entry.isFile) {
              entry.file(function(file) {
                if (_this.options.ignoreHiddenFiles &amp;&amp; file.name.substring(0, 1) === '.') {
                  return;
                }
                file.fullPath = "" + path + "/" + file.name;
                return _this.addFile(file);
              });
            } else if (entry.isDirectory) {
              _this._addFilesFromDirectory(entry, "" + path + "/" + entry.name);
            }
          }
        };
      })(this);
      return dirReader.readEntries(entriesReader, function(error) {
        return typeof console !== "undefined" &amp;&amp; console !== null ? typeof console.log === "function" ? console.log(error) : void 0 : void 0;
      });
    };

    Dropzone.prototype.accept = function(file, done) {
      if (file.size &gt; this.options.maxFilesize * 1024 * 1024) {
        return done(this.options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", this.options.maxFilesize));
      } else if (!Dropzone.isValidFile(file, this.options.acceptedFiles)) {
        return done(this.options.dictInvalidFileType);
      } else if ((this.options.maxFiles != null) &amp;&amp; this.getAcceptedFiles().length &gt;= this.options.maxFiles) {
        done(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}", this.options.maxFiles));
        return this.emit("maxfilesexceeded", file);
      } else {
        return this.options.accept.call(this, file, done);
      }
    };

    Dropzone.prototype.addFile = function(file) {
      file.upload = {
        progress: 0,
        total: file.size,
        bytesSent: 0
      };
      this.files.push(file);
      file.status = Dropzone.ADDED;
      this.emit("addedfile", file);
      this._enqueueThumbnail(file);
      return this.accept(file, (function(_this) {
        return function(error) {
          if (error) {
            file.accepted = false;
            _this._errorProcessing([file], error);
          } else {
            file.accepted = true;
            if (_this.options.autoQueue) {
              _this.enqueueFile(file);
            }
          }
          return _this._updateMaxFilesReachedClass();
        };
      })(this));
    };

    Dropzone.prototype.enqueueFiles = function(files) {
      var file, _i, _len;
      for (_i = 0, _len = files.length; _i &lt; _len; _i++) {
        file = files[_i];
        this.enqueueFile(file);
      }
      return null;
    };

    Dropzone.prototype.enqueueFile = function(file) {
      if (file.status === Dropzone.ADDED &amp;&amp; file.accepted === true) {
        file.status = Dropzone.QUEUED;
        if (this.options.autoProcessQueue) {
          return setTimeout(((function(_this) {
            return function() {
              return _this.processQueue();
            };
          })(this)), 0);
        }
      } else {
        throw new Error("This file can't be queued because it has already been processed or was rejected.");
      }
    };

    Dropzone.prototype._thumbnailQueue = [];

    Dropzone.prototype._processingThumbnail = false;

    Dropzone.prototype._enqueueThumbnail = function(file) {
      if (this.options.createImageThumbnails &amp;&amp; file.type.match(/image.*/) &amp;&amp; file.size &lt;= this.options.maxThumbnailFilesize * 1024 * 1024) {
        this._thumbnailQueue.push(file);
        return setTimeout(((function(_this) {
          return function() {
            return _this._processThumbnailQueue();
          };
        })(this)), 0);
      }
    };

    Dropzone.prototype._processThumbnailQueue = function() {
      if (this._processingThumbnail || this._thumbnailQueue.length === 0) {
        return;
      }
      this._processingThumbnail = true;
      return this.createThumbnail(this._thumbnailQueue.shift(), (function(_this) {
        return function() {
          _this._processingThumbnail = false;
          return _this._processThumbnailQueue();
        };
      })(this));
    };

    Dropzone.prototype.removeFile = function(file) {
      if (file.status === Dropzone.UPLOADING) {
        this.cancelUpload(file);
      }
      this.files = without(this.files, file);
      this.emit("removedfile", file);
      if (this.files.length === 0) {
        return this.emit("reset");
      }
    };

    Dropzone.prototype.removeAllFiles = function(cancelIfNecessary) {
      var file, _i, _len, _ref;
      if (cancelIfNecessary == null) {
        cancelIfNecessary = false;
      }
      _ref = this.files.slice();
      for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
        file = _ref[_i];
        if (file.status !== Dropzone.UPLOADING || cancelIfNecessary) {
          this.removeFile(file);
        }
      }
      return null;
    };

    Dropzone.prototype.createThumbnail = function(file, callback) {
      var fileReader;
      fileReader = new FileReader;
      fileReader.onload = (function(_this) {
        return function() {
          var img;
          img = document.createElement("img");
          img.onload = function() {
            var canvas, ctx, resizeInfo, thumbnail, _ref, _ref1, _ref2, _ref3;
            file.width = img.width;
            file.height = img.height;
            resizeInfo = _this.options.resize.call(_this, file);
            if (resizeInfo.trgWidth == null) {
              resizeInfo.trgWidth = resizeInfo.optWidth;
            }
            if (resizeInfo.trgHeight == null) {
              resizeInfo.trgHeight = resizeInfo.optHeight;
            }
            canvas = document.createElement("canvas");
            ctx = canvas.getContext("2d");
            canvas.width = resizeInfo.trgWidth;
            canvas.height = resizeInfo.trgHeight;
            drawImageIOSFix(ctx, img, (_ref = resizeInfo.srcX) != null ? _ref : 0, (_ref1 = resizeInfo.srcY) != null ? _ref1 : 0, resizeInfo.srcWidth, resizeInfo.srcHeight, (_ref2 = resizeInfo.trgX) != null ? _ref2 : 0, (_ref3 = resizeInfo.trgY) != null ? _ref3 : 0, resizeInfo.trgWidth, resizeInfo.trgHeight);
            thumbnail = canvas.toDataURL("image/png");
            _this.emit("thumbnail", file, thumbnail);
            if (callback != null) {
              return callback();
            }
          };
          return img.src = fileReader.result;
        };
      })(this);
      return fileReader.readAsDataURL(file);
    };

    Dropzone.prototype.processQueue = function() {
      var i, parallelUploads, processingLength, queuedFiles;
      parallelUploads = this.options.parallelUploads;
      processingLength = this.getUploadingFiles().length;
      i = processingLength;
      if (processingLength &gt;= parallelUploads) {
        return;
      }
      queuedFiles = this.getQueuedFiles();
      if (!(queuedFiles.length &gt; 0)) {
        return;
      }
      if (this.options.uploadMultiple) {
        return this.processFiles(queuedFiles.slice(0, parallelUploads - processingLength));
      } else {
        while (i &lt; parallelUploads) {
          if (!queuedFiles.length) {
            return;
          }
          this.processFile(queuedFiles.shift());
          i++;
        }
      }
    };

    Dropzone.prototype.processFile = function(file) {
      return this.processFiles([file]);
    };

    Dropzone.prototype.processFiles = function(files) {
      var file, _i, _len;
      for (_i = 0, _len = files.length; _i &lt; _len; _i++) {
        file = files[_i];
        file.processing = true;
        file.status = Dropzone.UPLOADING;
        this.emit("processing", file);
      }
      if (this.options.uploadMultiple) {
        this.emit("processingmultiple", files);
      }
      return this.uploadFiles(files);
    };

    Dropzone.prototype._getFilesWithXhr = function(xhr) {
      var file, files;
      return files = (function() {
        var _i, _len, _ref, _results;
        _ref = this.files;
        _results = [];
        for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
          file = _ref[_i];
          if (file.xhr === xhr) {
            _results.push(file);
          }
        }
        return _results;
      }).call(this);
    };

    Dropzone.prototype.cancelUpload = function(file) {
      var groupedFile, groupedFiles, _i, _j, _len, _len1, _ref;
      if (file.status === Dropzone.UPLOADING) {
        groupedFiles = this._getFilesWithXhr(file.xhr);
        for (_i = 0, _len = groupedFiles.length; _i &lt; _len; _i++) {
          groupedFile = groupedFiles[_i];
          groupedFile.status = Dropzone.CANCELED;
        }
        file.xhr.abort();
        for (_j = 0, _len1 = groupedFiles.length; _j &lt; _len1; _j++) {
          groupedFile = groupedFiles[_j];
          this.emit("canceled", groupedFile);
        }
        if (this.options.uploadMultiple) {
          this.emit("canceledmultiple", groupedFiles);
        }
      } else if ((_ref = file.status) === Dropzone.ADDED || _ref === Dropzone.QUEUED) {
        file.status = Dropzone.CANCELED;
        this.emit("canceled", file);
        if (this.options.uploadMultiple) {
          this.emit("canceledmultiple", [file]);
        }
      }
      if (this.options.autoProcessQueue) {
        return this.processQueue();
      }
    };

    Dropzone.prototype.uploadFile = function(file) {
      return this.uploadFiles([file]);
    };

    Dropzone.prototype.uploadFiles = function(files) {
      var file, formData, handleError, headerName, headerValue, headers, i, input, inputName, inputType, key, option, progressObj, response, updateProgress, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _m, _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
      xhr = new XMLHttpRequest();
      for (_i = 0, _len = files.length; _i &lt; _len; _i++) {
        file = files[_i];
        file.xhr = xhr;
      }
      xhr.open(this.options.method, this.options.url, true);
      xhr.withCredentials = !!this.options.withCredentials;
      response = null;
      handleError = (function(_this) {
        return function() {
          var _j, _len1, _results;
          _results = [];
          for (_j = 0, _len1 = files.length; _j &lt; _len1; _j++) {
            file = files[_j];
            _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr));
          }
          return _results;
        };
      })(this);
      updateProgress = (function(_this) {
        return function(e) {
          var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results;
          if (e != null) {
            progress = 100 * e.loaded / e.total;
            for (_j = 0, _len1 = files.length; _j &lt; _len1; _j++) {
              file = files[_j];
              file.upload = {
                progress: progress,
                total: e.total,
                bytesSent: e.loaded
              };
            }
          } else {
            allFilesFinished = true;
            progress = 100;
            for (_k = 0, _len2 = files.length; _k &lt; _len2; _k++) {
              file = files[_k];
              if (!(file.upload.progress === 100 &amp;&amp; file.upload.bytesSent === file.upload.total)) {
                allFilesFinished = false;
              }
              file.upload.progress = progress;
              file.upload.bytesSent = file.upload.total;
            }
            if (allFilesFinished) {
              return;
            }
          }
          _results = [];
          for (_l = 0, _len3 = files.length; _l &lt; _len3; _l++) {
            file = files[_l];
            _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent));
          }
          return _results;
        };
      })(this);
      xhr.onload = (function(_this) {
        return function(e) {
          var _ref;
          if (files[0].status === Dropzone.CANCELED) {
            return;
          }
          if (xhr.readyState !== 4) {
            return;
          }
          response = xhr.responseText;
          if (xhr.getResponseHeader("content-type") &amp;&amp; ~xhr.getResponseHeader("content-type").indexOf("application/json")) {
            try {
              response = JSON.parse(response);
            } catch (_error) {
              e = _error;
              response = "Invalid JSON response from server.";
            }
          }
          updateProgress();
          if (!((200 &lt;= (_ref = xhr.status) &amp;&amp; _ref &lt; 300))) {
            return handleError();
          } else {
            return _this._finished(files, response, e);
          }
        };
      })(this);
      xhr.onerror = (function(_this) {
        return function() {
          if (files[0].status === Dropzone.CANCELED) {
            return;
          }
          return handleError();
        };
      })(this);
      progressObj = (_ref = xhr.upload) != null ? _ref : xhr;
      progressObj.onprogress = updateProgress;
      headers = {
        "Accept": "application/json",
        "Cache-Control": "no-cache",
        "X-Requested-With": "XMLHttpRequest"
      };
      if (this.options.headers) {
        extend(headers, this.options.headers);
      }
      for (headerName in headers) {
        headerValue = headers[headerName];
        xhr.setRequestHeader(headerName, headerValue);
      }
      formData = new FormData();
      if (this.options.params) {
        _ref1 = this.options.params;
        for (key in _ref1) {
          value = _ref1[key];
          formData.append(key, value);
        }
      }
      for (_j = 0, _len1 = files.length; _j &lt; _len1; _j++) {
        file = files[_j];
        this.emit("sending", file, xhr, formData);
      }
      if (this.options.uploadMultiple) {
        this.emit("sendingmultiple", files, xhr, formData);
      }
      if (this.element.tagName === "FORM") {
        _ref2 = this.element.querySelectorAll("input, textarea, select, button");
        for (_k = 0, _len2 = _ref2.length; _k &lt; _len2; _k++) {
          input = _ref2[_k];
          inputName = input.getAttribute("name");
          inputType = input.getAttribute("type");
          if (input.tagName === "SELECT" &amp;&amp; input.hasAttribute("multiple")) {
            _ref3 = input.options;
            for (_l = 0, _len3 = _ref3.length; _l &lt; _len3; _l++) {
              option = _ref3[_l];
              if (option.selected) {
                formData.append(inputName, option.value);
              }
            }
          } else if (!inputType || ((_ref4 = inputType.toLowerCase()) !== "checkbox" &amp;&amp; _ref4 !== "radio") || input.checked) {
            formData.append(inputName, input.value);
          }
        }
      }
      for (i = _m = 0, _ref5 = files.length - 1; 0 &lt;= _ref5 ? _m &lt;= _ref5 : _m &gt;= _ref5; i = 0 &lt;= _ref5 ? ++_m : --_m) {
        formData.append(this._getParamName(i), files[i], files[i].name);
      }
      return xhr.send(formData);
    };

    Dropzone.prototype._finished = function(files, responseText, e) {
      var file, _i, _len;
      for (_i = 0, _len = files.length; _i &lt; _len; _i++) {
        file = files[_i];
        file.status = Dropzone.SUCCESS;
        this.emit("success", file, responseText, e);
        this.emit("complete", file);
      }
      if (this.options.uploadMultiple) {
        this.emit("successmultiple", files, responseText, e);
        this.emit("completemultiple", files);
      }
      if (this.options.autoProcessQueue) {
        return this.processQueue();
      }
    };

    Dropzone.prototype._errorProcessing = function(files, message, xhr) {
      var file, _i, _len;
      for (_i = 0, _len = files.length; _i &lt; _len; _i++) {
        file = files[_i];
        file.status = Dropzone.ERROR;
        this.emit("error", file, message, xhr);
        this.emit("complete", file);
      }
      if (this.options.uploadMultiple) {
        this.emit("errormultiple", files, message, xhr);
        this.emit("completemultiple", files);
      }
      if (this.options.autoProcessQueue) {
        return this.processQueue();
      }
    };

    return Dropzone;

  })(Em);

  Dropzone.version = "3.10.2";

  Dropzone.options = {};

  Dropzone.optionsForElement = function(element) {
    if (element.getAttribute("id")) {
      return Dropzone.options[camelize(element.getAttribute("id"))];
    } else {
      return void 0;
    }
  };

  Dropzone.instances = [];

  Dropzone.forElement = function(element) {
    if (typeof element === "string") {
      element = document.querySelector(element);
    }
    if ((element != null ? element.dropzone : void 0) == null) {
      throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone.");
    }
    return element.dropzone;
  };

  Dropzone.autoDiscover = true;

  Dropzone.discover = function() {
    var checkElements, dropzone, dropzones, _i, _len, _results;
    if (document.querySelectorAll) {
      dropzones = document.querySelectorAll(".dropzone");
    } else {
      dropzones = [];
      checkElements = function(elements) {
        var el, _i, _len, _results;
        _results = [];
        for (_i = 0, _len = elements.length; _i &lt; _len; _i++) {
          el = elements[_i];
          if (/(^| )dropzone($| )/.test(el.className)) {
            _results.push(dropzones.push(el));
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };
      checkElements(document.getElementsByTagName("div"));
      checkElements(document.getElementsByTagName("form"));
    }
    _results = [];
    for (_i = 0, _len = dropzones.length; _i &lt; _len; _i++) {
      dropzone = dropzones[_i];
      if (Dropzone.optionsForElement(dropzone) !== false) {
        _results.push(new Dropzone(dropzone));
      } else {
        _results.push(void 0);
      }
    }
    return _results;
  };

  Dropzone.blacklistedBrowsers = [/opera.*Macintosh.*version\/12/i];

  Dropzone.isBrowserSupported = function() {
    var capableBrowser, regex, _i, _len, _ref;
    capableBrowser = true;
    if (window.File &amp;&amp; window.FileReader &amp;&amp; window.FileList &amp;&amp; window.Blob &amp;&amp; window.FormData &amp;&amp; document.querySelector) {
      if (!("classList" in document.createElement("a"))) {
        capableBrowser = false;
      } else {
        _ref = Dropzone.blacklistedBrowsers;
        for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {
          regex = _ref[_i];
          if (regex.test(navigator.userAgent)) {
            capableBrowser = false;
            continue;
          }
        }
      }
    } else {
      capableBrowser = false;
    }
    return capableBrowser;
  };

  without = function(list, rejectedItem) {
    var item, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = list.length; _i &lt; _len; _i++) {
      item = list[_i];
      if (item !== rejectedItem) {
        _results.push(item);
      }
    }
    return _results;
  };

  camelize = function(str) {
    return str.replace(/[\-_](\w)/g, function(match) {
      return match.charAt(1).toUpperCase();
    });
  };

  Dropzone.createElement = function(string) {
    var div;
    div = document.createElement("div");
    div.innerHTML = string;
    return div.childNodes[0];
  };

  Dropzone.elementInside = function(element, container) {
    if (element === container) {
      return true;
    }
    while (element = element.parentNode) {
      if (element === container) {
        return true;
      }
    }
    return false;
  };

  Dropzone.getElement = function(el, name) {
    var element;
    if (typeof el === "string") {
      element = document.querySelector(el);
    } else if (el.nodeType != null) {
      element = el;
    }
    if (element == null) {
      throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector or a plain HTML element.");
    }
    return element;
  };

  Dropzone.getElements = function(els, name) {
    var e, el, elements, _i, _j, _len, _len1, _ref;
    if (els instanceof Array) {
      elements = [];
      try {
        for (_i = 0, _len = els.length; _i &lt; _len; _i++) {
          el = els[_i];
          elements.push(this.getElement(el, name));
        }
      } catch (_error) {
        e = _error;
        elements = null;
      }
    } else if (typeof els === "string") {
      elements = [];
      _ref = document.querySelectorAll(els);
      for (_j = 0, _len1 = _ref.length; _j &lt; _len1; _j++) {
        el = _ref[_j];
        elements.push(el);
      }
    } else if (els.nodeType != null) {
      elements = [els];
    }
    if (!((elements != null) &amp;&amp; elements.length)) {
      throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector, a plain HTML element or a list of those.");
    }
    return elements;
  };

  Dropzone.confirm = function(question, accepted, rejected) {
    if (window.confirm(question)) {
      return accepted();
    } else if (rejected != null) {
      return rejected();
    }
  };

  Dropzone.isValidFile = function(file, acceptedFiles) {
    var baseMimeType, mimeType, validType, _i, _len;
    if (!acceptedFiles) {
      return true;
    }
    acceptedFiles = acceptedFiles.split(",");
    mimeType = file.type;
    baseMimeType = mimeType.replace(/\/.*$/, "");
    for (_i = 0, _len = acceptedFiles.length; _i &lt; _len; _i++) {
      validType = acceptedFiles[_i];
      validType = validType.trim();
      if (validType.charAt(0) === ".") {
        if (file.name.toLowerCase().indexOf(validType.toLowerCase(), file.name.length - validType.length) !== -1) {
          return true;
        }
      } else if (/\/\*$/.test(validType)) {
        if (baseMimeType === validType.replace(/\/.*$/, "")) {
          return true;
        }
      } else {
        if (mimeType === validType) {
          return true;
        }
      }
    }
    return false;
  };

  if (typeof jQuery !== "undefined" &amp;&amp; jQuery !== null) {
    jQuery.fn.dropzone = function(options) {
      return this.each(function() {
        return new Dropzone(this, options);
      });
    };
  }

  if (typeof module !== "undefined" &amp;&amp; module !== null) {
    module.exports = Dropzone;
  } else {
    window.Dropzone = Dropzone;
  }

  Dropzone.ADDED = "added";

  Dropzone.QUEUED = "queued";

  Dropzone.ACCEPTED = Dropzone.QUEUED;

  Dropzone.UPLOADING = "uploading";

  Dropzone.PROCESSING = Dropzone.UPLOADING;

  Dropzone.CANCELED = "canceled";

  Dropzone.ERROR = "error";

  Dropzone.SUCCESS = "success";


  /*
  
  Bugfix for iOS 6 and 7
  Source: http://stackoverflow.com/questions/11929099/html5-canvas-drawimage-ratio-bug-ios
  based on the work of https://github.com/stomita/ios-imagefile-megapixel
   */

  detectVerticalSquash = function(img) {
    var alpha, canvas, ctx, data, ey, ih, iw, py, ratio, sy;
    iw = img.naturalWidth;
    ih = img.naturalHeight;
    canvas = document.createElement("canvas");
    canvas.width = 1;
    canvas.height = ih;
    ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    data = ctx.getImageData(0, 0, 1, ih).data;
    sy = 0;
    ey = ih;
    py = ih;
    while (py &gt; sy) {
      alpha = data[(py - 1) * 4 + 3];
      if (alpha === 0) {
        ey = py;
      } else {
        sy = py;
      }
      py = (ey + sy) &gt;&gt; 1;
    }
    ratio = py / ih;
    if (ratio === 0) {
      return 1;
    } else {
      return ratio;
    }
  };

  drawImageIOSFix = function(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) {
    var vertSquashRatio;
    vertSquashRatio = detectVerticalSquash(img);
    return ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio);
  };


  /*
   * contentloaded.js
   *
   * Author: Diego Perini (diego.perini at gmail.com)
   * Summary: cross-browser wrapper for DOMContentLoaded
   * Updated: 20101020
   * License: MIT
   * Version: 1.2
   *
   * URL:
   * http://javascript.nwbox.com/ContentLoaded/
   * http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE
   */

  contentLoaded = function(win, fn) {
    var add, doc, done, init, poll, pre, rem, root, top;
    done = false;
    top = true;
    doc = win.document;
    root = doc.documentElement;
    add = (doc.addEventListener ? "addEventListener" : "attachEvent");
    rem = (doc.addEventListener ? "removeEventListener" : "detachEvent");
    pre = (doc.addEventListener ? "" : "on");
    init = function(e) {
      if (e.type === "readystatechange" &amp;&amp; doc.readyState !== "complete") {
        return;
      }
      (e.type === "load" ? win : doc)[rem](pre + e.type, init, false);
      if (!done &amp;&amp; (done = true)) {
        return fn.call(win, e.type || e);
      }
    };
    poll = function() {
      var e;
      try {
        root.doScroll("left");
      } catch (_error) {
        e = _error;
        setTimeout(poll, 50);
        return;
      }
      return init("poll");
    };
    if (doc.readyState !== "complete") {
      if (doc.createEventObject &amp;&amp; root.doScroll) {
        try {
          top = !win.frameElement;
        } catch (_error) {}
        if (top) {
          poll();
        }
      }
      doc[add](pre + "DOMContentLoaded", init, false);
      doc[add](pre + "readystatechange", init, false);
      return win[add](pre + "load", init, false);
    }
  };

  Dropzone._autoDiscoverFunction = function() {
    if (Dropzone.autoDiscover) {
      return Dropzone.discover();
    }
  };

  contentLoaded(window, Dropzone._autoDiscoverFunction);

}).call(this);

});

if (typeof exports == "object") {
  module.exports = require("dropzone");
} else if (typeof define == "function" &amp;&amp; define.amd) {
  define([], function(){ return require("dropzone"); });
} else {
  this["Dropzone"] = require("dropzone");
}
})()
;/* ----------------------------------------------------------------------------
// Ezdz [izy-dizy]
// Licensed under the MIT license.
// http://github.com/jaysalvat/ezdz/
// ----------------------------------------------------------------------------
// Copyright (C) 2013 Jay Salvat
// http://jaysalvat.com/
// --------------------------------------------------------------------------*/

(function (factory) {
    if (typeof define === 'function' &amp;&amp; define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        factory(require('jquery'));
    } else {
        factory(jQuery);
    }
}(function ($) {
    // Default settings
    var defaults = {
        className:     '',
        text:          'Drop a file',
        previewImage:  true,
        value:         null,
        classes: {
            main:      'ezdz-dropzone',
            enter:     'ezdz-enter',
            reject:    'ezdz-reject',
            accept:    'ezdz-accept',
            focus:     'ezdz-focus'
        },
        validators: {
            maxSize:   null,
            width:     null,
            maxWidth:  null,
            minWidth:  null,
            height:    null,
            maxHeight: null,
            minHeight: null
        },
        init:   function() {},
        enter:  function() {},
        leave:  function() {},
        reject: function() {},
        accept: function() {},
        format: function(filename) {
            return filename;
        }
    };

    // Main plugin
    $.ezdz = function(element, options) {
        this.settings = $.extend(true, {}, defaults, $.ezdz.defaults, options);
        this.$input   = $(element);

        var self      = this,
            settings  = self.settings,
            $input    = self.$input;

        if (!$input.is('input[type="file"]')) {
            return;
        }

        // Stop if not compatible with HTML5 file API
        if (!$.ezdz.isBrowserCompatible()) {
            return;
        }

        // private: Init the plugin
        var init = function() {
            var $ezdz, $container, value;

            // Build the container
            $container = $('&lt;div class="' + settings.classes.main + '" /&gt;')

            .on('dragover.ezdz', function() {
                $(this).addClass(settings.classes.enter);

                if ($.isFunction(settings.enter)) {
                     settings.enter.apply(this);
                }
            })

            .on('dragleave.ezdz', function() {
                $(this).removeClass(settings.classes.enter);

                if ($.isFunction(settings.leaved)) {
                    settings.leaved.apply(this);
                }
            })

            .addClass(settings.className);

            // Build the whole dropzone
            $input
                .wrap($container)
                .before('&lt;div&gt;' + settings.text + '&lt;/div&gt;');

            $ezdz = $input.parent('.' + settings.classes.main);

            // Preview a file at start if it's defined
            value = settings.value || $input.data('value');

            if (value) {
                self.preview(value);
            }

            // Trigger the init callback
            if ($.isFunction(settings.init)) {
                 settings.init.apply($input, [ value ]);
            }

            // Events on the input
            $input

            .on('focus.ezdz', function() {
                $ezdz.addClass(settings.classes.focus);
            })

            .on('blur.ezdz', function() {
                $ezdz.removeClass(settings.classes.focus);
            })

            .on('change.ezdz', function() {
                var file = this.files[0];

                // No file, so user has cancelled
                if (!file) {
                    return;
                }

                // Info about the dropped or selected file
                var basename  = file.name.replace(/\\/g,'/').replace( /.*\//, ''),
                    extension = file.name.split('.').pop(),
                    formatted = settings.format(basename);

                file.extension = extension;

                // Mime-Types
                var allowed  = $input.attr('accept'),
                    accepted = false;
                    valid    = true;
                    errors   = {
                        'mimeType':  false,
                        'maxSize':   false,
                        'width':     false,
                        'minWidth':  false,
                        'maxWidth':  false,
                        'height':    false,
                        'minHeight': false,
                        'maxHeight': false
                    };

                // Check the accepted Mime-Types from the input file
                if (allowed) {
                    var types = allowed.split(/[,|]/);

                    $.each(types, function(i, type) {
                        type = $.trim(type);

                        if (file.type == type) {
                            accepted = true;
                            return false;
                        }

                        // Mime-Type with wildcards ex. image/*
                        if (type.indexOf('/*') !== false) {
                            var a = type.replace('/*', ''),
                                b = file.type.replace(/(\/.*)$/g, '');

                            if (a === b) {
                                accepted = true;
                                return false;
                            }
                        }
                    });

                    if (accepted === false) {
                        errors.mimeType = true;
                    }
                } else {
                    accepted = true;
                }

                // Reset the accepted / rejected classes
                $ezdz.removeClass(settings.classes.reject + ' ' + settings.classes.accept);

                // If the Mime-Type is not accepted
                if (accepted !== true) {
                    $input.val('');

                    $ezdz.addClass(settings.classes.reject);

                    // Trigger the reject callback
                    if ($.isFunction(settings.reject)) {
                         settings.reject.apply($input, [ file, errors ]);
                    }
                    return false;
                }

                // Read the added file
                var reader = new FileReader(file);

                reader.readAsDataURL(file);

                reader.onload = function(e) {
                    var img = new Image(),
                        isImage;

                    file.data = e.target.result;
                    img.src   = file.data;

                    setTimeout(function() {
                        isImage = (img.width &amp;&amp; img.height);

                        // Validator
                        if (settings.validators.maxSize &amp;&amp; file.size &gt; settings.validators.maxSize) {
                            valid = false;
                            errors.maxSize = true;
                        }

                        if (isImage) {
                            file.width  = img.width;
                            file.height = img.height;

                            if (settings.validators.width &amp;&amp; img.width != settings.validators.width) {
                                valid = false;
                                errors.width = true;
                            }

                            if (settings.validators.maxWidth &amp;&amp; img.width &gt; settings.validators.maxWidth) {
                                valid = false;
                                errors.maxWidth = true;
                            }

                            if (settings.validators.minWidth &amp;&amp; img.width &lt; settings.validators.minWidth) {
                                valid = false;
                                errors.minWidth = true;
                            }

                            if (settings.validators.height &amp;&amp; img.height != settings.validators.height) {
                                valid = false;
                                errors.height = true;
                            }

                            if (settings.validators.maxHeight &amp;&amp; img.height &gt; settings.validators.maxHeight) {
                                valid = false;
                                errors.maxHeight = true;
                            }

                            if (settings.validators.minHeight &amp;&amp; img.height &lt; settings.validators.minHeight) {
                                valid = false;
                                errors.minHeight = true;
                            }
                        }

                        // The file is validated, so added to input
                        if (valid === true) {
                            $ezdz.find('img').remove();

                            if (isImage &amp;&amp; settings.previewImage === true) {
                                $ezdz.find('div').html($(img).fadeIn());
                            } else {
                                $ezdz.find('div').html('&lt;span&gt;' + formatted + '&lt;/span&gt;');
                            }

                            $ezdz.addClass(settings.classes.accept);

                            // Trigger the accept callback
                            if ($.isFunction(settings.accept)) {
                                 settings.accept.apply($input, [ file ]);
                            }
                        // The file is invalidated, so rejected
                        } else {
                            $input.val('');

                            $ezdz.addClass(settings.classes.reject);

                            // Trigger the reject callback
                            if ($.isFunction(settings.reject)) {
                                 settings.reject.apply($input, [ file, errors ]);
                            }
                        }
                    }, 250);
                };
            });
        };

        init();
    };

    // Inject a file or image in the preview
    $.ezdz.prototype.preview = function(path, callback) {
        var settings  = this.settings,
            $input    = this.$input,
            $ezdz     = $input.parent('.' + settings.classes.main);
            basename  = path.replace(/\\/g,'/').replace( /.*\//, ''),
            formatted = settings.format(basename);

        var img = new Image();
        img.src = path;

        // Is an image
        img.onload = function() {
            $ezdz.find('div').html($(img).fadeIn());

            if ($.isFunction(callback)) {
                 callback.apply(this);
            }
        };

        // Is not an image
        img.onerror = function() {
            $ezdz.find('div').html('&lt;span&gt;' + formatted + '&lt;/span&gt;');

            if ($.isFunction(callback)) {
                 callback.apply(this);
            }
        };

        $ezdz.addClass(settings.classes.accept);
    };

    // Destroy ezdz
    $.ezdz.prototype.destroy = function() {
        var settings = this.settings,
            $input   = this.$input;

        $input.parent('.' + settings.classes.main).replaceWith($input);
        $input.off('*.ezdz');
        $input.data('ezdz', '');
    };

    // Extend settings
    $.ezdz.prototype.options = function(options) {
        var settings = this.settings;

        if (!options) {
            return settings;
        }

        $.extend(true, this.settings, options);
    };

    // Get input container
    $.ezdz.prototype.container = function() {
        var settings = this.settings,
            $input   = this.$input;

        return $input.parent('.' + settings.classes.main);
    };

    // Is browser compatible
    $.ezdz.isBrowserCompatible = function() {
        return !!(window.File &amp;&amp; window.FileList &amp;&amp; window.FileReader);
    };

    // Default options
    $.ezdz.defaults = defaults;

    // jQuery plugin
    $.fn.ezdz = function(options) {
        var args = arguments,
            plugin = $(this).data('ezdz');

        if (!plugin) {
            return $(this).data('ezdz', new $.ezdz(this, options));
        } if (plugin[options]) {
            return plugin[options].apply(plugin, Array.prototype.slice.call(args, 1));
        } else {
            $.error('Ezdz error - Method ' +  options + ' does not exist.');
        }
    };
}));
;/**
 * Farbtastic Color Picker 1.2
 * Â© 2008 Steven Wittens
 *
 * 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 2 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

jQuery.fn.farbtastic = function (callback) {
  $.farbtastic(this, callback);
  return this;
};

jQuery.farbtastic = function (container, callback) {
  var container = $(container).get(0);
  return container.farbtastic || (container.farbtastic = new jQuery._farbtastic(container, callback));
}

jQuery._farbtastic = function (container, callback) {
  // Store farbtastic object
  var fb = this;

  // Insert markup
  $(container).html('&lt;div class="farbtastic"&gt;&lt;div class="color"&gt;&lt;/div&gt;&lt;div class="wheel"&gt;&lt;/div&gt;&lt;div class="overlay"&gt;&lt;/div&gt;&lt;div class="h-marker marker"&gt;&lt;/div&gt;&lt;div class="sl-marker marker"&gt;&lt;/div&gt;&lt;/div&gt;');
  var e = $('.farbtastic', container);
  fb.wheel = $('.wheel', container).get(0);
  // Dimensions
  fb.radius = 84;
  fb.square = 100;
  fb.width = 194;

  // Fix background PNGs in IE6
  if (navigator.appVersion.match(/MSIE [0-6]\./)) {
    $('*', e).each(function () {
      if (this.currentStyle.backgroundImage != 'none') {
        var image = this.currentStyle.backgroundImage;
        image = this.currentStyle.backgroundImage.substring(5, image.length - 2);
        $(this).css({
          'backgroundImage': 'none',
          'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
        });
      }
    });
  }

  /**
   * Link to the given element(s) or callback.
   */
  fb.linkTo = function (callback) {
    // Unbind previous nodes
    if (typeof fb.callback == 'object') {
      $(fb.callback).unbind('keyup', fb.updateValue);
    }

    // Reset color
    fb.color = null;

    // Bind callback or elements
    if (typeof callback == 'function') {
      fb.callback = callback;
    }
    else if (typeof callback == 'object' || typeof callback == 'string') {
      fb.callback = $(callback);
      fb.callback.bind('keyup', fb.updateValue);
      if (fb.callback.get(0).value) {
        fb.setColor(fb.callback.get(0).value);
      }
    }
    return this;
  }
  fb.updateValue = function (event) {
    if (this.value &amp;&amp; this.value != fb.color) {
      fb.setColor(this.value);
    }
  }

  /**
   * Change color with HTML syntax #123456
   */
  fb.setColor = function (color) {
    var unpack = fb.unpack(color);
    if (fb.color != color &amp;&amp; unpack) {
      fb.color = color;
      fb.rgb = unpack;
      fb.hsl = fb.RGBToHSL(fb.rgb);
      fb.updateDisplay();
    }
    return this;
  }

  /**
   * Change color with HSL triplet [0..1, 0..1, 0..1]
   */
  fb.setHSL = function (hsl) {
    fb.hsl = hsl;
    fb.rgb = fb.HSLToRGB(hsl);
    fb.color = fb.pack(fb.rgb);
    fb.updateDisplay();
    return this;
  }

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

  /**
   * Retrieve the coordinates of the given event relative to the center
   * of the widget.
   */
  fb.widgetCoords = function (event) {
    var x, y;
    var el = event.target || event.srcElement;
    var reference = fb.wheel;

    if (typeof event.offsetX != 'undefined') {
      // Use offset coordinates and find common offsetParent
      var pos = { x: event.offsetX, y: event.offsetY };

      // Send the coordinates upwards through the offsetParent chain.
      var e = el;
      while (e) {
        e.mouseX = pos.x;
        e.mouseY = pos.y;
        pos.x += e.offsetLeft;
        pos.y += e.offsetTop;
        e = e.offsetParent;
      }

      // Look for the coordinates starting from the wheel widget.
      var e = reference;
      var offset = { x: 0, y: 0 }
      while (e) {
        if (typeof e.mouseX != 'undefined') {
          x = e.mouseX - offset.x;
          y = e.mouseY - offset.y;
          break;
        }
        offset.x += e.offsetLeft;
        offset.y += e.offsetTop;
        e = e.offsetParent;
      }

      // Reset stored coordinates
      e = el;
      while (e) {
        e.mouseX = undefined;
        e.mouseY = undefined;
        e = e.offsetParent;
      }
    }
    else {
      // Use absolute coordinates
      var pos = fb.absolutePosition(reference);
      x = (event.pageX || 0*(event.clientX + $('html').get(0).scrollLeft)) - pos.x;
      y = (event.pageY || 0*(event.clientY + $('html').get(0).scrollTop)) - pos.y;
    }
    // Subtract distance to middle
    return { x: x - fb.width / 2, y: y - fb.width / 2 };
  }

  /**
   * Mousedown handler
   */
  fb.mousedown = function (event) {
    // Capture mouse
    if (!document.dragging) {
      $(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup);
      document.dragging = true;
    }

    // Check which area is being dragged
    var pos = fb.widgetCoords(event);
    fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 &gt; fb.square;

    // Process
    fb.mousemove(event);
    return false;
  }

  /**
   * Mousemove handler
   */
  fb.mousemove = function (event) {
    // Get coordinates relative to color picker center
    var pos = fb.widgetCoords(event);

    // Set new HSL parameters
    if (fb.circleDrag) {
      var hue = Math.atan2(pos.x, -pos.y) / 6.28;
      if (hue &lt; 0) hue += 1;
      fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]);
    }
    else {
      var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5));
      var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5));
      fb.setHSL([fb.hsl[0], sat, lum]);
    }
    return false;
  }

  /**
   * Mouseup handler
   */
  fb.mouseup = function () {
    // Uncapture mouse
    $(document).unbind('mousemove', fb.mousemove);
    $(document).unbind('mouseup', fb.mouseup);
    document.dragging = false;
  }

  /**
   * Update the markers and styles
   */
  fb.updateDisplay = function () {
    // Markers
    var angle = fb.hsl[0] * 6.28;
    $('.h-marker', e).css({
      left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px',
      top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px'
    });

    $('.sl-marker', e).css({
      left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px',
      top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px'
    });

    // Saturation/Luminance gradient
    $('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5])));

    // Linked elements or callback
    if (typeof fb.callback == 'object') {
      // Set background/foreground color
      $(fb.callback).css({
        backgroundColor: fb.color,
        color: fb.hsl[2] &gt; 0.5 ? '#000' : '#fff'
      });

      // Change linked value
      $(fb.callback).each(function() {
        if (this.value != fb.color) {
          this.value = fb.color;
        }
      });
    }
    else if (typeof fb.callback == 'function') {
      fb.callback.call(fb, fb.color);
    }
  }

  /**
   * Get absolute position of element
   */
  fb.absolutePosition = function (el) {
    var r = { x: el.offsetLeft, y: el.offsetTop };
    // Resolve relative to offsetParent
    if (el.offsetParent) {
      var tmp = fb.absolutePosition(el.offsetParent);
      r.x += tmp.x;
      r.y += tmp.y;
    }
    return r;
  };

  /* Various color utility functions */
  fb.pack = function (rgb) {
    var r = Math.round(rgb[0] * 255);
    var g = Math.round(rgb[1] * 255);
    var b = Math.round(rgb[2] * 255);
    return '#' + (r &lt; 16 ? '0' : '') + r.toString(16) +
           (g &lt; 16 ? '0' : '') + g.toString(16) +
           (b &lt; 16 ? '0' : '') + b.toString(16);
  }

  fb.unpack = function (color) {
    if (color.length == 7) {
      return [parseInt('0x' + color.substring(1, 3)) / 255,
        parseInt('0x' + color.substring(3, 5)) / 255,
        parseInt('0x' + color.substring(5, 7)) / 255];
    }
    else if (color.length == 4) {
      return [parseInt('0x' + color.substring(1, 2)) / 15,
        parseInt('0x' + color.substring(2, 3)) / 15,
        parseInt('0x' + color.substring(3, 4)) / 15];
    }
  }

  fb.HSLToRGB = function (hsl) {
    var m1, m2, r, g, b;
    var h = hsl[0], s = hsl[1], l = hsl[2];
    m2 = (l &lt;= 0.5) ? l * (s + 1) : l + s - l*s;
    m1 = l * 2 - m2;
    return [this.hueToRGB(m1, m2, h+0.33333),
        this.hueToRGB(m1, m2, h),
        this.hueToRGB(m1, m2, h-0.33333)];
  }

  fb.hueToRGB = function (m1, m2, h) {
    h = (h &lt; 0) ? h + 1 : ((h &gt; 1) ? h - 1 : h);
    if (h * 6 &lt; 1) return m1 + (m2 - m1) * h * 6;
    if (h * 2 &lt; 1) return m2;
    if (h * 3 &lt; 2) return m1 + (m2 - m1) * (0.66666 - h) * 6;
    return m1;
  }

  fb.RGBToHSL = function (rgb) {
    var min, max, delta, h, s, l;
    var r = rgb[0], g = rgb[1], b = rgb[2];
    min = Math.min(r, Math.min(g, b));
    max = Math.max(r, Math.max(g, b));
    delta = max - min;
    l = (min + max) / 2;
    s = 0;
    if (l &gt; 0 &amp;&amp; l &lt; 1) {
      s = delta / (l &lt; 0.5 ? (2 * l) : (2 - 2 * l));
    }
    h = 0;
    if (delta &gt; 0) {
      if (max == r &amp;&amp; max != g) h += (g - b) / delta;
      if (max == g &amp;&amp; max != b) h += (2 + (b - r) / delta);
      if (max == b &amp;&amp; max != r) h += (4 + (r - g) / delta);
      h /= 6;
    }
    return [h, s, l];
  }

  // Install mousedown handler (the others are set on the document on-demand)
  $('*', e).mousedown(fb.mousedown);

    // Init color
  fb.setColor('#000000');

  // Set linked elements/callback
  if (callback) {
    fb.linkTo(callback);
  }
}</pre></body></html>