(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return!!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return!!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return+new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return!o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return-1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return!!T.firstChild},empty:function(T){return!T.firstChild},has:function(V,U,T){return!!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex"in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J&&J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return!F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();

;jQuery.ui||(function($){var _remove=$.fn.remove,isFF2=$.browser.mozilla&&(parseFloat($.browser.version)<1.9);$.ui={version:"1.7.2",plugin:{add:function(module,option,set){var proto=$.ui[module].prototype;for(var i in set){proto.plugins[i]=proto.plugins[i]||[];proto.plugins[i].push([option,set[i]]);}},call:function(instance,name,args){var set=instance.plugins[name];if(!set||!instance.element[0].parentNode){return;}
for(var i=0;i<set.length;i++){if(instance.options[set[i][0]]){set[i][1].apply(instance.element,args);}}}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b);},hasScroll:function(el,a){if($(el).css('overflow')=='hidden'){return false;}
var scroll=(a&&a=='left')?'scrollLeft':'scrollTop',has=false;if(el[scroll]>0){return true;}
el[scroll]=1;has=(el[scroll]>0);el[scroll]=0;return has;},isOverAxis:function(x,reference,size){return(x>reference)&&(x<(reference+size));},isOver:function(y,x,top,left,height,width){return $.ui.isOverAxis(y,top,height)&&$.ui.isOverAxis(x,left,width);},keyCode:{BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,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,SHIFT:16,SPACE:32,TAB:9,UP:38}};if(isFF2){var attr=$.attr,removeAttr=$.fn.removeAttr,ariaNS="http://www.w3.org/2005/07/aaa",ariaState=/^aria-/,ariaRole=/^wairole:/;$.attr=function(elem,name,value){var set=value!==undefined;return(name=='role'?(set?attr.call(this,elem,name,"wairole:"+value):(attr.apply(this,arguments)||"").replace(ariaRole,"")):(ariaState.test(name)?(set?elem.setAttributeNS(ariaNS,name.replace(ariaState,"aaa:"),value):attr.call(this,elem,name.replace(ariaState,"aaa:"))):attr.apply(this,arguments)));};$.fn.removeAttr=function(name){return(ariaState.test(name)?this.each(function(){this.removeAttributeNS(ariaNS,name.replace(ariaState,""));}):removeAttr.call(this,name));};}
$.fn.extend({remove:function(){$("*",this).add(this).each(function(){$(this).triggerHandler("remove");});return _remove.apply(this,arguments);},enableSelection:function(){return this.attr('unselectable','off').css('MozUserSelect','').unbind('selectstart.ui');},disableSelection:function(){return this.attr('unselectable','on').css('MozUserSelect','none').bind('selectstart.ui',function(){return false;});},scrollParent:function(){var scrollParent;if(($.browser.msie&&(/(static|relative)/).test(this.css('position')))||(/absolute/).test(this.css('position'))){scrollParent=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test($.curCSS(this,'position',1))&&(/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));}).eq(0);}else{scrollParent=this.parents().filter(function(){return(/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));}).eq(0);}
return(/fixed/).test(this.css('position'))||!scrollParent.length?$(document):scrollParent;}});$.extend($.expr[':'],{data:function(elem,i,match){return!!$.data(elem,match[3]);},focusable:function(element){var nodeName=element.nodeName.toLowerCase(),tabIndex=$.attr(element,'tabindex');return(/input|select|textarea|button|object/.test(nodeName)?!element.disabled:'a'==nodeName||'area'==nodeName?element.href||!isNaN(tabIndex):!isNaN(tabIndex))&&!$(element)['area'==nodeName?'parents':'closest'](':hidden').length;},tabbable:function(element){var tabIndex=$.attr(element,'tabindex');return(isNaN(tabIndex)||tabIndex>=0)&&$(element).is(':focusable');}});function getter(namespace,plugin,method,args){function getMethods(type){var methods=$[namespace][plugin][type]||[];return(typeof methods=='string'?methods.split(/,?\s+/):methods);}
var methods=getMethods('getter');if(args.length==1&&typeof args[0]=='string'){methods=methods.concat(getMethods('getterSetter'));}
return($.inArray(method,methods)!=-1);}
$.widget=function(name,prototype){var namespace=name.split(".")[0];name=name.split(".")[1];$.fn[name]=function(options){var isMethodCall=(typeof options=='string'),args=Array.prototype.slice.call(arguments,1);if(isMethodCall&&options.substring(0,1)=='_'){return this;}
if(isMethodCall&&getter(namespace,name,options,args)){var instance=$.data(this[0],name);return(instance?instance[options].apply(instance,args):undefined);}
return this.each(function(){var instance=$.data(this,name);(!instance&&!isMethodCall&&$.data(this,name,new $[namespace][name](this,options))._init());(instance&&isMethodCall&&$.isFunction(instance[options])&&instance[options].apply(instance,args));});};$[namespace]=$[namespace]||{};$[namespace][name]=function(element,options){var self=this;this.namespace=namespace;this.widgetName=name;this.widgetEventPrefix=$[namespace][name].eventPrefix||name;this.widgetBaseClass=namespace+'-'+name;this.options=$.extend({},$.widget.defaults,$[namespace][name].defaults,$.metadata&&$.metadata.get(element)[name],options);this.element=$(element).bind('setData.'+name,function(event,key,value){if(event.target==element){return self._setData(key,value);}}).bind('getData.'+name,function(event,key){if(event.target==element){return self._getData(key);}}).bind('remove',function(){return self.destroy();});};$[namespace][name].prototype=$.extend({},$.widget.prototype,prototype);$[namespace][name].getterSetter='option';};$.widget.prototype={_init:function(){},destroy:function(){this.element.removeData(this.widgetName).removeClass(this.widgetBaseClass+'-disabled'+' '+this.namespace+'-state-disabled').removeAttr('aria-disabled');},option:function(key,value){var options=key,self=this;if(typeof key=="string"){if(value===undefined){return this._getData(key);}
options={};options[key]=value;}
$.each(options,function(key,value){self._setData(key,value);});},_getData:function(key){return this.options[key];},_setData:function(key,value){this.options[key]=value;if(key=='disabled'){this.element
[value?'addClass':'removeClass'](this.widgetBaseClass+'-disabled'+' '+
this.namespace+'-state-disabled').attr("aria-disabled",value);}},enable:function(){this._setData('disabled',false);},disable:function(){this._setData('disabled',true);},_trigger:function(type,event,data){var callback=this.options[type],eventName=(type==this.widgetEventPrefix?type:this.widgetEventPrefix+type);event=$.Event(event);event.type=eventName;if(event.originalEvent){for(var i=$.event.props.length,prop;i;){prop=$.event.props[--i];event[prop]=event.originalEvent[prop];}}
this.element.trigger(event,data);return!($.isFunction(callback)&&callback.call(this.element[0],event,data)===false||event.isDefaultPrevented());}};$.widget.defaults={disabled:false};$.ui.mouse={_mouseInit:function(){var self=this;this.element.bind('mousedown.'+this.widgetName,function(event){return self._mouseDown(event);}).bind('click.'+this.widgetName,function(event){if(self._preventClickEvent){self._preventClickEvent=false;event.stopImmediatePropagation();return false;}});if($.browser.msie){this._mouseUnselectable=this.element.attr('unselectable');this.element.attr('unselectable','on');}
this.started=false;},_mouseDestroy:function(){this.element.unbind('.'+this.widgetName);($.browser.msie&&this.element.attr('unselectable',this._mouseUnselectable));},_mouseDown:function(event){event.originalEvent=event.originalEvent||{};if(event.originalEvent.mouseHandled){return;}
(this._mouseStarted&&this._mouseUp(event));this._mouseDownEvent=event;var self=this,btnIsLeft=(event.which==1),elIsCancel=(typeof this.options.cancel=="string"?$(event.target).parents().add(event.target).filter(this.options.cancel).length:false);if(!btnIsLeft||elIsCancel||!this._mouseCapture(event)){return true;}
this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){self.mouseDelayMet=true;},this.options.delay);}
if(this._mouseDistanceMet(event)&&this._mouseDelayMet(event)){this._mouseStarted=(this._mouseStart(event)!==false);if(!this._mouseStarted){event.preventDefault();return true;}}
this._mouseMoveDelegate=function(event){return self._mouseMove(event);};this._mouseUpDelegate=function(event){return self._mouseUp(event);};$(document).bind('mousemove.'+this.widgetName,this._mouseMoveDelegate).bind('mouseup.'+this.widgetName,this._mouseUpDelegate);($.browser.safari||event.preventDefault());event.originalEvent.mouseHandled=true;return true;},_mouseMove:function(event){if($.browser.msie&&!event.button){return this._mouseUp(event);}
if(this._mouseStarted){this._mouseDrag(event);return event.preventDefault();}
if(this._mouseDistanceMet(event)&&this._mouseDelayMet(event)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,event)!==false);(this._mouseStarted?this._mouseDrag(event):this._mouseUp(event));}
return!this._mouseStarted;},_mouseUp:function(event){$(document).unbind('mousemove.'+this.widgetName,this._mouseMoveDelegate).unbind('mouseup.'+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=(event.target==this._mouseDownEvent.target);this._mouseStop(event);}
return false;},_mouseDistanceMet:function(event){return(Math.max(Math.abs(this._mouseDownEvent.pageX-event.pageX),Math.abs(this._mouseDownEvent.pageY-event.pageY))>=this.options.distance);},_mouseDelayMet:function(event){return this.mouseDelayMet;},_mouseStart:function(event){},_mouseDrag:function(event){},_mouseStop:function(event){},_mouseCapture:function(event){return true;}};$.ui.mouse.defaults={cancel:null,distance:1,delay:0};})(jQuery);(function($){$.widget("ui.draggable",$.extend({},$.ui.mouse,{_init:function(){if(this.options.helper=='original'&&!(/^(?:r|a|f)/).test(this.element.css("position")))
this.element[0].style.position='relative';(this.options.addClasses&&this.element.addClass("ui-draggable"));(this.options.disabled&&this.element.addClass("ui-draggable-disabled"));this._mouseInit();},destroy:function(){if(!this.element.data('draggable'))return;this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable"
+" ui-draggable-dragging"
+" ui-draggable-disabled");this._mouseDestroy();},_mouseCapture:function(event){var o=this.options;if(this.helper||o.disabled||$(event.target).is('.ui-resizable-handle'))
return false;this.handle=this._getHandle(event);if(!this.handle)
return false;return true;},_mouseStart:function(event){var o=this.options;this.helper=this._createHelper(event);this._cacheHelperProportions();if($.ui.ddmanager)
$.ui.ddmanager.current=this;this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};$.extend(this.offset,{click:{left:event.pageX-this.offset.left,top:event.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(event);this.originalPageX=event.pageX;this.originalPageY=event.pageY;if(o.cursorAt)
this._adjustOffsetFromHelper(o.cursorAt);if(o.containment)
this._setContainment();this._trigger("start",event);this._cacheHelperProportions();if($.ui.ddmanager&&!o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(this,event);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(event,true);return true;},_mouseDrag:function(event,noPropagation){this.position=this._generatePosition(event);this.positionAbs=this._convertPositionTo("absolute");if(!noPropagation){var ui=this._uiHash();this._trigger('drag',event,ui);this.position=ui.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';if($.ui.ddmanager)$.ui.ddmanager.drag(this,event);return false;},_mouseStop:function(event){var dropped=false;if($.ui.ddmanager&&!this.options.dropBehaviour)
dropped=$.ui.ddmanager.drop(this,event);if(this.dropped){dropped=this.dropped;this.dropped=false;}
if((this.options.revert=="invalid"&&!dropped)||(this.options.revert=="valid"&&dropped)||this.options.revert===true||($.isFunction(this.options.revert)&&this.options.revert.call(this.element,dropped))){var self=this;$(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){self._trigger("stop",event);self._clear();});}else{this._trigger("stop",event);this._clear();}
return false;},_getHandle:function(event){var handle=!this.options.handle||!$(this.options.handle,this.element).length?true:false;$(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==event.target)handle=true;});return handle;},_createHelper:function(event){var o=this.options;var helper=$.isFunction(o.helper)?$(o.helper.apply(this.element[0],[event])):(o.helper=='clone'?this.element.clone():this.element);if(!helper.parents('body').length)
helper.appendTo((o.appendTo=='parent'?this.element[0].parentNode:o.appendTo));if(helper[0]!=this.element[0]&&!(/(fixed|absolute)/).test(helper.css("position")))
helper.css("position","absolute");return helper;},_adjustOffsetFromHelper:function(obj){if(obj.left!=undefined)this.offset.click.left=obj.left+this.margins.left;if(obj.right!=undefined)this.offset.click.left=this.helperProportions.width-obj.right+this.margins.left;if(obj.top!=undefined)this.offset.click.top=obj.top+this.margins.top;if(obj.bottom!=undefined)this.offset.click.top=this.helperProportions.height-obj.bottom+this.margins.top;},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var po=this.offsetParent.offset();if(this.cssPosition=='absolute'&&this.scrollParent[0]!=document&&$.ui.contains(this.scrollParent[0],this.offsetParent[0])){po.left+=this.scrollParent.scrollLeft();po.top+=this.scrollParent.scrollTop();}
if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=='html'&&$.browser.msie))
po={top:0,left:0};return{top:po.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:po.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)};},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var p=this.element.position();return{top:p.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:p.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()};}else{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)};},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};},_setContainment:function(){var o=this.options;if(o.containment=='parent')o.containment=this.helper[0].parentNode;if(o.containment=='document'||o.containment=='window')this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,$(o.containment=='document'?document:window).width()-this.helperProportions.width-this.margins.left,($(o.containment=='document'?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!(/^(document|window|parent)$/).test(o.containment)&&o.containment.constructor!=Array){var ce=$(o.containment)[0];if(!ce)return;var co=$(o.containment).offset();var over=($(ce).css("overflow")!='hidden');this.containment=[co.left+(parseInt($(ce).css("borderLeftWidth"),10)||0)+(parseInt($(ce).css("paddingLeft"),10)||0)-this.margins.left,co.top+(parseInt($(ce).css("borderTopWidth"),10)||0)+(parseInt($(ce).css("paddingTop"),10)||0)-this.margins.top,co.left+(over?Math.max(ce.scrollWidth,ce.offsetWidth):ce.offsetWidth)-(parseInt($(ce).css("borderLeftWidth"),10)||0)-(parseInt($(ce).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,co.top+(over?Math.max(ce.scrollHeight,ce.offsetHeight):ce.offsetHeight)-(parseInt($(ce).css("borderTopWidth"),10)||0)-(parseInt($(ce).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top];}else if(o.containment.constructor==Array){this.containment=o.containment;}},_convertPositionTo:function(d,pos){if(!pos)pos=this.position;var mod=d=="absolute"?1:-1;var o=this.options,scroll=this.cssPosition=='absolute'&&!(this.scrollParent[0]!=document&&$.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,scrollIsRootNode=(/(html|body)/i).test(scroll[0].tagName);return{top:(pos.top
+this.offset.relative.top*mod
+this.offset.parent.top*mod
-($.browser.safari&&this.cssPosition=='fixed'?0:(this.cssPosition=='fixed'?-this.scrollParent.scrollTop():(scrollIsRootNode?0:scroll.scrollTop()))*mod)),left:(pos.left
+this.offset.relative.left*mod
+this.offset.parent.left*mod
-($.browser.safari&&this.cssPosition=='fixed'?0:(this.cssPosition=='fixed'?-this.scrollParent.scrollLeft():scrollIsRootNode?0:scroll.scrollLeft())*mod))};},_generatePosition:function(event){var o=this.options,scroll=this.cssPosition=='absolute'&&!(this.scrollParent[0]!=document&&$.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,scrollIsRootNode=(/(html|body)/i).test(scroll[0].tagName);if(this.cssPosition=='relative'&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset();}
var pageX=event.pageX;var pageY=event.pageY;if(this.originalPosition){if(this.containment){if(event.pageX-this.offset.click.left<this.containment[0])pageX=this.containment[0]+this.offset.click.left;if(event.pageY-this.offset.click.top<this.containment[1])pageY=this.containment[1]+this.offset.click.top;if(event.pageX-this.offset.click.left>this.containment[2])pageX=this.containment[2]+this.offset.click.left;if(event.pageY-this.offset.click.top>this.containment[3])pageY=this.containment[3]+this.offset.click.top;}
if(o.grid){var top=this.originalPageY+Math.round((pageY-this.originalPageY)/o.grid[1])*o.grid[1];pageY=this.containment?(!(top-this.offset.click.top<this.containment[1]||top-this.offset.click.top>this.containment[3])?top:(!(top-this.offset.click.top<this.containment[1])?top-o.grid[1]:top+o.grid[1])):top;var left=this.originalPageX+Math.round((pageX-this.originalPageX)/o.grid[0])*o.grid[0];pageX=this.containment?(!(left-this.offset.click.left<this.containment[0]||left-this.offset.click.left>this.containment[2])?left:(!(left-this.offset.click.left<this.containment[0])?left-o.grid[0]:left+o.grid[0])):left;}}
return{top:(pageY
-this.offset.click.top
-this.offset.relative.top
-this.offset.parent.top
+($.browser.safari&&this.cssPosition=='fixed'?0:(this.cssPosition=='fixed'?-this.scrollParent.scrollTop():(scrollIsRootNode?0:scroll.scrollTop())))),left:(pageX
-this.offset.click.left
-this.offset.relative.left
-this.offset.parent.left
+($.browser.safari&&this.cssPosition=='fixed'?0:(this.cssPosition=='fixed'?-this.scrollParent.scrollLeft():scrollIsRootNode?0:scroll.scrollLeft())))};},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval)this.helper.remove();this.helper=null;this.cancelHelperRemoval=false;},_trigger:function(type,event,ui){ui=ui||this._uiHash();$.ui.plugin.call(this,type,[event,ui]);if(type=="drag")this.positionAbs=this._convertPositionTo("absolute");return $.widget.prototype._trigger.call(this,type,event,ui);},plugins:{},_uiHash:function(event){return{helper:this.helper,position:this.position,absolutePosition:this.positionAbs,offset:this.positionAbs};}}));$.extend($.ui.draggable,{version:"1.7.2",eventPrefix:"drag",defaults:{addClasses:true,appendTo:"parent",axis:false,cancel:":input,option",connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,delay:0,distance:1,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false}});$.ui.plugin.add("draggable","connectToSortable",{start:function(event,ui){var inst=$(this).data("draggable"),o=inst.options,uiSortable=$.extend({},ui,{item:inst.element});inst.sortables=[];$(o.connectToSortable).each(function(){var sortable=$.data(this,'sortable');if(sortable&&!sortable.options.disabled){inst.sortables.push({instance:sortable,shouldRevert:sortable.options.revert});sortable._refreshItems();sortable._trigger("activate",event,uiSortable);}});},stop:function(event,ui){var inst=$(this).data("draggable"),uiSortable=$.extend({},ui,{item:inst.element});$.each(inst.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;inst.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert)this.instance.options.revert=true;this.instance._mouseStop(event);this.instance.options.helper=this.instance.options._helper;if(inst.options.helper=='original')
this.instance.currentItem.css({top:'auto',left:'auto'});}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",event,uiSortable);}});},drag:function(event,ui){var inst=$(this).data("draggable"),self=this;var checkPos=function(o){var dyClick=this.offset.click.top,dxClick=this.offset.click.left;var helperTop=this.positionAbs.top,helperLeft=this.positionAbs.left;var itemHeight=o.height,itemWidth=o.width;var itemTop=o.top,itemLeft=o.left;return $.ui.isOver(helperTop+dyClick,helperLeft+dxClick,itemTop,itemLeft,itemHeight,itemWidth);};$.each(inst.sortables,function(i){this.instance.positionAbs=inst.positionAbs;this.instance.helperProportions=inst.helperProportions;this.instance.offset.click=inst.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=$(self).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return ui.helper[0];};event.target=this.instance.currentItem[0];this.instance._mouseCapture(event,true);this.instance._mouseStart(event,true,true);this.instance.offset.click.top=inst.offset.click.top;this.instance.offset.click.left=inst.offset.click.left;this.instance.offset.parent.left-=inst.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=inst.offset.parent.top-this.instance.offset.parent.top;inst._trigger("toSortable",event);inst.dropped=this.instance.element;inst.currentItem=inst.element;this.instance.fromOutside=inst;}
if(this.instance.currentItem)this.instance._mouseDrag(event);}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger('out',event,this.instance._uiHash(this.instance));this.instance._mouseStop(event,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder)this.instance.placeholder.remove();inst._trigger("fromSortable",event);inst.dropped=false;}};});}});$.ui.plugin.add("draggable","cursor",{start:function(event,ui){var t=$('body');var i=$(this).data('draggable');if(!i)return;var o=i.options;if(t.css("cursor"))o._cursor=t.css("cursor");t.css("cursor",o.cursor);},stop:function(event,ui){var i=$(this).data('draggable');if(!i)return;var o=i.options;if(o._cursor)$('body').css("cursor",o._cursor);}});$.ui.plugin.add("draggable","iframeFix",{start:function(event,ui){var i=$(this).data('draggable');if(!i)return;var o=i.options;$(o.iframeFix===true?"iframe":o.iframeFix).each(function(){$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css($(this).offset()).appendTo("body");});},stop:function(event,ui){$("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this);});}});$.ui.plugin.add("draggable","opacity",{start:function(event,ui){var t=$(ui.helper);var i=$(this).data('draggable');if(!i)return;var o=i.options;if(t.css("opacity"))o._opacity=t.css("opacity");t.css('opacity',o.opacity);},stop:function(event,ui){var i=$(this).data('draggable');if(!i)return;var o=i.options;if(o._opacity)$(ui.helper).css('opacity',o._opacity);}});$.ui.plugin.add("draggable","scroll",{start:function(event,ui){var i=$(this).data("draggable");if(i.scrollParent[0]!=document&&i.scrollParent[0].tagName!='HTML')i.overflowOffset=i.scrollParent.offset();},drag:function(event,ui){var i=$(this).data("draggable");if(!i)return;var o=i.options,scrolled=false;if(i.scrollParent[0]!=document&&i.scrollParent[0].tagName!='HTML'){if(!o.axis||o.axis!='x'){if((i.overflowOffset.top+i.scrollParent[0].offsetHeight)-event.pageY<o.scrollSensitivity)
i.scrollParent[0].scrollTop=scrolled=i.scrollParent[0].scrollTop+o.scrollSpeed;else if(event.pageY-i.overflowOffset.top<o.scrollSensitivity)
i.scrollParent[0].scrollTop=scrolled=i.scrollParent[0].scrollTop-o.scrollSpeed;}
if(!o.axis||o.axis!='y'){if((i.overflowOffset.left+i.scrollParent[0].offsetWidth)-event.pageX<o.scrollSensitivity)
i.scrollParent[0].scrollLeft=scrolled=i.scrollParent[0].scrollLeft+o.scrollSpeed;else if(event.pageX-i.overflowOffset.left<o.scrollSensitivity)
i.scrollParent[0].scrollLeft=scrolled=i.scrollParent[0].scrollLeft-o.scrollSpeed;}}else{if(!o.axis||o.axis!='x'){if(event.pageY-$(document).scrollTop()<o.scrollSensitivity)
scrolled=$(document).scrollTop($(document).scrollTop()-o.scrollSpeed);else if($(window).height()-(event.pageY-$(document).scrollTop())<o.scrollSensitivity)
scrolled=$(document).scrollTop($(document).scrollTop()+o.scrollSpeed);}
if(!o.axis||o.axis!='y'){if(event.pageX-$(document).scrollLeft()<o.scrollSensitivity)
scrolled=$(document).scrollLeft($(document).scrollLeft()-o.scrollSpeed);else if($(window).width()-(event.pageX-$(document).scrollLeft())<o.scrollSensitivity)
scrolled=$(document).scrollLeft($(document).scrollLeft()+o.scrollSpeed);}}
if(scrolled!==false&&$.ui.ddmanager&&!o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(i,event);}});$.ui.plugin.add("draggable","snap",{start:function(event,ui){var i=$(this).data("draggable"),o=i.options;i.snapElements=[];$(o.snap.constructor!=String?(o.snap.items||':data(draggable)'):o.snap).each(function(){var $t=$(this);var $o=$t.offset();if(this!=i.element[0])i.snapElements.push({item:this,width:$t.outerWidth(),height:$t.outerHeight(),top:$o.top,left:$o.left});});},drag:function(event,ui){var inst=$(this).data("draggable"),o=inst.options;var d=o.snapTolerance;var x1=ui.offset.left,x2=x1+inst.helperProportions.width,y1=ui.offset.top,y2=y1+inst.helperProportions.height;for(var i=inst.snapElements.length-1;i>=0;i--){var l=inst.snapElements[i].left,r=l+inst.snapElements[i].width,t=inst.snapElements[i].top,b=t+inst.snapElements[i].height;if(!((l-d<x1&&x1<r+d&&t-d<y1&&y1<b+d)||(l-d<x1&&x1<r+d&&t-d<y2&&y2<b+d)||(l-d<x2&&x2<r+d&&t-d<y1&&y1<b+d)||(l-d<x2&&x2<r+d&&t-d<y2&&y2<b+d))){if(inst.snapElements[i].snapping)(inst.options.snap.release&&inst.options.snap.release.call(inst.element,event,$.extend(inst._uiHash(),{snapItem:inst.snapElements[i].item})));inst.snapElements[i].snapping=false;continue;}
if(o.snapMode!='inner'){var ts=Math.abs(t-y2)<=d;var bs=Math.abs(b-y1)<=d;var ls=Math.abs(l-x2)<=d;var rs=Math.abs(r-x1)<=d;if(ts)ui.position.top=inst._convertPositionTo("relative",{top:t-inst.helperProportions.height,left:0}).top-inst.margins.top;if(bs)ui.position.top=inst._convertPositionTo("relative",{top:b,left:0}).top-inst.margins.top;if(ls)ui.position.left=inst._convertPositionTo("relative",{top:0,left:l-inst.helperProportions.width}).left-inst.margins.left;if(rs)ui.position.left=inst._convertPositionTo("relative",{top:0,left:r}).left-inst.margins.left;}
var first=(ts||bs||ls||rs);if(o.snapMode!='outer'){var ts=Math.abs(t-y1)<=d;var bs=Math.abs(b-y2)<=d;var ls=Math.abs(l-x1)<=d;var rs=Math.abs(r-x2)<=d;if(ts)ui.position.top=inst._convertPositionTo("relative",{top:t,left:0}).top-inst.margins.top;if(bs)ui.position.top=inst._convertPositionTo("relative",{top:b-inst.helperProportions.height,left:0}).top-inst.margins.top;if(ls)ui.position.left=inst._convertPositionTo("relative",{top:0,left:l}).left-inst.margins.left;if(rs)ui.position.left=inst._convertPositionTo("relative",{top:0,left:r-inst.helperProportions.width}).left-inst.margins.left;}
if(!inst.snapElements[i].snapping&&(ts||bs||ls||rs||first))
(inst.options.snap.snap&&inst.options.snap.snap.call(inst.element,event,$.extend(inst._uiHash(),{snapItem:inst.snapElements[i].item})));inst.snapElements[i].snapping=(ts||bs||ls||rs||first);};}});$.ui.plugin.add("draggable","stack",{start:function(event,ui){var o=$(this).data("draggable").options;var group=$.makeArray($(o.stack.group)).sort(function(a,b){return(parseInt($(a).css("zIndex"),10)||o.stack.min)-(parseInt($(b).css("zIndex"),10)||o.stack.min);});$(group).each(function(i){this.style.zIndex=o.stack.min+i;});this[0].style.zIndex=o.stack.min+group.length;}});$.ui.plugin.add("draggable","zIndex",{start:function(event,ui){var t=$(ui.helper),o=$(this).data("draggable").options;if(t.css("zIndex"))o._zIndex=t.css("zIndex");t.css('zIndex',o.zIndex);},stop:function(event,ui){var o=$(this).data("draggable").options;if(o._zIndex)$(ui.helper).css('zIndex',o._zIndex);}});})(jQuery);(function($){$.widget("ui.droppable",{_init:function(){var o=this.options,accept=o.accept;this.isover=0;this.isout=1;this.options.accept=this.options.accept&&$.isFunction(this.options.accept)?this.options.accept:function(d){return d.is(accept);};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};$.ui.ddmanager.droppables[this.options.scope]=$.ui.ddmanager.droppables[this.options.scope]||[];$.ui.ddmanager.droppables[this.options.scope].push(this);(this.options.addClasses&&this.element.addClass("ui-droppable"));},destroy:function(){var drop=$.ui.ddmanager.droppables[this.options.scope];for(var i=0;i<drop.length;i++)
if(drop[i]==this)
drop.splice(i,1);this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");},_setData:function(key,value){if(key=='accept'){this.options.accept=value&&$.isFunction(value)?value:function(d){return d.is(value);};}else{$.widget.prototype._setData.apply(this,arguments);}},_activate:function(event){var draggable=$.ui.ddmanager.current;if(this.options.activeClass)this.element.addClass(this.options.activeClass);(draggable&&this._trigger('activate',event,this.ui(draggable)));},_deactivate:function(event){var draggable=$.ui.ddmanager.current;if(this.options.activeClass)this.element.removeClass(this.options.activeClass);(draggable&&this._trigger('deactivate',event,this.ui(draggable)));},_over:function(event){var draggable=$.ui.ddmanager.current;if(!draggable||(draggable.currentItem||draggable.element)[0]==this.element[0])return;if(this.options.accept.call(this.element[0],(draggable.currentItem||draggable.element))){if(this.options.hoverClass)this.element.addClass(this.options.hoverClass);this._trigger('over',event,this.ui(draggable));}},_out:function(event){var draggable=$.ui.ddmanager.current;if(!draggable||(draggable.currentItem||draggable.element)[0]==this.element[0])return;if(this.options.accept.call(this.element[0],(draggable.currentItem||draggable.element))){if(this.options.hoverClass)this.element.removeClass(this.options.hoverClass);this._trigger('out',event,this.ui(draggable));}},_drop:function(event,custom){var draggable=custom||$.ui.ddmanager.current;if(!draggable||(draggable.currentItem||draggable.element)[0]==this.element[0])return false;var childrenIntersection=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var inst=$.data(this,'droppable');if(inst.options.greedy&&$.ui.intersect(draggable,$.extend(inst,{offset:inst.element.offset()}),inst.options.tolerance)){childrenIntersection=true;return false;}});if(childrenIntersection)return false;if(this.options.accept.call(this.element[0],(draggable.currentItem||draggable.element))){if(this.options.activeClass)this.element.removeClass(this.options.activeClass);if(this.options.hoverClass)this.element.removeClass(this.options.hoverClass);this._trigger('drop',event,this.ui(draggable));return this.element;}
return false;},ui:function(c){return{draggable:(c.currentItem||c.element),helper:c.helper,position:c.position,absolutePosition:c.positionAbs,offset:c.positionAbs};}});$.extend($.ui.droppable,{version:"1.7.2",eventPrefix:'drop',defaults:{accept:'*',activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:'default',tolerance:'intersect'}});$.ui.intersect=function(draggable,droppable,toleranceMode){if(!droppable.offset)return false;var x1=(draggable.positionAbs||draggable.position.absolute).left,x2=x1+draggable.helperProportions.width,y1=(draggable.positionAbs||draggable.position.absolute).top,y2=y1+draggable.helperProportions.height;var l=droppable.offset.left,r=l+droppable.proportions.width,t=droppable.offset.top,b=t+droppable.proportions.height;switch(toleranceMode){case'fit':return(l<x1&&x2<r&&t<y1&&y2<b);break;case'intersect':return(l<x1+(draggable.helperProportions.width/2)&&x2-(draggable.helperProportions.width/2)<r&&t<y1+(draggable.helperProportions.height/2)&&y2-(draggable.helperProportions.height/2)<b);break;case'pointer':var draggableLeft=((draggable.positionAbs||draggable.position.absolute).left+(draggable.clickOffset||draggable.offset.click).left),draggableTop=((draggable.positionAbs||draggable.position.absolute).top+(draggable.clickOffset||draggable.offset.click).top),isOver=$.ui.isOver(draggableTop,draggableLeft,t,l,droppable.proportions.height,droppable.proportions.width);return isOver;break;case'touch':return((y1>=t&&y1<=b)||(y2>=t&&y2<=b)||(y1<t&&y2>b))&&((x1>=l&&x1<=r)||(x2>=l&&x2<=r)||(x1<l&&x2>r));break;default:return false;break;}};$.ui.ddmanager={current:null,droppables:{'default':[]},prepareOffsets:function(t,event){var m=$.ui.ddmanager.droppables[t.options.scope];var type=event?event.type:null;var list=(t.currentItem||t.element).find(":data(droppable)").andSelf();droppablesLoop:for(var i=0;i<m.length;i++){if(m[i].options.disabled||(t&&!m[i].options.accept.call(m[i].element[0],(t.currentItem||t.element))))continue;for(var j=0;j<list.length;j++){if(list[j]==m[i].element[0]){m[i].proportions.height=0;continue droppablesLoop;}};m[i].visible=m[i].element.css("display")!="none";if(!m[i].visible)continue;m[i].offset=m[i].element.offset();m[i].proportions={width:m[i].element[0].offsetWidth,height:m[i].element[0].offsetHeight};if(type=="mousedown")m[i]._activate.call(m[i],event);}},drop:function(draggable,event){var dropped=false;$.each($.ui.ddmanager.droppables[draggable.options.scope],function(){if(!this.options)return;if(!this.options.disabled&&this.visible&&$.ui.intersect(draggable,this,this.options.tolerance))
dropped=this._drop.call(this,event);if(!this.options.disabled&&this.visible&&this.options.accept.call(this.element[0],(draggable.currentItem||draggable.element))){this.isout=1;this.isover=0;this._deactivate.call(this,event);}});return dropped;},drag:function(draggable,event){if(draggable.options.refreshPositions)$.ui.ddmanager.prepareOffsets(draggable,event);$.each($.ui.ddmanager.droppables[draggable.options.scope],function(){if(this.options.disabled||this.greedyChild||!this.visible)return;var intersects=$.ui.intersect(draggable,this,this.options.tolerance);var c=!intersects&&this.isover==1?'isout':(intersects&&this.isover==0?'isover':null);if(!c)return;var parentInstance;if(this.options.greedy){var parent=this.element.parents(':data(droppable):eq(0)');if(parent.length){parentInstance=$.data(parent[0],'droppable');parentInstance.greedyChild=(c=='isover'?1:0);}}
if(parentInstance&&c=='isover'){parentInstance['isover']=0;parentInstance['isout']=1;parentInstance._out.call(parentInstance,event);}
this[c]=1;this[c=='isout'?'isover':'isout']=0;this[c=="isover"?"_over":"_out"].call(this,event);if(parentInstance&&c=='isout'){parentInstance['isout']=0;parentInstance['isover']=1;parentInstance._over.call(parentInstance,event);}});}};})(jQuery);(function($){$.widget("ui.accordion",{_init:function(){var o=this.options,self=this;this.running=0;if(o.collapsible==$.ui.accordion.defaults.collapsible&&o.alwaysOpen!=$.ui.accordion.defaults.alwaysOpen){o.collapsible=!o.alwaysOpen;}
if(o.navigation){var current=this.element.find("a").filter(o.navigationFilter);if(current.length){if(current.filter(o.header).length){this.active=current;}else{this.active=current.parent().parent().prev();current.addClass("ui-accordion-content-active");}}}
this.element.addClass("ui-accordion ui-widget ui-helper-reset");if(this.element[0].nodeName=="UL"){this.element.children("li").addClass("ui-accordion-li-fix");}
this.headers=this.element.find(o.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){$(this).addClass('ui-state-hover');}).bind("mouseleave.accordion",function(){$(this).removeClass('ui-state-hover');}).bind("focus.accordion",function(){$(this).addClass('ui-state-focus');}).bind("blur.accordion",function(){$(this).removeClass('ui-state-focus');});this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");this.active=this._findActive(this.active||o.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");this.active.next().addClass('ui-accordion-content-active');$("<span/>").addClass("ui-icon "+o.icons.header).prependTo(this.headers);this.active.find(".ui-icon").toggleClass(o.icons.header).toggleClass(o.icons.headerSelected);if($.browser.msie){this.element.find('a').css('zoom','1');}
this.resize();this.element.attr('role','tablist');this.headers.attr('role','tab').bind('keydown',function(event){return self._keydown(event);}).next().attr('role','tabpanel');this.headers.not(this.active||"").attr('aria-expanded','false').attr("tabIndex","-1").next().hide();if(!this.active.length){this.headers.eq(0).attr('tabIndex','0');}else{this.active.attr('aria-expanded','true').attr('tabIndex','0');}
if(!$.browser.safari)
this.headers.find('a').attr('tabIndex','-1');if(o.event){this.headers.bind((o.event)+".accordion",function(event){return self._clickHandler.call(self,event,this);});}},destroy:function(){var o=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role").unbind('.accordion').removeData('accordion');this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("tabindex");this.headers.find("a").removeAttr("tabindex");this.headers.children(".ui-icon").remove();var contents=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active");if(o.autoHeight||o.fillHeight){contents.css("height","");}},_setData:function(key,value){if(key=='alwaysOpen'){key='collapsible';value=!value;}
$.widget.prototype._setData.apply(this,arguments);},_keydown:function(event){var o=this.options,keyCode=$.ui.keyCode;if(o.disabled||event.altKey||event.ctrlKey)
return;var length=this.headers.length;var currentIndex=this.headers.index(event.target);var toFocus=false;switch(event.keyCode){case keyCode.RIGHT:case keyCode.DOWN:toFocus=this.headers[(currentIndex+1)%length];break;case keyCode.LEFT:case keyCode.UP:toFocus=this.headers[(currentIndex-1+length)%length];break;case keyCode.SPACE:case keyCode.ENTER:return this._clickHandler({target:event.target},event.target);}
if(toFocus){$(event.target).attr('tabIndex','-1');$(toFocus).attr('tabIndex','0');toFocus.focus();return false;}
return true;},resize:function(){var o=this.options,maxHeight;if(o.fillSpace){if($.browser.msie){var defOverflow=this.element.parent().css('overflow');this.element.parent().css('overflow','hidden');}
maxHeight=this.element.parent().height();if($.browser.msie){this.element.parent().css('overflow',defOverflow);}
this.headers.each(function(){maxHeight-=$(this).outerHeight();});var maxPadding=0;this.headers.next().each(function(){maxPadding=Math.max(maxPadding,$(this).innerHeight()-$(this).height());}).height(Math.max(0,maxHeight-maxPadding)).css('overflow','auto');}else if(o.autoHeight){maxHeight=0;this.headers.next().each(function(){maxHeight=Math.max(maxHeight,$(this).outerHeight());}).height(maxHeight);}},activate:function(index){var active=this._findActive(index)[0];this._clickHandler({target:active},active);},_findActive:function(selector){return selector?typeof selector=="number"?this.headers.filter(":eq("+selector+")"):this.headers.not(this.headers.not(selector)):selector===false?$([]):this.headers.filter(":eq(0)");},_clickHandler:function(event,target){var o=this.options;if(o.disabled)return false;if(!event.target&&o.collapsible){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header);this.active.next().addClass('ui-accordion-content-active');var toHide=this.active.next(),data={options:o,newHeader:$([]),oldHeader:o.active,newContent:$([]),oldContent:toHide},toShow=(this.active=$([]));this._toggle(toShow,toHide,data);return false;}
var clicked=$(event.currentTarget||target);var clickedIsActive=clicked[0]==this.active[0];if(this.running||(!o.collapsible&&clickedIsActive)){return false;}
this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header);this.active.next().addClass('ui-accordion-content-active');if(!clickedIsActive){clicked.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").find(".ui-icon").removeClass(o.icons.header).addClass(o.icons.headerSelected);clicked.next().addClass('ui-accordion-content-active');}
var toShow=clicked.next(),toHide=this.active.next(),data={options:o,newHeader:clickedIsActive&&o.collapsible?$([]):clicked,oldHeader:this.active,newContent:clickedIsActive&&o.collapsible?$([]):toShow.find('> *'),oldContent:toHide.find('> *')},down=this.headers.index(this.active[0])>this.headers.index(clicked[0]);this.active=clickedIsActive?$([]):clicked;this._toggle(toShow,toHide,data,clickedIsActive,down);return false;},_toggle:function(toShow,toHide,data,clickedIsActive,down){var o=this.options,self=this;this.toShow=toShow;this.toHide=toHide;this.data=data;var complete=function(){if(!self)return;return self._completed.apply(self,arguments);};this._trigger("changestart",null,this.data);this.running=toHide.size()===0?toShow.size():toHide.size();if(o.animated){var animOptions={};if(o.collapsible&&clickedIsActive){animOptions={toShow:$([]),toHide:toHide,complete:complete,down:down,autoHeight:o.autoHeight||o.fillSpace};}else{animOptions={toShow:toShow,toHide:toHide,complete:complete,down:down,autoHeight:o.autoHeight||o.fillSpace};}
if(!o.proxied){o.proxied=o.animated;}
if(!o.proxiedDuration){o.proxiedDuration=o.duration;}
o.animated=$.isFunction(o.proxied)?o.proxied(animOptions):o.proxied;o.duration=$.isFunction(o.proxiedDuration)?o.proxiedDuration(animOptions):o.proxiedDuration;var animations=$.ui.accordion.animations,duration=o.duration,easing=o.animated;if(!animations[easing]){animations[easing]=function(options){this.slide(options,{easing:easing,duration:duration||700});};}
animations[easing](animOptions);}else{if(o.collapsible&&clickedIsActive){toShow.toggle();}else{toHide.hide();toShow.show();}
complete(true);}
toHide.prev().attr('aria-expanded','false').attr("tabIndex","-1").blur();toShow.prev().attr('aria-expanded','true').attr("tabIndex","0").focus();},_completed:function(cancel){var o=this.options;this.running=cancel?0:--this.running;if(this.running)return;if(o.clearStyle){this.toShow.add(this.toHide).css({height:"",overflow:""});}
this._trigger('change',null,this.data);}});$.extend($.ui.accordion,{version:"1.7.2",defaults:{active:null,alwaysOpen:true,animated:'slide',autoHeight:true,clearStyle:false,collapsible:false,event:"click",fillSpace:false,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:false,navigationFilter:function(){return this.href.toLowerCase()==location.href.toLowerCase();}},animations:{slide:function(options,additions){options=$.extend({easing:"swing",duration:300},options,additions);if(!options.toHide.size()){options.toShow.animate({height:"show"},options);return;}
if(!options.toShow.size()){options.toHide.animate({height:"hide"},options);return;}
var overflow=options.toShow.css('overflow'),percentDone,showProps={},hideProps={},fxAttrs=["height","paddingTop","paddingBottom"],originalWidth;var s=options.toShow;originalWidth=s[0].style.width;s.width(parseInt(s.parent().width(),10)-parseInt(s.css("paddingLeft"),10)-parseInt(s.css("paddingRight"),10)-(parseInt(s.css("borderLeftWidth"),10)||0)-(parseInt(s.css("borderRightWidth"),10)||0));$.each(fxAttrs,function(i,prop){hideProps[prop]='hide';var parts=(''+$.css(options.toShow[0],prop)).match(/^([\d+-.]+)(.*)$/);showProps[prop]={value:parts[1],unit:parts[2]||'px'};});options.toShow.css({height:0,overflow:'hidden'}).show();options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate(hideProps,{step:function(now,settings){if(settings.prop=='height'){percentDone=(settings.now-settings.start)/(settings.end-settings.start);}
options.toShow[0].style[settings.prop]=(percentDone*showProps[settings.prop].value)+showProps[settings.prop].unit;},duration:options.duration,easing:options.easing,complete:function(){if(!options.autoHeight){options.toShow.css("height","");}
options.toShow.css("width",originalWidth);options.toShow.css({overflow:overflow});options.complete();}});},bounceslide:function(options){this.slide(options,{easing:options.down?"easeOutBounce":"swing",duration:options.down?1000:200});},easeslide:function(options){this.slide(options,{easing:"easeinout",duration:700});}}});})(jQuery);(function($){var setDataSwitch={dragStart:"start.draggable",drag:"drag.draggable",dragStop:"stop.draggable",maxHeight:"maxHeight.resizable",minHeight:"minHeight.resizable",maxWidth:"maxWidth.resizable",minWidth:"minWidth.resizable",resizeStart:"start.resizable",resize:"drag.resizable",resizeStop:"stop.resizable"},uiDialogClasses='ui-dialog '+'ui-widget '+'ui-widget-content '+'ui-corner-all ';$.widget("ui.dialog",{_init:function(){this.originalTitle=this.element.attr('title');var self=this,options=this.options,title=options.title||this.originalTitle||'&nbsp;',titleId=$.ui.dialog.getTitleId(this.element),uiDialog=(this.uiDialog=$('<div/>')).appendTo(document.body).hide().addClass(uiDialogClasses+options.dialogClass).css({position:'absolute',overflow:'hidden',zIndex:options.zIndex}).attr('tabIndex',-1).css('outline',0).keydown(function(event){(options.closeOnEscape&&event.keyCode&&event.keyCode==$.ui.keyCode.ESCAPE&&self.close(event));}).attr({role:'dialog','aria-labelledby':titleId}).mousedown(function(event){self.moveToTop(false,event);}),uiDialogContent=this.element.show().removeAttr('title').addClass('ui-dialog-content '+'ui-widget-content').appendTo(uiDialog),uiDialogTitlebar=(this.uiDialogTitlebar=$('<div></div>')).addClass('ui-dialog-titlebar '+'ui-widget-header '+'ui-corner-all '+'ui-helper-clearfix').prependTo(uiDialog),uiDialogTitlebarClose=$('<a href="#"/>').addClass('ui-dialog-titlebar-close '+'ui-corner-all').attr('role','button').hover(function(){uiDialogTitlebarClose.addClass('ui-state-hover');},function(){uiDialogTitlebarClose.removeClass('ui-state-hover');}).focus(function(){uiDialogTitlebarClose.addClass('ui-state-focus');}).blur(function(){uiDialogTitlebarClose.removeClass('ui-state-focus');}).mousedown(function(ev){ev.stopPropagation();}).click(function(event){self.close(event);return false;}).appendTo(uiDialogTitlebar),uiDialogTitlebarCloseText=(this.uiDialogTitlebarCloseText=$('<span/>')).addClass('ui-icon '+'ui-icon-closethick').text(options.closeText).appendTo(uiDialogTitlebarClose),uiDialogTitle=$('<span/>').addClass('ui-dialog-title').attr('id',titleId).html(title).prependTo(uiDialogTitlebar);uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection();(options.draggable&&$.fn.draggable&&this._makeDraggable());(options.resizable&&$.fn.resizable&&this._makeResizable());this._createButtons(options.buttons);this._isOpen=false;(options.bgiframe&&$.fn.bgiframe&&uiDialog.bgiframe());(options.autoOpen&&this.open());},destroy:function(){(this.overlay&&this.overlay.destroy());this.uiDialog.hide();this.element.unbind('.dialog').removeData('dialog').removeClass('ui-dialog-content ui-widget-content').hide().appendTo('body');this.uiDialog.remove();(this.originalTitle&&this.element.attr('title',this.originalTitle));},close:function(event){var self=this;if(false===self._trigger('beforeclose',event)){return;}
(self.overlay&&self.overlay.destroy());self.uiDialog.unbind('keypress.ui-dialog');(self.options.hide?self.uiDialog.hide(self.options.hide,function(){self._trigger('close',event);}):self.uiDialog.hide()&&self._trigger('close',event));$.ui.dialog.overlay.resize();self._isOpen=false;if(self.options.modal){var maxZ=0;$('.ui-dialog').each(function(){if(this!=self.uiDialog[0]){maxZ=Math.max(maxZ,$(this).css('z-index'));}});$.ui.dialog.maxZ=maxZ;}},isOpen:function(){return this._isOpen;},moveToTop:function(force,event){if((this.options.modal&&!force)||(!this.options.stack&&!this.options.modal)){return this._trigger('focus',event);}
if(this.options.zIndex>$.ui.dialog.maxZ){$.ui.dialog.maxZ=this.options.zIndex;}
(this.overlay&&this.overlay.$el.css('z-index',$.ui.dialog.overlay.maxZ=++$.ui.dialog.maxZ));var saveScroll={scrollTop:this.element.attr('scrollTop'),scrollLeft:this.element.attr('scrollLeft')};this.uiDialog.css('z-index',++$.ui.dialog.maxZ);this.element.attr(saveScroll);this._trigger('focus',event);},open:function(){if(this._isOpen){return;}
var options=this.options,uiDialog=this.uiDialog;this.overlay=options.modal?new $.ui.dialog.overlay(this):null;(uiDialog.next().length&&uiDialog.appendTo('body'));this._size();this._position(options.position);uiDialog.show(options.show);this.moveToTop(true);(options.modal&&uiDialog.bind('keypress.ui-dialog',function(event){if(event.keyCode!=$.ui.keyCode.TAB){return;}
var tabbables=$(':tabbable',this),first=tabbables.filter(':first')[0],last=tabbables.filter(':last')[0];if(event.target==last&&!event.shiftKey){setTimeout(function(){first.focus();},1);}else if(event.target==first&&event.shiftKey){setTimeout(function(){last.focus();},1);}}));$([]).add(uiDialog.find('.ui-dialog-content :tabbable:first')).add(uiDialog.find('.ui-dialog-buttonpane :tabbable:first')).add(uiDialog).filter(':first').focus();this._trigger('open');this._isOpen=true;},_createButtons:function(buttons){var self=this,hasButtons=false,uiDialogButtonPane=$('<div></div>').addClass('ui-dialog-buttonpane '+'ui-widget-content '+'ui-helper-clearfix');this.uiDialog.find('.ui-dialog-buttonpane').remove();(typeof buttons=='object'&&buttons!==null&&$.each(buttons,function(){return!(hasButtons=true);}));if(hasButtons){$.each(buttons,function(name,fn){$('<button type="button"></button>').addClass('ui-state-default '+'ui-corner-all').text(name).click(function(){fn.apply(self.element[0],arguments);}).hover(function(){$(this).addClass('ui-state-hover');},function(){$(this).removeClass('ui-state-hover');}).focus(function(){$(this).addClass('ui-state-focus');}).blur(function(){$(this).removeClass('ui-state-focus');}).appendTo(uiDialogButtonPane);});uiDialogButtonPane.appendTo(this.uiDialog);}},_makeDraggable:function(){var self=this,options=this.options,heightBeforeDrag;this.uiDialog.draggable({cancel:'.ui-dialog-content',handle:'.ui-dialog-titlebar',containment:'document',start:function(){heightBeforeDrag=options.height;$(this).height($(this).height()).addClass("ui-dialog-dragging");(options.dragStart&&options.dragStart.apply(self.element[0],arguments));},drag:function(){(options.drag&&options.drag.apply(self.element[0],arguments));},stop:function(){$(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag);(options.dragStop&&options.dragStop.apply(self.element[0],arguments));$.ui.dialog.overlay.resize();}});},_makeResizable:function(handles){handles=(handles===undefined?this.options.resizable:handles);var self=this,options=this.options,resizeHandles=typeof handles=='string'?handles:'n,e,s,w,se,sw,ne,nw';this.uiDialog.resizable({cancel:'.ui-dialog-content',alsoResize:this.element,maxWidth:options.maxWidth,maxHeight:options.maxHeight,minWidth:options.minWidth,minHeight:options.minHeight,start:function(){$(this).addClass("ui-dialog-resizing");(options.resizeStart&&options.resizeStart.apply(self.element[0],arguments));},resize:function(){(options.resize&&options.resize.apply(self.element[0],arguments));},handles:resizeHandles,stop:function(){$(this).removeClass("ui-dialog-resizing");options.height=$(this).height();options.width=$(this).width();(options.resizeStop&&options.resizeStop.apply(self.element[0],arguments));$.ui.dialog.overlay.resize();}}).find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se');},_position:function(pos){var wnd=$(window),doc=$(document),pTop=doc.scrollTop(),pLeft=doc.scrollLeft(),minTop=pTop;if($.inArray(pos,['center','top','right','bottom','left'])>=0){pos=[pos=='right'||pos=='left'?pos:'center',pos=='top'||pos=='bottom'?pos:'middle'];}
if(pos.constructor!=Array){pos=['center','middle'];}
if(pos[0].constructor==Number){pLeft+=pos[0];}else{switch(pos[0]){case'left':pLeft+=0;break;case'right':pLeft+=wnd.width()-this.uiDialog.outerWidth();break;default:case'center':pLeft+=(wnd.width()-this.uiDialog.outerWidth())/2;}}
if(pos[1].constructor==Number){pTop+=pos[1];}else{switch(pos[1]){case'top':pTop+=0;break;case'bottom':pTop+=wnd.height()-this.uiDialog.outerHeight();break;default:case'middle':pTop+=(wnd.height()-this.uiDialog.outerHeight())/2;}}
pTop=Math.max(pTop,minTop);this.uiDialog.css({top:pTop,left:pLeft});},_setData:function(key,value){(setDataSwitch[key]&&this.uiDialog.data(setDataSwitch[key],value));switch(key){case"buttons":this._createButtons(value);break;case"closeText":this.uiDialogTitlebarCloseText.text(value);break;case"dialogClass":this.uiDialog.removeClass(this.options.dialogClass).addClass(uiDialogClasses+value);break;case"draggable":(value?this._makeDraggable():this.uiDialog.draggable('destroy'));break;case"height":this.uiDialog.height(value);break;case"position":this._position(value);break;case"resizable":var uiDialog=this.uiDialog,isResizable=this.uiDialog.is(':data(resizable)');(isResizable&&!value&&uiDialog.resizable('destroy'));(isResizable&&typeof value=='string'&&uiDialog.resizable('option','handles',value));(isResizable||this._makeResizable(value));break;case"title":$(".ui-dialog-title",this.uiDialogTitlebar).html(value||'&nbsp;');break;case"width":this.uiDialog.width(value);break;}
$.widget.prototype._setData.apply(this,arguments);},_size:function(){var options=this.options;this.element.css({height:0,minHeight:0,width:'auto'});var nonContentHeight=this.uiDialog.css({height:'auto',width:options.width}).height();this.element.css({minHeight:Math.max(options.minHeight-nonContentHeight,0),height:options.height=='auto'?'auto':Math.max(options.height-nonContentHeight,0)});}});$.extend($.ui.dialog,{version:"1.7.2",defaults:{autoOpen:true,bgiframe:false,buttons:{},closeOnEscape:true,closeText:'close',dialogClass:'',draggable:true,hide:null,height:'auto',maxHeight:false,maxWidth:false,minHeight:0,minWidth:150,modal:false,position:'center',resizable:true,show:null,stack:true,title:'',width:300,zIndex:1000},getter:'isOpen',uuid:0,maxZ:0,getTitleId:function($el){return'ui-dialog-title-'+($el.attr('id')||++this.uuid);},overlay:function(dialog){this.$el=$.ui.dialog.overlay.create(dialog);}});$.extend($.ui.dialog.overlay,{instances:[],maxZ:0,events:$.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),function(event){return event+'.dialog-overlay';}).join(' '),create:function(dialog){if(this.instances.length===0){setTimeout(function(){if($.ui.dialog.overlay.instances.length){$(document).bind($.ui.dialog.overlay.events,function(event){var dialogZ=$(event.target).parents('.ui-dialog[role=dialog]').css('zIndex')||0;return(dialogZ>$.ui.dialog.overlay.maxZ);});}},1);$(document).bind('keydown.dialog-overlay',function(event){(dialog.options.closeOnEscape&&event.keyCode&&event.keyCode==$.ui.keyCode.ESCAPE&&dialog.close(event));});$(window).bind('resize.dialog-overlay',$.ui.dialog.overlay.resize);}
var $el=$('<div></div>').appendTo(document.body).addClass('ui-widget-overlay').css({width:this.width(),height:this.height()});(dialog.options.bgiframe&&$.fn.bgiframe&&$el.bgiframe());this.instances.push($el);return $el;},destroy:function($el){this.instances.splice($.inArray(this.instances,$el),1);if(this.instances.length===0){$([document,window]).unbind('.dialog-overlay');}
$el.remove();var maxZ=0;$.each(this.instances,function(){maxZ=Math.max(maxZ,this.css('z-index'));});this.maxZ=maxZ;},height:function(){if($.browser.msie&&$.browser.version<7){var scrollHeight=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);var offsetHeight=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);if(scrollHeight<offsetHeight){return $(window).height()+'px';}else{return scrollHeight+'px';}}else{return $(document).height()+'px';}},width:function(){if($.browser.msie&&$.browser.version<7){var scrollWidth=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);var offsetWidth=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);if(scrollWidth<offsetWidth){return $(window).width()+'px';}else{return scrollWidth+'px';}}else{return $(document).width()+'px';}},resize:function(){var $overlays=$([]);$.each($.ui.dialog.overlay.instances,function(){$overlays=$overlays.add(this);});$overlays.css({width:0,height:0}).css({width:$.ui.dialog.overlay.width(),height:$.ui.dialog.overlay.height()});}});$.extend($.ui.dialog.overlay.prototype,{destroy:function(){$.ui.dialog.overlay.destroy(this.$el);}});})(jQuery);(function($){$.widget("ui.tabs",{_init:function(){if(this.options.deselectable!==undefined){this.options.collapsible=this.options.deselectable;}
this._tabify(true);},_setData:function(key,value){if(key=='selected'){if(this.options.collapsible&&value==this.options.selected){return;}
this.select(value);}
else{this.options[key]=value;if(key=='deselectable'){this.options.collapsible=value;}
this._tabify();}},_tabId:function(a){return a.title&&a.title.replace(/\s/g,'_').replace(/[^A-Za-z0-9\-_:\.]/g,'')||this.options.idPrefix+$.data(a);},_sanitizeSelector:function(hash){return hash.replace(/:/g,'\\:');},_cookie:function(){var cookie=this.cookie||(this.cookie=this.options.cookie.name||'ui-tabs-'+$.data(this.list[0]));return $.cookie.apply(null,[cookie].concat($.makeArray(arguments)));},_ui:function(tab,panel){return{tab:tab,panel:panel,index:this.anchors.index(tab)};},_cleanup:function(){this.lis.filter('.ui-state-processing').removeClass('ui-state-processing').find('span:data(label.tabs)').each(function(){var el=$(this);el.html(el.data('label.tabs')).removeData('label.tabs');});},_tabify:function(init){this.list=this.element.children('ul:first');this.lis=$('li:has(a[href])',this.list);this.anchors=this.lis.map(function(){return $('a',this)[0];});this.panels=$([]);var self=this,o=this.options;var fragmentId=/^#.+/;this.anchors.each(function(i,a){var href=$(a).attr('href');var hrefBase=href.split('#')[0],baseEl;if(hrefBase&&(hrefBase===location.toString().split('#')[0]||(baseEl=$('base')[0])&&hrefBase===baseEl.href)){href=a.hash;a.href=href;}
if(fragmentId.test(href)){self.panels=self.panels.add(self._sanitizeSelector(href));}
else if(href!='#'){$.data(a,'href.tabs',href);$.data(a,'load.tabs',href.replace(/#.*$/,''));var id=self._tabId(a);a.href='#'+id;var $panel=$('#'+id);if(!$panel.length){$panel=$(o.panelTemplate).attr('id',id).addClass('ui-tabs-panel ui-widget-content ui-corner-bottom').insertAfter(self.panels[i-1]||self.list);$panel.data('destroy.tabs',true);}
self.panels=self.panels.add($panel);}
else{o.disabled.push(i);}});if(init){this.element.addClass('ui-tabs ui-widget ui-widget-content ui-corner-all');this.list.addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');this.lis.addClass('ui-state-default ui-corner-top');this.panels.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom');if(o.selected===undefined){if(location.hash){this.anchors.each(function(i,a){if(a.hash==location.hash){o.selected=i;return false;}});}
if(typeof o.selected!='number'&&o.cookie){o.selected=parseInt(self._cookie(),10);}
if(typeof o.selected!='number'&&this.lis.filter('.ui-tabs-selected').length){o.selected=this.lis.index(this.lis.filter('.ui-tabs-selected'));}
o.selected=o.selected||0;}
else if(o.selected===null){o.selected=-1;}
o.selected=((o.selected>=0&&this.anchors[o.selected])||o.selected<0)?o.selected:0;o.disabled=$.unique(o.disabled.concat($.map(this.lis.filter('.ui-state-disabled'),function(n,i){return self.lis.index(n);}))).sort();if($.inArray(o.selected,o.disabled)!=-1){o.disabled.splice($.inArray(o.selected,o.disabled),1);}
this.panels.addClass('ui-tabs-hide');this.lis.removeClass('ui-tabs-selected ui-state-active');if(o.selected>=0&&this.anchors.length){this.panels.eq(o.selected).removeClass('ui-tabs-hide');this.lis.eq(o.selected).addClass('ui-tabs-selected ui-state-active');self.element.queue("tabs",function(){self._trigger('show',null,self._ui(self.anchors[o.selected],self.panels[o.selected]));});this.load(o.selected);}
$(window).bind('unload',function(){self.lis.add(self.anchors).unbind('.tabs');self.lis=self.anchors=self.panels=null;});}
else{o.selected=this.lis.index(this.lis.filter('.ui-tabs-selected'));}
this.element[o.collapsible?'addClass':'removeClass']('ui-tabs-collapsible');if(o.cookie){this._cookie(o.selected,o.cookie);}
for(var i=0,li;(li=this.lis[i]);i++){$(li)[$.inArray(i,o.disabled)!=-1&&!$(li).hasClass('ui-tabs-selected')?'addClass':'removeClass']('ui-state-disabled');}
if(o.cache===false){this.anchors.removeData('cache.tabs');}
this.lis.add(this.anchors).unbind('.tabs');if(o.event!='mouseover'){var addState=function(state,el){if(el.is(':not(.ui-state-disabled)')){el.addClass('ui-state-'+state);}};var removeState=function(state,el){el.removeClass('ui-state-'+state);};this.lis.bind('mouseover.tabs',function(){addState('hover',$(this));});this.lis.bind('mouseout.tabs',function(){removeState('hover',$(this));});this.anchors.bind('focus.tabs',function(){addState('focus',$(this).closest('li'));});this.anchors.bind('blur.tabs',function(){removeState('focus',$(this).closest('li'));});}
var hideFx,showFx;if(o.fx){if($.isArray(o.fx)){hideFx=o.fx[0];showFx=o.fx[1];}
else{hideFx=showFx=o.fx;}}
function resetStyle($el,fx){$el.css({display:''});if($.browser.msie&&fx.opacity){$el[0].style.removeAttribute('filter');}}
var showTab=showFx?function(clicked,$show){$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');$show.hide().removeClass('ui-tabs-hide').animate(showFx,showFx.duration||'normal',function(){resetStyle($show,showFx);self._trigger('show',null,self._ui(clicked,$show[0]));});}:function(clicked,$show){$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');$show.removeClass('ui-tabs-hide');self._trigger('show',null,self._ui(clicked,$show[0]));};var hideTab=hideFx?function(clicked,$hide){$hide.animate(hideFx,hideFx.duration||'normal',function(){self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');$hide.addClass('ui-tabs-hide');resetStyle($hide,hideFx);self.element.dequeue("tabs");});}:function(clicked,$hide,$show){self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');$hide.addClass('ui-tabs-hide');self.element.dequeue("tabs");};this.anchors.bind(o.event+'.tabs',function(){var el=this,$li=$(this).closest('li'),$hide=self.panels.filter(':not(.ui-tabs-hide)'),$show=$(self._sanitizeSelector(this.hash));if(($li.hasClass('ui-tabs-selected')&&!o.collapsible)||$li.hasClass('ui-state-disabled')||$li.hasClass('ui-state-processing')||self._trigger('select',null,self._ui(this,$show[0]))===false){this.blur();return false;}
o.selected=self.anchors.index(this);self.abort();if(o.collapsible){if($li.hasClass('ui-tabs-selected')){o.selected=-1;if(o.cookie){self._cookie(o.selected,o.cookie);}
self.element.queue("tabs",function(){hideTab(el,$hide);}).dequeue("tabs");this.blur();return false;}
else if(!$hide.length){if(o.cookie){self._cookie(o.selected,o.cookie);}
self.element.queue("tabs",function(){showTab(el,$show);});self.load(self.anchors.index(this));this.blur();return false;}}
if(o.cookie){self._cookie(o.selected,o.cookie);}
if($show.length){if($hide.length){self.element.queue("tabs",function(){hideTab(el,$hide);});}
self.element.queue("tabs",function(){showTab(el,$show);});self.load(self.anchors.index(this));}
else{throw'jQuery UI Tabs: Mismatching fragment identifier.';}
if($.browser.msie){this.blur();}});this.anchors.bind('click.tabs',function(){return false;});},destroy:function(){var o=this.options;this.abort();this.element.unbind('.tabs').removeClass('ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible').removeData('tabs');this.list.removeClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');this.anchors.each(function(){var href=$.data(this,'href.tabs');if(href){this.href=href;}
var $this=$(this).unbind('.tabs');$.each(['href','load','cache'],function(i,prefix){$this.removeData(prefix+'.tabs');});});this.lis.unbind('.tabs').add(this.panels).each(function(){if($.data(this,'destroy.tabs')){$(this).remove();}
else{$(this).removeClass(['ui-state-default','ui-corner-top','ui-tabs-selected','ui-state-active','ui-state-hover','ui-state-focus','ui-state-disabled','ui-tabs-panel','ui-widget-content','ui-corner-bottom','ui-tabs-hide'].join(' '));}});if(o.cookie){this._cookie(null,o.cookie);}},add:function(url,label,index){if(index===undefined){index=this.anchors.length;}
var self=this,o=this.options,$li=$(o.tabTemplate.replace(/#\{href\}/g,url).replace(/#\{label\}/g,label)),id=!url.indexOf('#')?url.replace('#',''):this._tabId($('a',$li)[0]);$li.addClass('ui-state-default ui-corner-top').data('destroy.tabs',true);var $panel=$('#'+id);if(!$panel.length){$panel=$(o.panelTemplate).attr('id',id).data('destroy.tabs',true);}
$panel.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide');if(index>=this.lis.length){$li.appendTo(this.list);$panel.appendTo(this.list[0].parentNode);}
else{$li.insertBefore(this.lis[index]);$panel.insertBefore(this.panels[index]);}
o.disabled=$.map(o.disabled,function(n,i){return n>=index?++n:n;});this._tabify();if(this.anchors.length==1){$li.addClass('ui-tabs-selected ui-state-active');$panel.removeClass('ui-tabs-hide');this.element.queue("tabs",function(){self._trigger('show',null,self._ui(self.anchors[0],self.panels[0]));});this.load(0);}
this._trigger('add',null,this._ui(this.anchors[index],this.panels[index]));},remove:function(index){var o=this.options,$li=this.lis.eq(index).remove(),$panel=this.panels.eq(index).remove();if($li.hasClass('ui-tabs-selected')&&this.anchors.length>1){this.select(index+(index+1<this.anchors.length?1:-1));}
o.disabled=$.map($.grep(o.disabled,function(n,i){return n!=index;}),function(n,i){return n>=index?--n:n;});this._tabify();this._trigger('remove',null,this._ui($li.find('a')[0],$panel[0]));},enable:function(index){var o=this.options;if($.inArray(index,o.disabled)==-1){return;}
this.lis.eq(index).removeClass('ui-state-disabled');o.disabled=$.grep(o.disabled,function(n,i){return n!=index;});this._trigger('enable',null,this._ui(this.anchors[index],this.panels[index]));},disable:function(index){var self=this,o=this.options;if(index!=o.selected){this.lis.eq(index).addClass('ui-state-disabled');o.disabled.push(index);o.disabled.sort();this._trigger('disable',null,this._ui(this.anchors[index],this.panels[index]));}},select:function(index){if(typeof index=='string'){index=this.anchors.index(this.anchors.filter('[href$='+index+']'));}
else if(index===null){index=-1;}
if(index==-1&&this.options.collapsible){index=this.options.selected;}
this.anchors.eq(index).trigger(this.options.event+'.tabs');},load:function(index){var self=this,o=this.options,a=this.anchors.eq(index)[0],url=$.data(a,'load.tabs');this.abort();if(!url||this.element.queue("tabs").length!==0&&$.data(a,'cache.tabs')){this.element.dequeue("tabs");return;}
this.lis.eq(index).addClass('ui-state-processing');if(o.spinner){var span=$('span',a);span.data('label.tabs',span.html()).html(o.spinner);}
this.xhr=$.ajax($.extend({},o.ajaxOptions,{url:url,success:function(r,s){$(self._sanitizeSelector(a.hash)).html(r);self._cleanup();if(o.cache){$.data(a,'cache.tabs',true);}
self._trigger('load',null,self._ui(self.anchors[index],self.panels[index]));try{o.ajaxOptions.success(r,s);}
catch(e){}
self.element.dequeue("tabs");}}));},abort:function(){this.element.queue([]);this.panels.stop(false,true);if(this.xhr){this.xhr.abort();delete this.xhr;}
this._cleanup();},url:function(index,url){this.anchors.eq(index).removeData('cache.tabs').data('load.tabs',url);},length:function(){return this.anchors.length;}});$.extend($.ui.tabs,{version:'1.7.2',getter:'length',defaults:{ajaxOptions:null,cache:false,cookie:null,collapsible:false,disabled:[],event:'click',fx:null,idPrefix:'ui-tabs-',panelTemplate:'<div></div>',spinner:'<em>Loading&#8230;</em>',tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>'}});$.extend($.ui.tabs.prototype,{rotation:null,rotate:function(ms,continuing){var self=this,o=this.options;var rotate=self._rotate||(self._rotate=function(e){clearTimeout(self.rotation);self.rotation=setTimeout(function(){var t=o.selected;self.select(++t<self.anchors.length?t:0);},ms);if(e){e.stopPropagation();}});var stop=self._unrotate||(self._unrotate=!continuing?function(e){if(e.clientX){self.rotate(null);}}:function(e){t=o.selected;rotate();});if(ms){this.element.bind('tabsshow',rotate);this.anchors.bind(o.event+'.tabs',stop);rotate();}
else{clearTimeout(self.rotation);this.element.unbind('tabsshow',rotate);this.anchors.unbind(o.event+'.tabs',stop);delete this._rotate;delete this._unrotate;}}});})(jQuery);


(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+
(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)
this.insertBefore(document.createElement(html),this.firstChild);});}
return this;};})(jQuery);


(function($){var Range=function(x1,y1,x2,y2){this.x1=x1;this.x2=x2;this.y1=y1;this.y2=y2;};Range.prototype.contains=function(range){return(this.x1<=range.x1&&range.x2<=this.x2)&&(this.y1<=range.y1&&range.y2<=this.y2);};Range.prototype.transform=function(x,y){return new Range(this.x1+x,this.y1+y,this.x2+x,this.y2+y);};$.fn.positionBy=function(args){var date1=new Date();if(this.length==0){return this;}
var args=$.extend({target:null,targetPos:null,elementPos:null,x:null,y:null,positions:null,addClass:false,force:false,container:window,hideAfterPosition:false},args);if(args.x!=null){var tLeft=args.x;var tTop=args.y;var tWidth=0;var tHeight=0;}else{var $target=$($(args.target)[0]);var tWidth=$target.outerWidth();var tHeight=$target.outerHeight();var tOffset=$target.offset();var tLeft=tOffset.left;var tTop=tOffset.top;}
var tRight=tLeft+tWidth;var tBottom=tTop+tHeight;return this.each(function(){var $element=$(this);if(!$element.is(':visible')){$element.css({left:-3000,top:-3000}).show();}
var eWidth=$element.outerWidth();var eHeight=$element.outerHeight();var position=[];var next=[];position[0]=new Range(tRight,tTop,tRight+eWidth,tTop+eHeight);next[0]=[1,7,4];position[1]=new Range(tRight,tBottom-eHeight,tRight+eWidth,tBottom);next[1]=[0,6,4];position[2]=new Range(tRight,tBottom,tRight+eWidth,tBottom+eHeight);next[2]=[1,3,10];position[3]=new Range(tRight-eWidth,tBottom,tRight,tBottom+eHeight);next[3]=[1,6,10];position[4]=new Range(tLeft,tBottom,tLeft+eWidth,tBottom+eHeight);next[4]=[1,6,9];position[5]=new Range(tLeft-eWidth,tBottom,tLeft,tBottom+eHeight);next[5]=[6,4,9];position[6]=new Range(tLeft-eWidth,tBottom-eHeight,tLeft,tBottom);next[6]=[7,1,4];position[7]=new Range(tLeft-eWidth,tTop,tLeft,tTop+eHeight);next[7]=[6,0,4];position[8]=new Range(tLeft-eWidth,tTop-eHeight,tLeft,tTop);next[8]=[7,9,4];position[9]=new Range(tLeft,tTop-eHeight,tLeft+eWidth,tTop);next[9]=[0,7,4];position[10]=new Range(tRight-eWidth,tTop-eHeight,tRight,tTop);next[10]=[0,7,3];position[11]=new Range(tRight,tTop-eHeight,tRight+eWidth,tTop);next[11]=[0,10,3];position[12]=new Range(tRight-eWidth,tTop,tRight,tTop+eHeight);next[12]=[13,7,10];position[13]=new Range(tRight-eWidth,tBottom-eHeight,tRight,tBottom);next[13]=[12,6,3];position[14]=new Range(tLeft,tBottom-eHeight,tLeft+eWidth,tBottom);next[14]=[15,1,4];position[15]=new Range(tLeft,tTop,tLeft+eWidth,tTop+eHeight);next[15]=[14,0,9];if(args.positions!==null){var pos=args.positions[0];}else if(args.targetPos!=null&&args.elementPos!=null){var pos=[];pos[0]=[];pos[0][0]=15;pos[0][1]=7;pos[0][2]=8;pos[0][3]=9;pos[1]=[];pos[1][0]=0;pos[1][1]=12;pos[1][2]=10;pos[1][3]=11;pos[2]=[];pos[2][0]=2;pos[2][1]=3;pos[2][2]=13;pos[2][3]=1;pos[3]=[];pos[3][0]=4;pos[3][1]=5;pos[3][2]=6;pos[3][3]=14;var pos=pos[args.targetPos][args.elementPos];}
var ePos=position[pos];var fPos=pos;if(!args.force){$window=$(window);var sx=$window.scrollLeft();var sy=$window.scrollTop();var container=new Range(sx,sy,sx+$window.width(),sy+$window.height());var stack;if(args.positions){stack=args.positions;}else{stack=[pos];}
var test=[];while(stack.length>0){var p=stack.shift();if(test[p]){continue;}
test[p]=true;if(!container.contains(position[p])){if(args.positions===null){stack=jQuery.merge(stack,next[p]);}}else{ePos=position[p];break;}}}
$element.parents().each(function(){var $this=$(this);if($this.css('position')!='static'){var abs=$this.offset();ePos=ePos.transform(-abs.left,-abs.top);return false;}});var css={left:ePos.x1,top:ePos.y1};if(args.hideAfterPosition){css['display']='none';}
$element.css(css);if(args.addClass){$element.removeClass('positionBy0 positionBy1 positionBy2 positionBy3 positionBy4 positionBy5 '
+'positionBy6 positionBy7 positionBy8 positionBy9 positionBy10 positionBy11 '
+'positionBy12 positionBy13 positionBy14 positionBy15').addClass('positionBy'+p);}});};})(jQuery);

;(function($){if(/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery)||/^1.1/.test($.fn.jquery)){alert('blockUI requires jQuery v1.2.3 or later!  You are using v'+$.fn.jquery);return;}
$.blockUI=function(opts){install(window,opts);};$.unblockUI=function(opts){remove(window,opts);};$.fn.block=function(opts){return this.each(function(){if($.css(this,'position')=='static')
this.style.position='relative';if($.browser.msie)
this.style.zoom=1;install(this,opts);});};$.fn.unblock=function(opts){return this.each(function(){remove(this,opts);});};$.blockUI.version=2.11;$.blockUI.defaults={message:'<h1>Please wait...</h1>',css:{padding:0,margin:0,width:'30%',top:'40%',left:'35%',textAlign:'center',color:'#000',border:'3px solid #aaa',backgroundColor:'#fff',cursor:'wait'},overlayCSS:{backgroundColor:'#000',opacity:'0.6'},baseZ:1000,centerX:true,centerY:true,allowBodyStretch:true,constrainTabKey:true,fadeOut:400,focusInput:true,applyPlatformOpacityRules:true,onUnblock:null,quirksmodeOffsetHack:4};var ie6=$.browser.msie&&/MSIE 6.0/.test(navigator.userAgent);var pageBlock=null;var pageBlockEls=[];function install(el,opts){var full=(el==window);var msg=opts&&opts.message!==undefined?opts.message:undefined;opts=$.extend({},$.blockUI.defaults,opts||{});opts.overlayCSS=$.extend({},$.blockUI.defaults.overlayCSS,opts.overlayCSS||{});var css=$.extend({},$.blockUI.defaults.css,opts.css||{});msg=msg===undefined?opts.message:msg;if(full&&pageBlock)
remove(window,{fadeOut:0});if(msg&&typeof msg!='string'&&(msg.parentNode||msg.jquery)){var node=msg.jquery?msg[0]:msg;var data={};$(el).data('blockUI.history',data);data.el=node;data.parent=node.parentNode;data.display=node.style.display;data.position=node.style.position;data.parent.removeChild(node);}
var z=opts.baseZ;var lyr1=($.browser.msie)?$('<iframe class="blockUI" style="z-index:'+z+++';border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="javascript:false;"></iframe>'):$('<div class="blockUI" style="display:none"></div>');var lyr2=$('<div class="blockUI blockOverlay" style="z-index:'+z+++';cursor:wait;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');var lyr3=full?$('<div class="blockUI blockMsg blockPage" style="z-index:'+z+';position:fixed"></div>'):$('<div class="blockUI blockMsg blockElement" style="z-index:'+z+';display:none;position:absolute"></div>');if(msg)
lyr3.css(css);if(!opts.applyPlatformOpacityRules||!($.browser.mozilla&&/Linux/.test(navigator.platform)))
lyr2.css(opts.overlayCSS);lyr2.css('position',full?'fixed':'absolute');if($.browser.msie)
lyr1.css('opacity','0.0');$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full?'body':el);var expr=$.browser.msie&&(!$.boxModel||$('object,embed',full?null:el).length>0);if(ie6||expr){if(full&&opts.allowBodyStretch&&$.boxModel)
$('html,body').css('height','100%');if((ie6||!$.boxModel)&&!full){var t=sz(el,'borderTopWidth'),l=sz(el,'borderLeftWidth');var fixT=t?'(0 - '+t+')':0;var fixL=l?'(0 - '+l+')':0;}
$.each([lyr1,lyr2,lyr3],function(i,o){var s=o[0].style;s.position='absolute';if(i<2){full?s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"'):s.setExpression('height','this.parentNode.offsetHeight + "px"');full?s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'):s.setExpression('width','this.parentNode.offsetWidth + "px"');if(fixL)s.setExpression('left',fixL);if(fixT)s.setExpression('top',fixT);}
else if(opts.centerY){if(full)s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');s.marginTop=0;}});}
lyr3.append(msg).show();if(msg&&(msg.jquery||msg.nodeType))
$(msg).show();bind(1,el,opts);if(full){pageBlock=lyr3[0];pageBlockEls=$(':input:enabled:visible',pageBlock);if(opts.focusInput)
setTimeout(focus,20);}
else
center(lyr3[0],opts.centerX,opts.centerY);};function remove(el,opts){var full=el==window;var data=$(el).data('blockUI.history');opts=$.extend({},$.blockUI.defaults,opts||{});bind(0,el,opts);var els=full?$('body').children().filter('.blockUI'):$('.blockUI',el);if(full)
pageBlock=pageBlockEls=null;if(opts.fadeOut){els.fadeOut(opts.fadeOut);setTimeout(function(){reset(els,data,opts,el);},opts.fadeOut);}
else
reset(els,data,opts,el);};function reset(els,data,opts,el){els.each(function(i,o){if(this.parentNode)
this.parentNode.removeChild(this);});if(data&&data.el){data.el.style.display=data.display;data.el.style.position=data.position;data.parent.appendChild(data.el);$(data.el).removeData('blockUI.history');}
if(typeof opts.onUnblock=='function')
opts.onUnblock(el,opts);};function bind(b,el,opts){var full=el==window,$el=$(el);if(!b&&(full&&!pageBlock||!full&&!$el.data('blockUI.isBlocked')))
return;if(!full)
$el.data('blockUI.isBlocked',b);var events='mousedown mouseup keydown keypress';b?$(document).bind(events,opts,handler):$(document).unbind(events,handler);};function handler(e){if(e.keyCode&&e.keyCode==9){if(pageBlock&&e.data.constrainTabKey){var els=pageBlockEls;var fwd=!e.shiftKey&&e.target==els[els.length-1];var back=e.shiftKey&&e.target==els[0];if(fwd||back){setTimeout(function(){focus(back)},10);return false;}}}
if($(e.target).parents('div.blockMsg').length>0)
return true;return $(e.target).parents().children().filter('div.blockUI').length==0;};function focus(back){if(!pageBlockEls)
return;var e=pageBlockEls[back===true?pageBlockEls.length-1:0];if(e)
e.focus();};function center(el,x,y){var p=el.parentNode,s=el.style;var l=((p.offsetWidth-el.offsetWidth)/2)-sz(p,'borderLeftWidth');var t=((p.offsetHeight-el.offsetHeight)/2)-sz(p,'borderTopWidth');if(x)s.left=l>0?(l+'px'):'0';if(y)s.top=t>0?(t+'px'):'0';};function sz(el,p){return parseInt($.css(el,p))||0;};})(jQuery);


(function($){function addEvents(ul){var settings=$.data($(ul).parents().andSelf().filter('ul.jd_menu')[0],'jdMenuSettings');$('> li',ul).bind('mouseenter.jdmenu mouseleave.jdmenu',function(evt){$(this).toggleClass('jdm_hover');var ul=$('> ul',this);if(ul.length==1){clearTimeout(this.$jdTimer);var enter=(evt.type=='mouseenter');var fn=(enter?showMenu:hideMenu);this.$jdTimer=setTimeout(function(){fn(ul[0],settings.onAnimate,settings.isVertical);},enter?settings.showDelay:settings.hideDelay);}}).bind('click.jdmenu',function(evt){var ul=$('> ul',this);if(ul.length==1&&(settings.disableLinks==true||$(this).hasClass('accessible'))){showMenu(ul,settings.onAnimate,settings.isVertical);return false;}
if(evt.target==this){var link=$('> a',evt.target).not('.accessible');if(link.length>0){var a=link[0];if(!a.onclick){window.open(a.href,a.target||'_self');}else{$(a).trigger('click');}}}
if(settings.disableLinks||(!settings.disableLinks&&!$(this).parent().hasClass('jd_menu'))){$(this).parent().jdMenuHide();evt.stopPropagation();}}).find('> a').bind('focus.jdmenu blur.jdmenu',function(evt){var p=$(this).parents('li:eq(0)');if(evt.type=='focus'){p.addClass('jdm_hover');}else{p.removeClass('jdm_hover');}}).filter('.accessible').bind('click.jdmenu',function(evt){evt.preventDefault();});}
function showMenu(ul,animate,vertical){var ul=$(ul);if(ul.is(':visible')){return;}
ul.bgiframe();var li=ul.parent();ul.trigger('jdMenuShow').positionBy({target:li[0],targetPos:(vertical===true||!li.parent().hasClass('jd_menu')?1:3),elementPos:0,hideAfterPosition:true});if(!ul.hasClass('jdm_events')){ul.addClass('jdm_events');addEvents(ul);}
li.addClass('jdm_active').siblings('li').find('> ul:eq(0):visible').each(function(){hideMenu(this);});if(animate===undefined){ul.show();}else{animate.apply(ul[0],[true]);}}
function hideMenu(ul,animate){var ul=$(ul);$('.bgiframe',ul).remove();ul.filter(':not(.jd_menu)').find('> li > ul:eq(0):visible').each(function(){hideMenu(this);}).end();if(animate===undefined){if(!ul.hasClass('jd_menu'))
ul.hide()}else{animate.apply(ul[0],[false]);}
ul.trigger('jdMenuHide').parents('li:eq(0)').removeClass('jdm_active jdm_hover').end().find('> li').removeClass('jdm_active jdm_hover');}
$.fn.jdMenu=function(settings){var settings=$.extend({showDelay:200,hideDelay:500,disableLinks:true},settings);if(!$.isFunction(settings.onAnimate)){settings.onAnimate=undefined;}
return this.filter('ul.jd_menu').each(function(){$.data(this,'jdMenuSettings',$.extend({isVertical:$(this).hasClass('jd_menu_vertical')},settings));$(this).addClass('ui-widget ui-state-default');$(this).append('<div style="clear:both;"></div>');$(this).find('ul').addClass('ui-widget ui-state-default ui-no-bg-image');addEvents(this);});};$.fn.jdMenuUnbind=function(){$('ul.jdm_events',this).unbind('.jdmenu').find('> a').unbind('.jdmenu');};$.fn.jdMenuHide=function(){return this.filter('ul').each(function(){hideMenu(this);});};$(window).bind('click.jdmenu',function(){$('ul.jd_menu ul:visible').jdMenuHide();});})(jQuery);


(function(jQuery){jQuery.fn.__bind__=jQuery.fn.bind;jQuery.fn.__unbind__=jQuery.fn.unbind;jQuery.fn.__find__=jQuery.fn.find;var hotkeys={version:'0.7.9',override:/keypress|keydown|keyup/g,triggersMap:{},specialKeys:{27:'esc',9:'tab',32:'space',13:'return',8:'backspace',145:'scroll',20:'capslock',144:'numlock',19:'pause',45:'insert',36:'home',46:'del',35:'end',33:'pageup',34:'pagedown',37:'left',38:'up',39:'right',40:'down',109:'-',112:'f1',113:'f2',114:'f3',115:'f4',116:'f5',117:'f6',118:'f7',119:'f8',120:'f9',121:'f10',122:'f11',123:'f12',191:'/'},shiftNums:{"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":"\"",",":"<",".":">","/":"?","\\":"|"},newTrigger:function(type,combi,callback){var result={};result[type]={};result[type][combi]={cb:callback,disableInInput:false};return result;}};hotkeys.specialKeys=jQuery.extend(hotkeys.specialKeys,{96:'0',97:'1',98:'2',99:'3',100:'4',101:'5',102:'6',103:'7',104:'8',105:'9',106:'*',107:'+',109:'-',110:'.',111:'/'});jQuery.fn.find=function(selector){this.query=selector;return jQuery.fn.__find__.apply(this,arguments);};jQuery.fn.unbind=function(type,combi,fn){if(jQuery.isFunction(combi)){fn=combi;combi=null;}
if(combi&&typeof combi==='string'){var selectorId=((this.prevObject&&this.prevObject.query)||(this[0].id&&this[0].id)||this[0]).toString();var hkTypes=type.split(' ');for(var x=0;x<hkTypes.length;x++){delete hotkeys.triggersMap[selectorId][hkTypes[x]][combi];}}
return this.__unbind__(type,fn);};jQuery.fn.bind=function(type,data,fn){var handle=type.match(hotkeys.override);if(jQuery.isFunction(data)||!handle){return this.__bind__(type,data,fn);}
else{var result=null,pass2jq=jQuery.trim(type.replace(hotkeys.override,''));if(pass2jq){result=this.__bind__(pass2jq,data,fn);}
if(typeof data==="string"){data={'combi':data};}
if(data.combi){for(var x=0;x<handle.length;x++){var eventType=handle[x];var combi=data.combi.toLowerCase(),trigger=hotkeys.newTrigger(eventType,combi,fn),selectorId=((this.prevObject&&this.prevObject.query)||(this[0].id&&this[0].id)||this[0]).toString();trigger[eventType][combi].disableInInput=data.disableInInput;if(!hotkeys.triggersMap[selectorId]){hotkeys.triggersMap[selectorId]=trigger;}
else if(!hotkeys.triggersMap[selectorId][eventType]){hotkeys.triggersMap[selectorId][eventType]=trigger[eventType];}
var mapPoint=hotkeys.triggersMap[selectorId][eventType][combi];if(!mapPoint){hotkeys.triggersMap[selectorId][eventType][combi]=[trigger[eventType][combi]];}
else if(mapPoint.constructor!==Array){hotkeys.triggersMap[selectorId][eventType][combi]=[mapPoint];}
else{hotkeys.triggersMap[selectorId][eventType][combi][mapPoint.length]=trigger[eventType][combi];}
this.each(function(){var jqElem=jQuery(this);if(jqElem.attr('hkId')&&jqElem.attr('hkId')!==selectorId){selectorId=jqElem.attr('hkId')+";"+selectorId;}
jqElem.attr('hkId',selectorId);});result=this.__bind__(handle.join(' '),data,hotkeys.handler)}}
return result;}};hotkeys.findElement=function(elem){if(!jQuery(elem).attr('hkId')){if(jQuery.browser.opera||jQuery.browser.safari){while(!jQuery(elem).attr('hkId')&&elem.parentNode){elem=elem.parentNode;}}}
return elem;};hotkeys.handler=function(event){var target=hotkeys.findElement(event.currentTarget),jTarget=jQuery(target),ids=jTarget.attr('hkId');if(ids){ids=ids.split(';');var code=event.which,type=event.type,special=hotkeys.specialKeys[code],character=!special&&String.fromCharCode(code).toLowerCase(),shift=event.shiftKey,ctrl=event.ctrlKey,alt=event.altKey||event.originalEvent.altKey,mapPoint=null;for(var x=0;x<ids.length;x++){if(hotkeys.triggersMap[ids[x]][type]){mapPoint=hotkeys.triggersMap[ids[x]][type];break;}}
if(mapPoint){var trigger;if(!shift&&!ctrl&&!alt){trigger=mapPoint[special]||(character&&mapPoint[character]);}
else{var modif='';if(alt)modif+='alt+';if(ctrl)modif+='ctrl+';if(shift)modif+='shift+';trigger=mapPoint[modif+special];if(!trigger){if(character){trigger=mapPoint[modif+character]||mapPoint[modif+hotkeys.shiftNums[character]]||(modif==='shift+'&&mapPoint[hotkeys.shiftNums[character]]);}}}
if(trigger){var result=false;for(var x=0;x<trigger.length;x++){if(trigger[x].disableInInput){var elem=jQuery(event.target);if(jTarget.is("input")||jTarget.is("textarea")||jTarget.is("select")||elem.is("input")||elem.is("textarea")||elem.is("select")){return true;}}
result=result||trigger[x].cb.apply(this,[event]);}
return result;}}}};window.hotkeys=hotkeys;return jQuery;})(jQuery);


var imageUrl='editor_images/color.png';$.fn.colorPicker=function(o){var options=$.extend({},$.fn.colorPicker.defaults,o);var me=this;if($('#iColorPicker').size()==0){$(document.createElement("div")).attr("id","iColorPicker").css('display','none').html('<table class="pickerTable" id="pickerTable0"><thead id="hexSection0"><tr><td style="background:#f00;" hx="f00"></td><td style="background:#ff0" hx="ff0"></td><td style="background:#0f0" hx="0f0"></td><td style="background:#0ff" hx="0ff"></td><td style="background:#00f" hx="00f"></td><td style="background:#f0f" hx="f0f"></td><td style="background:#fff" hx="fff"></td><td style="background:#ebebeb" hx="ebebeb"></td><td style="background:#e1e1e1" hx="e1e1e1"></td><td style="background:#d7d7d7" hx="d7d7d7"></td><td style="background:#cccccc" hx="cccccc"></td><td style="background:#c2c2c2" hx="c2c2c2"></td><td style="background:#b7b7b7" hx="b7b7b7"></td><td style="background:#acacac" hx="acacac"></td><td style="background:#a0a0a0" hx="a0a0a0"></td><td style="background:#959595" hx="959595"></td></tr><tr><td style="background:#ee1d24" hx="ee1d24"></td><td style="background:#fff100" hx="fff100"></td><td style="background:#00a650" hx="00a650"></td><td style="background:#00aeef" hx="00aeef"></td><td style="background:#2f3192" hx="2f3192"></td><td style="background:#ed008c" hx="ed008c"></td><td style="background:#898989" hx="898989"></td><td style="background:#7d7d7d" hx="7d7d7d"></td><td style="background:#707070" hx="707070"></td><td style="background:#626262" hx="626262"></td><td style="background:#555" hx="555"></td><td style="background:#464646" hx="464646"></td><td style="background:#363636" hx="363636"></td><td style="background:#262626" hx="262626"></td><td style="background:#111" hx="111"></td><td style="background:#000" hx="000"></td></tr><tr><td style="background:#f7977a" hx="f7977a"></td><td style="background:#fbad82" hx="fbad82"></td><td style="background:#fdc68c" hx="fdc68c"></td><td style="background:#fff799" hx="fff799"></td><td style="background:#c6df9c" hx="c6df9c"></td><td style="background:#a4d49d" hx="a4d49d"></td><td style="background:#81ca9d" hx="81ca9d"></td><td style="background:#7bcdc9" hx="7bcdc9"></td><td style="background:#6ccff7" hx="6ccff7"></td><td style="background:#7ca6d8" hx="7ca6d8"></td><td style="background:#8293ca" hx="8293ca"></td><td style="background:#8881be" hx="8881be"></td><td style="background:#a286bd" hx="a286bd"></td><td style="background:#bc8cbf" hx="bc8cbf"></td><td style="background:#f49bc1" hx="f49bc1"></td><td style="background:#f5999d" hx="f5999d"></td></tr><tr><td style="background:#f16c4d" hx="f16c4d"></td><td style="background:#f68e54" hx="f68e54"></td><td style="background:#fbaf5a" hx="fbaf5a"></td><td style="background:#fff467" hx="fff467"></td><td style="background:#acd372" hx="acd372"></td><td style="background:#7dc473" hx="7dc473"></td><td style="background:#39b778" hx="39b778"></td><td style="background:#16bcb4" hx="16bcb4"></td><td style="background:#00bff3" hx="00bff3"></td><td style="background:#438ccb" hx="438ccb"></td><td style="background:#5573b7" hx="5573b7"></td><td style="background:#5e5ca7" hx="5e5ca7"></td><td style="background:#855fa8" hx="855fa8"></td><td style="background:#a763a9" hx="a763a9"></td><td style="background:#ef6ea8" hx="ef6ea8"></td><td style="background:#f16d7e" hx="f16d7e"></td></tr><tr><td style="background:#ee1d24" hx="ee1d24"></td><td style="background:#f16522" hx="f16522"></td><td style="background:#f7941d" hx="f7941d"></td><td style="background:#fff100" hx="fff100"></td><td style="background:#8fc63d" hx="8fc63d"></td><td style="background:#37b44a" hx="37b44a"></td><td style="background:#00a650" hx="00a650"></td><td style="background:#00a99e" hx="00a99e"></td><td style="background:#00aeef" hx="00aeef"></td><td style="background:#0072bc" hx="0072bc"></td><td style="background:#0054a5" hx="0054a5"></td><td style="background:#2f3192" hx="2f3192"></td><td style="background:#652c91" hx="652c91"></td><td style="background:#91278f" hx="91278f"></td><td style="background:#ed008c" hx="ed008c"></td><td style="background:#ee105a" hx="ee105a"></td></tr><tr><td style="background:#9d0a0f" hx="9d0a0f"></td><td style="background:#a1410d" hx="a1410d"></td><td style="background:#a36209" hx="a36209"></td><td style="background:#aba000" hx="aba000"></td><td style="background:#588528" hx="588528"></td><td style="background:#197b30" hx="197b30"></td><td style="background:#007236" hx="007236"></td><td style="background:#00736a" hx="00736a"></td><td style="background:#0076a4" hx="0076a4"></td><td style="background:#004a80" hx="004a80"></td><td style="background:#003370" hx="003370"></td><td style="background:#1d1363" hx="1d1363"></td><td style="background:#450e61" hx="450e61"></td><td style="background:#62055f" hx="62055f"></td><td style="background:#9e005c" hx="9e005c"></td><td style="background:#9d0039" hx="9d0039"></td></tr><tr><td style="background:#790000" hx="790000"></td><td style="background:#7b3000" hx="7b3000"></td><td style="background:#7c4900" hx="7c4900"></td><td style="background:#827a00" hx="827a00"></td><td style="background:#3e6617" hx="3e6617"></td><td style="background:#045f20" hx="045f20"></td><td style="background:#005824" hx="005824"></td><td style="background:#005951" hx="005951"></td><td style="background:#005b7e" hx="005b7e"></td><td style="background:#003562" hx="003562"></td><td style="background:#002056" hx="002056"></td><td style="background:#0c004b" hx="0c004b"></td><td style="background:#30004a" hx="30004a"></td><td style="background:#4b0048" hx="4b0048"></td><td style="background:#7a0045" hx="7a0045"></td><td style="background:#7a0026" hx="7a0026"></td></tr></thead><tbody><tr><td style="border:1px solid #000;background:#fff;cursor:pointer;height:60px;-moz-background-clip:-moz-initial;-moz-background-origin:-moz-initial;-moz-background-inline-policy:-moz-initial;" colspan="16" align="center" id="colorPreview"><span style="color:#000;border:1px solid rgb(0, 0, 0);padding:5px;background-color:#fff;font:11px Arial, Helvetica, sans-serif;"></span></td></tr></tbody></table><style>#iColorPicker input{margin:2px}</style>').appendTo("body");$(document.createElement("div")).attr("id","iColorPickerBg").click(function(){$("#iColorPickerBg").hide();$("#iColorPicker").hide();return false;}).appendTo("body");$('table.pickerTable td').css({'width':'12px','height':'14px','border':'1px solid #000','cursor':'pointer'});$('#iColorPicker table.pickerTable').css({'border-collapse':'collapse'});$('#iColorPicker').css({'border':'1px solid #ccc','background':'#333','padding':'5px','color':'#fff','z-index':9999})
$('#colorPreview').css({'height':'50px'});$('#iColorPicker').attr('unselectable','on');$('#iColorPicker *').attr('unselectable','on');}
$.fn.colorPicker.setInputColor(this);if(options.immediate){iColorShow(this,options.done);}
else{$(this).focus(function(){iColorShow(this,options.done);});}
return this;}
$.fn.colorPicker.defaults={done:function(id,val){$.fn.colorPicker.setValue(id,val);},immediate:false};$.fn.colorPicker.setInputColor=function(query){$(query).each(function(){if(RGBColor){var c=new RGBColor($(this).val());$(this).val(c.toHex());var brightness=c.r+c.g+c.b;if(brightness>=128*3){$(this).css({color:'#000000',background:c.toHex()});}
else{$(this).css({color:'#ffffff',background:c.toHex()});}}
else{$(this).css("backgroundColor",$(this).val());}});}
$.fn.colorPicker.setValue=function(query,val){if(val!=$(query).val()){$(query).val(val);$(query).change();}
$.fn.colorPicker.setInputColor(query);}
function iColorShow(id,done){var eICP=$(id).offset();$("#iColorPicker").css({'top':eICP.top+($(id).outerHeight())+"px",'left':(eICP.left)+"px",'position':'absolute'}).show();$("#iColorPickerBg").css({'position':'absolute','top':0,'left':0,'width':'100%','height':'100%'}).show();var def=$(id).val();$('#colorPreview span').text(def);$('#colorPreview').css('background',def);$('#color').val(def);var hxs=$('#iColorPicker');for(i=0;i<hxs.length;i++){var tbl=document.getElementById('hexSection'+i);var tblChilds=tbl.childNodes;for(j=0;j<tblChilds.length;j++){var tblCells=tblChilds[j].childNodes;for(k=0;k<tblCells.length;k++){$(tblChilds[j].childNodes[k]).unbind().mouseover(function(a){var aaa="#"+$(this).attr('hx');$('#colorPreview').css('background',aaa);$('#colorPreview span').text(aaa)}).mousedown(function(){var aaa="#"+$(this).attr('hx');done(id,aaa);$("#iColorPickerBg").hide();$("#iColorPicker").hide();return false;})}}}}


(function($){var menu,shadow,trigger,content,hash,currentTarget;var defaults={menuStyle:{listStyle:'none',padding:'1px',margin:'0px',backgroundColor:'#fff',border:'1px solid #999'},itemStyle:{margin:'0px',color:'#000',display:'block',cursor:'default',padding:'3px',border:'1px solid #fff',backgroundColor:'transparent'},itemHoverStyle:{border:'1px solid #0a246a',backgroundColor:'#b6bdd2'},eventPosX:'pageX',eventPosY:'pageY',shadow:true,onContextMenu:null,onShowMenu:null};$.fn.contextMenu=function(id,options){if(!menu){menu=$('<div id="jqContextMenu"></div>').hide().css({position:'absolute',zIndex:'800'}).appendTo('body').bind('click',function(e){e.stopPropagation();});}
if(!shadow){shadow=$('<div></div>').css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:799}).appendTo('body').hide();}
hash=hash||[];hash.push({id:id,menuStyle:$.extend({},defaults.menuStyle,options.menuStyle||{}),itemStyle:$.extend({},defaults.itemStyle,options.itemStyle||{}),itemHoverStyle:$.extend({},defaults.itemHoverStyle,options.itemHoverStyle||{}),bindings:options.bindings||{},shadow:options.shadow||options.shadow===false?options.shadow:defaults.shadow,onContextMenu:options.onContextMenu||defaults.onContextMenu,onShowMenu:options.onShowMenu||defaults.onShowMenu,eventPosX:options.eventPosX||defaults.eventPosX,eventPosY:options.eventPosY||defaults.eventPosY});var index=hash.length-1;$(this).bind('contextmenu',function(e){var bShowContext=(!!hash[index].onContextMenu)?hash[index].onContextMenu(e):true;if(bShowContext){display(index,this,e,options);return false;}});return this;};function GetScrollTop(){var ScrollTop=document.body.scrollTop;if(ScrollTop==0){if(window.pageYOffset)
ScrollTop=window.pageYOffset;else
ScrollTop=(document.body.parentElement)?document.body.parentElement.scrollTop:0;}
return ScrollTop;}
function GetScrollLeft(){var ScrollLeft=document.body.scrollLeft;if(ScrollLeft==0){if(window.pageXOffset)
ScrollLeft=window.pageXOffset;else
ScrollLeft=(document.body.parentElement)?document.body.parentElement.scrollLeft:0;}
return ScrollLeft;}
function WindowWidth(){if(window.innerWidth!==undefined)
return window.innerWidth;else{var D=(document.body.clientWidth)?document.body:document.documentElement;return D.clientWidth;}}
function WindowHeight(){if(window.innerHeight!==undefined)
return window.innerHeight;else{var D=(document.body.clientHeight)?document.body:document.documentElement;return D.clientHeight;}}
function display(index,trigger,e,options){var cur=hash[index];content=$('#'+cur.id).find('ul:first').clone(true);content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(function(){$(this).css(cur.itemHoverStyle);},function(){$(this).css(cur.itemStyle);}).find('img').css({verticalAlign:'-19%',paddingRight:'4px'});menu.html(content);if(!!cur.onShowMenu)menu=cur.onShowMenu(e,menu);currentTarget={x:e.pageX,y:e.pageY};$.each(cur.bindings,function(id,func){$('#'+id,menu).bind('click',function(e){hide();func(trigger,currentTarget);});});menu.css({'left':'-10000px','top':'-10000px'}).show();var pos={x:e.pageX,y:e.pageY};var w=WindowWidth();var h=WindowHeight();var bottom=h+GetScrollTop();var right=w+GetScrollLeft();var margin=2;if(pos.x>right-menu.width()-margin*2&&pos.x>menu.width())
menu.css({'left':(pos.x-menu.width()-margin)+'px'});else
menu.css({'left':(pos.x+margin)+'px'});if(pos.y>bottom-menu.height()-margin*2&&pos.y>menu.height())
menu.css({'top':(pos.y-menu.height()-margin)+'px'});else
menu.css({'top':(pos.y+margin)+'px'});if(cur.shadow)shadow.css({width:menu.width(),height:menu.height(),left:menu.offset().left+2,top:menu.offset().top+2}).show();$(document).one('mousedown',function(e){var x=e.pageX;var y=e.pageY;var offset=menu.offset();var w=menu.width();var h=menu.height();if(x>offset.left&&x<offset.left+w&&y>offset.top&&y<offset.top+h){}
else{hide();}});}
function hide(){menu.hide();shadow.hide();}
$.contextMenu={defaults:function(userDefaults){$.each(userDefaults,function(i,val){if(typeof val=='object'&&defaults[i]){$.extend(defaults[i],val);}
else defaults[i]=val;});}};})(jQuery);$(function(){$('div.contextMenu').hide();});

;(function($){var helper={},current,title,tID,IE=$.browser.msie&&/MSIE\s(5\.5|6\.)/.test(navigator.userAgent),track=false;$.tooltip={blocked:false,defaults:{delay:200,fade:false,showURL:true,extraClass:"",top:15,left:15,id:"tooltip"},block:function(){$.tooltip.blocked=!$.tooltip.blocked;}};$.fn.extend({tooltip:function(settings){settings=$.extend({},$.tooltip.defaults,settings);createHelper(settings);return this.each(function(){$.data(this,"tooltip",settings);this.tOpacity=helper.parent.css("opacity");this.tooltipText=this.title;$(this).removeAttr("title");this.alt="";}).mouseover(save).mouseout(hide).click(hide);},fixPNG:IE?function(){return this.each(function(){var image=$(this).css('backgroundImage');if(image.match(/^url\(["']?(.*\.png)["']?\)$/i)){image=RegExp.$1;$(this).css({'backgroundImage':'none','filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+image+"')"}).each(function(){var position=$(this).css('position');if(position!='absolute'&&position!='relative')
$(this).css('position','relative');});}});}:function(){return this;},unfixPNG:IE?function(){return this.each(function(){$(this).css({'filter':'',backgroundImage:''});});}:function(){return this;},hideWhenEmpty:function(){return this.each(function(){$(this)[$(this).html()?"show":"hide"]();});},url:function(){return this.attr('href')||this.attr('src');}});function createHelper(settings){if(helper.parent)
return;helper.parent=$('<div id="'+settings.id+'"><h3></h3><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();if($.fn.bgiframe)
helper.parent.bgiframe();helper.title=$('h3',helper.parent);helper.body=$('div.body',helper.parent);helper.url=$('div.url',helper.parent);}
function settings(element){return $.data(element,"tooltip");}
function handle(event){if(settings(this).delay)
tID=setTimeout(show,settings(this).delay);else
show();track=!!settings(this).track;$(document.body).bind('mousemove',update);update(event);}
function save(){if($.tooltip.blocked||this==current||(!this.tooltipText&&!settings(this).bodyHandler))
return;current=this;title=this.tooltipText;if(settings(this).bodyHandler){helper.title.hide();var bodyContent=settings(this).bodyHandler.call(this);if(bodyContent.nodeType||bodyContent.jquery){helper.body.empty().append(bodyContent)}else{helper.body.html(bodyContent);}
helper.body.show();}else if(settings(this).showBody){var parts=title.split(settings(this).showBody);helper.title.html(parts.shift()).show();helper.body.empty();for(var i=0,part;(part=parts[i]);i++){if(i>0)
helper.body.append("<br/>");helper.body.append(part);}
helper.body.hideWhenEmpty();}else{helper.title.html(title).show();helper.body.hide();}
if(settings(this).showURL&&$(this).url())
helper.url.html($(this).url().replace('http://','')).show();else
helper.url.hide();helper.parent.addClass(settings(this).extraClass);if(settings(this).fixPNG)
helper.parent.fixPNG();handle.apply(this,arguments);}
function show(){tID=null;if((!IE||!$.fn.bgiframe)&&settings(current).fade){if(helper.parent.is(":animated"))
helper.parent.stop().show().fadeTo(settings(current).fade,current.tOpacity);else
helper.parent.is(':visible')?helper.parent.fadeTo(settings(current).fade,current.tOpacity):helper.parent.fadeIn(settings(current).fade);}else{helper.parent.show();}
update();}
function update(event){if($.tooltip.blocked)
return;if(event&&event.target.tagName=="OPTION"){return;}
if(!track&&helper.parent.is(":visible")){$(document.body).unbind('mousemove',update)}
if(current==null||settings(current)==null){helper.parent.hide();$(document.body).unbind('mousemove',update);return;}
helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");var left=helper.parent[0].offsetLeft;var top=helper.parent[0].offsetTop;if(event){left=event.pageX+settings(current).left;top=event.pageY+settings(current).top;var right='auto';if(settings(current).positionLeft){right=$(window).width()-left;left='auto';}
helper.parent.css({left:left,right:right,top:top});}
var v=viewport(),h=helper.parent[0];if(v.x+v.cx<h.offsetLeft+h.offsetWidth){left-=h.offsetWidth+20+settings(current).left;helper.parent.css({left:left+'px'}).addClass("viewport-right");}
if(v.y+v.cy<h.offsetTop+h.offsetHeight){top-=h.offsetHeight+20+settings(current).top;helper.parent.css({top:top+'px'}).addClass("viewport-bottom");}}
function viewport(){return{x:$(window).scrollLeft(),y:$(window).scrollTop(),cx:$(window).width(),cy:$(window).height()};}
function hide(event){if($.tooltip.blocked)
return;if(tID)
clearTimeout(tID);current=null;var tsettings=settings(this);function complete(){helper.parent.removeClass(tsettings.extraClass).hide().css("opacity","");}
if((!IE||!$.fn.bgiframe)&&tsettings.fade){if(helper.parent.is(':animated'))
helper.parent.stop().fadeTo(tsettings.fade,0,complete);else
helper.parent.stop().fadeOut(tsettings.fade,complete);}else
complete();if(settings(this).fixPNG)
helper.parent.unfixPNG();}})(jQuery);


(function($){$.jGrowl=function(m,o){if($('#jGrowl').size()==0){$('<div id="jGrowl"></div>').addClass($.jGrowl.defaults.position).appendTo('body');setInterval(function(){var offset=$('#viewport').offset();var width=$('#viewport').get(0).clientWidth;var height=$('#viewport').get(0).clientHeight;$('#jGrowl').css({bottom:(WindowHeight()-(offset.top+height))+'px',right:(WindowWidth()-(offset.left+width))+'px'});},100);}
$('#jGrowl').jGrowl(m,o);};$.fn.jGrowl=function(m,o){if($.isFunction(this.each)){var args=arguments;return this.each(function(){var self=this;if($(this).data('jGrowl.instance')==undefined){$(this).data('jGrowl.instance',new $.fn.jGrowl());$(this).data('jGrowl.instance').startup(this);}
if($.isFunction($(this).data('jGrowl.instance')[m])){$(this).data('jGrowl.instance')[m].apply($(this).data('jGrowl.instance'),$.makeArray(args).slice(1));}else{$(this).data('jGrowl.instance').notification(m,o);}});};};$.extend($.fn.jGrowl.prototype,{defaults:{header:'',sticky:false,position:'bottom-right',glue:'after',theme:'default',corners:'10px',check:500,life:3000,speed:'normal',easing:'swing',closer:false,closeTemplate:'&times;',closerTemplate:'<div>[ close all ]</div>',log:function(e,m,o){},beforeOpen:function(e,m,o){},open:function(e,m,o){},beforeClose:function(e,m,o){},close:function(e,m,o){},animateOpen:{opacity:'show'},animateClose:{opacity:'hide'}},element:null,interval:null,notification:function(message,o){var self=this;var o=$.extend({},this.defaults,o);o.log.apply(this.element,[this.element,message,o]);var notification=$('<div class="jGrowl-notification"><div class="close">'+o.closeTemplate+'</div><div class="header">'+o.header+'</div><div class="message">'+message+'</div></div>').data("jGrowl",o).addClass(o.theme).children('div.close').bind("click.jGrowl",function(){$(this).unbind('click.jGrowl').parent().trigger('jGrowl.beforeClose').animate(o.animateClose,o.speed,o.easing,function(){$(this).trigger('jGrowl.close').remove();});}).parent();(o.glue=='after')?$('div.jGrowl-notification:last',this.element).after(notification):$('div.jGrowl-notification:first',this.element).before(notification);$(notification).bind("mouseover.jGrowl",function(){$(this).data("jGrowl").pause=true;}).bind("mouseout.jGrowl",function(){$(this).data("jGrowl").pause=false;}).bind('jGrowl.beforeOpen',function(){o.beforeOpen.apply(self.element,[self.element,message,o]);}).bind('jGrowl.open',function(){o.open.apply(self.element,[self.element,message,o]);}).bind('jGrowl.beforeClose',function(){o.beforeClose.apply(self.element,[self.element,message,o]);}).bind('jGrowl.close',function(){o.close.apply(self.element,[self.element,message,o]);}).trigger('jGrowl.beforeOpen').animate(o.animateOpen,o.speed,o.easing,function(){$(this).data("jGrowl").created=new Date();}).trigger('jGrowl.open').addClass('ui-widget ui-state-default ui-corner-all');if($.fn.corner!=undefined)$(notification).corner(o.corners);if($('div.jGrowl-notification:parent',this.element).size()>1&&$('div.jGrowl-closer',this.element).size()==0&&this.defaults.closer!=false){$(this.defaults.closerTemplate).addClass('jGrowl-closer').addClass(this.defaults.theme).appendTo(this.element).animate(this.defaults.animateOpen,this.defaults.speed,this.defaults.easing).bind("click.jGrowl",function(){$(this).siblings().children('div.close').trigger("click.jGrowl");if($.isFunction(self.defaults.closer))self.defaults.closer.apply($(this).parent()[0],[$(this).parent()[0]]);});};},update:function(){$(this.element).find('div.jGrowl-notification:parent').each(function(){if($(this).data("jGrowl")!=undefined&&$(this).data("jGrowl").created!=undefined&&($(this).data("jGrowl").created.getTime()+$(this).data("jGrowl").life)<(new Date()).getTime()&&$(this).data("jGrowl").sticky!=true&&($(this).data("jGrowl").pause==undefined||$(this).data("jGrowl").pause!=true)){$(this).children('div.close').trigger('click.jGrowl');}});if($(this.element).find('div.jGrowl-notification:parent').size()<2){$(this.element).find('div.jGrowl-closer').animate(this.defaults.animateClose,this.defaults.speed,this.defaults.easing,function(){$(this).remove();});};},startup:function(e){this.element=$(e).addClass('jGrowl').append('<div class="jGrowl-notification"></div>');this.interval=setInterval(function(){jQuery(e).data('jGrowl.instance').update();},this.defaults.check);if($.browser.msie&&parseInt($.browser.version)<7&&!window["XMLHttpRequest"])$(this.element).addClass('ie6');},shutdown:function(){$(this.element).removeClass('jGrowl').find('div.jGrowl-notification').remove();clearInterval(this.interval);}});$.jGrowl.defaults=$.fn.jGrowl.prototype.defaults;})(jQuery);


jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{path:'/',expires:365};if(value===null){value='';options.expires=-1;}
var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}
expires='; expires='+date.toUTCString();}
var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}
return cookieValue;}};


$.popupMenu=function(o){o.css=$.extend({},$.popupMenu.defaults.css,o.css);var options=$.extend({},$.popupMenu.defaults,o);if($.popupMenu.div==null){$.popupMenu.div=$('<div></div>');$(document).mousedown(function(e){var offset=$.popupMenu.div.offset();var width=$.popupMenu.div.width();var height=$.popupMenu.div.height();if(e.pageX<offset.left||e.pageY<offset.top||e.pageX>offset.left+width||e.pageY>offset.top+height)
$.popupMenu.hide();});}
var div=$.popupMenu.div;function GetScrollTop(){var ScrollTop=document.body.scrollTop;if(ScrollTop==0){if(window.pageYOffset)
ScrollTop=window.pageYOffset;else
ScrollTop=(document.body.parentElement)?document.body.parentElement.scrollTop:0;}
return ScrollTop;}
function GetScrollLeft(){var ScrollLeft=document.body.scrollLeft;if(ScrollLeft==0){if(window.pageXOffset)
ScrollLeft=window.pageXOffset;else
ScrollLeft=(document.body.parentElement)?document.body.parentElement.scrollLeft:0;}
return ScrollLeft;}
function WindowWidth(){if(window.innerWidth!==undefined)
return window.innerWidth;else{var D=(document.body.clientWidth)?document.body:document.documentElement;return D.clientWidth;}}
function WindowHeight(){if(window.innerHeight!==undefined)
return window.innerHeight;else{var D=(document.body.clientHeight)?document.body:document.documentElement;return D.clientHeight;}}
div.css({position:'absolute'}).css(options.css);div.css({'left':'-10000px','top':'-10000px'});div.html(options.content);$('body').append(div);var w=WindowWidth();var h=WindowHeight();var bottom=h+GetScrollTop();var right=w+GetScrollLeft();var margin=2;if(options.x>right-div.width()-margin*2&&options.x>div.width())
div.css({'left':(options.x-div.width()-margin)+'px'});else
div.css({'left':(options.x+margin)+'px'});if(options.y>bottom-div.height()-margin*2&&options.y>div.height())
div.css({'top':(options.y-div.height()-margin)+'px'});else
div.css({'top':(options.y+margin)+'px'});return div;}
$.popupMenu.hide=function(){if($.popupMenu.div!=null)
$.popupMenu.div.remove();}
$.popupMenu.defaults={x:0,y:0,css:{border:'1px solid #aaaaaa',background:'white',width:'100px',height:'300px'},content:'Hello world'};


if(!this.JSON){JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapeable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapeable.lastIndex=0;return escapeable.test(string)?'"'+string.replace(escapeable,function(a){var c=meta[a];if(typeof c==='string'){return c;}
return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(typeof value.length==='number'&&!value.propertyIsEnumerable('length')){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}})();


var ImageDomain=document.domain;ImageDomain=document.location.protocol+'//'+ImageDomain;function ShowVideo(name,title){jqAlert('<div id="media" style="width:640px;height:485px;"><div id="noUpdate"><p>You do not need Flash to use '+Configure.product+', but you need a more current version of Flash to view this video.</p></div></div>',title,{},630);var s1=new SWFObject("/video/player.swf","ply","640","480","9","#1a1a1a");s1.addParam("quality","best");s1.addParam("allowfullscreen","true");s1.addParam("allowscriptaccess","always");s1.addParam("flashvars","file="+encodeURIComponent("http://lucidchart.s3.amazonaws.com/video/"+name)+"&autostart=true");s1.write("media");$('#media').css({display:'block'});$('.dialog').css({background:'#1a1a1a'});}
$(function(){$('a[video]').each(function(){$(this).attr('href','javascript:ShowVideo("'+$(this).attr('video')+'");');});});var agt=navigator.userAgent.toLowerCase();var is_major=parseInt(navigator.appVersion);var is_minor=parseFloat(navigator.appVersion);var is_nav=((agt.indexOf('mozilla')!=-1)&&(agt.indexOf('spoofer')==-1)&&(agt.indexOf('compatible')==-1)&&(agt.indexOf('opera')==-1)&&(agt.indexOf('webtv')==-1));var is_nav2=(is_nav&&(is_major==2));var is_nav3=(is_nav&&(is_major==3));var is_nav4=(is_nav&&(is_major==4));var is_nav4up=(is_nav&&(is_major>=4));var is_navonly=(is_nav&&((agt.indexOf(";nav")!=-1)||(agt.indexOf("; nav")!=-1)));var is_nav5=(is_nav&&(is_major==5));var is_nav5up=(is_nav&&(is_major>=5));var is_ie=(agt.indexOf("msie")!=-1);var is_ie3=(is_ie&&(is_major<4));var is_ie4=(is_ie&&(is_major==4)&&(agt.indexOf("msie 5.0")==-1));var is_ie4up=(is_ie&&(is_major>=4));var is_ie5=(is_ie&&(is_major==4)&&(agt.indexOf("msie 5.0")!=-1));var is_ie5up=(is_ie&&!is_ie3&&!is_ie4);var is_ie6=(is_ie&&(is_major==4)&&(agt.indexOf("msie 6.")!=-1));var is_ie7=(is_ie&&(is_major==4)&&(agt.indexOf("msie 7.")!=-1));var is_safari=navigator.appVersion.search('Safari')!=-1&&navigator.appVersion.search('Chrome')==-1;var is_chrome=navigator.appVersion.search('Chrome')!=-1;var is_aol=(agt.indexOf("aol")!=-1);var is_aol3=(is_aol&&is_ie3);var is_aol4=(is_aol&&is_ie4);var is_opera=(agt.indexOf("opera")!=-1);var is_webtv=(agt.indexOf("webtv")!=-1);var is_firefox=/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent);var is_js;if(is_nav2||is_ie3)is_js=1.0
else if(is_nav3||is_opera)is_js=1.1
else if((is_nav4&&(is_minor<=4.05))||is_ie4)is_js=1.2
else if((is_nav4&&(is_minor>4.05))||is_ie5)is_js=1.3
else if(is_nav5)is_js=1.4
else if(is_nav&&(is_major>5))is_js=1.4
else if(is_ie&&(is_major>5))is_js=1.3
else is_js=0.0;var is_win=((agt.indexOf("win")!=-1)||(agt.indexOf("16bit")!=-1));var is_win95=((agt.indexOf("win95")!=-1)||(agt.indexOf("windows 95")!=-1));var is_win16=((agt.indexOf("win16")!=-1)||(agt.indexOf("16bit")!=-1)||(agt.indexOf("windows 3.1")!=-1)||(agt.indexOf("windows 16-bit")!=-1));var is_win31=((agt.indexOf("windows 3.1")!=-1)||(agt.indexOf("win16")!=-1)||(agt.indexOf("windows 16-bit")!=-1));var is_win98=((agt.indexOf("win98")!=-1)||(agt.indexOf("windows 98")!=-1));var is_winnt=((agt.indexOf("winnt")!=-1)||(agt.indexOf("windows nt")!=-1));var is_win32=(is_win95||is_winnt||is_win98||((is_major>=4)&&(navigator.platform=="Win32"))||(agt.indexOf("win32")!=-1)||(agt.indexOf("32bit")!=-1));var is_os2=((agt.indexOf("os/2")!=-1)||(navigator.appVersion.indexOf("OS/2")!=-1)||(agt.indexOf("ibm-webexplorer")!=-1));var is_mac=(agt.indexOf("mac")!=-1);var is_mac68k=(is_mac&&((agt.indexOf("68k")!=-1)||(agt.indexOf("68000")!=-1)));var is_macppc=(is_mac&&((agt.indexOf("ppc")!=-1)||(agt.indexOf("powerpc")!=-1)));var is_sun=(agt.indexOf("sunos")!=-1);var is_sun4=(agt.indexOf("sunos 4")!=-1);var is_sun5=(agt.indexOf("sunos 5")!=-1);var is_suni86=(is_sun&&(agt.indexOf("i86")!=-1));var is_irix=(agt.indexOf("irix")!=-1);var is_irix5=(agt.indexOf("irix 5")!=-1);var is_irix6=((agt.indexOf("irix 6")!=-1)||(agt.indexOf("irix6")!=-1));var is_hpux=(agt.indexOf("hp-ux")!=-1);var is_hpux9=(is_hpux&&(agt.indexOf("09.")!=-1));var is_hpux10=(is_hpux&&(agt.indexOf("10.")!=-1));var is_aix=(agt.indexOf("aix")!=-1);var is_aix1=(agt.indexOf("aix 1")!=-1);var is_aix2=(agt.indexOf("aix 2")!=-1);var is_aix3=(agt.indexOf("aix 3")!=-1);var is_aix4=(agt.indexOf("aix 4")!=-1);var is_linux=(agt.indexOf("inux")!=-1);var is_sco=(agt.indexOf("sco")!=-1)||(agt.indexOf("unix_sv")!=-1);var is_unixware=(agt.indexOf("unix_system_v")!=-1);var is_mpras=(agt.indexOf("ncr")!=-1);var is_reliant=(agt.indexOf("reliantunix")!=-1);var is_dec=((agt.indexOf("dec")!=-1)||(agt.indexOf("osf1")!=-1)||(agt.indexOf("dec_alpha")!=-1)||(agt.indexOf("alphaserver")!=-1)||(agt.indexOf("ultrix")!=-1)||(agt.indexOf("alphastation")!=-1));var is_sinix=(agt.indexOf("sinix")!=-1);var is_freebsd=(agt.indexOf("freebsd")!=-1);var is_bsd=(agt.indexOf("bsd")!=-1);var is_unix=((agt.indexOf("x11")!=-1)||is_sun||is_irix||is_hpux||is_sco||is_unixware||is_mpras||is_reliant||is_dec||is_sinix||is_aix||is_linux||is_bsd||is_freebsd);var is_vms=((agt.indexOf("vax")!=-1)||(agt.indexOf("openvms")!=-1));var left_button=is_ie?1:0;var right_button=2;function CallerFn(f,me){return function(){f.call(me);}}
function GetFormQueryString(FormFilter){var qs='';$(FormFilter).find(":enabled:input[name][type!=submit][type!=checkbox][type!=radio]").each(function(){qs+=(qs==''?'':'&');qs+=encodeURIComponent(this.name)+'='+encodeURIComponent(this.value);});$(FormFilter).find(":enabled:checked[name]").each(function(){qs+=(qs==''?'':'&');qs+=encodeURIComponent(this.name)+'='+encodeURIComponent(this.value);});return qs;}
function jqForm(url,done,ondialog,beforeSubmit,filter,urlIsSource,onclose){if(filter==null)
filter='form';function MakeDialog(msg){msg=$('<div>'+msg+'</div>');var form=msg.find(filter).get(0);var html=$(form).html();$('body').append("<div id='jqFormSizeChecker' style='width:10000px;position:absolute;left:-100000px;'><div id='jqFormSizeCheckerFloat' style='float:left;'>"+html+"</div></div>");var width=jqWidth('#jqFormSizeCheckerFloat');$('#jqFormSizeChecker').remove();var dlg=jqAlert(html,null,{},width,null,onclose);dlg.find('a').attr('target','_blank');dlg.find('input:visible:first').focus();dlg.find('input[type=submit]').click(function(){if(beforeSubmit&&beforeSubmit(dlg)==false)
return false;dlg.block({message:null});$.ajax({type:form.method,url:form.action,data:GetFormQueryString(dlg),success:function(resultmsg){resultmsgdom=$('<div>'+resultmsg+'</div>');if(resultmsgdom.find('.error-message').size()>0){jqForm(resultmsg,done,ondialog,beforeSubmit,filter,true);}
else{if(done)
done();}},error:function(){jqAlert('Error submitting form.  Please try again.');},complete:function(){dlg.dialog('close');}});});if(ondialog)
ondialog(dlg);}
if(urlIsSource)
MakeDialog(url);else{$.ajax({type:'GET',url:url+'?NoSSLChange=true',success:MakeDialog,error:function(){jqForm(url,done,ondialog,beforeSubmit,filter,urlIsSource);}});}}
function jqPrompt(msg,val,fn,title,width){var dlg=jqAlert('<p>'+msg+'</p><input type="text" id="jqPromptInput"/>',title,{OK:function(){fn(val);},Cancel:function(){}},width);var w=dlg.width();if(is_ie)
w-=40;$('#jqPromptInput').val(val).bind('keydown keyup change',function(){val=$('#jqPromptInput').val();}).bind('keydown',function(e){if(e.which==13||e.keyCode==13)
dlg.parent().find('button').eq(0).click();}).focus().select().css({width:w+'px'});}
function jqConfirm(ButtonFilter,msg,OkLabel,okf){$(ButtonFilter).each(function(){var TheButton=$(this);var OkFunction=okf;if(OkLabel==null)
OkLabel='Ok';if(OkFunction==null){OkFunction=function(){if(TheButton.attr('href')==null)
TheButton.click();else
window.location=TheButton.attr('href');}}
TheButton.bind('click',function(){if(TheButton.attr('IsConfirmed')=='1')
return true;buttons={};buttons[OkLabel]=function(){TheButton.attr('IsConfirmed','1');OkFunction();TheButton.attr('IsConfirmed','0');};buttons['Cancel']=function(){};jqAlert(msg,null,buttons);return false;});});}
function jqAlert(msg,title,buttons,width,runfnbefore,onclose){if(msg==null){jqAlert('null');}
var id='jqalertbox_'+Math.floor(Math.random()*100000000);if(title==null)
title=Configure.product;if(buttons==null){buttons={Ok:function(){}};}
for(var b in buttons){buttons[b]=function(old){return function(){if(runfnbefore){if(old()==false)
return;}
$('#'+id).dialog('close');if(!runfnbefore)
old();}}(buttons[b]);}
if(width==null)
width=300;if(msg.indexOf('<')==-1)
msg='<p>'+msg+'</p>';$('body').append('<div id="'+id+'" title="'+title+'">'+msg+'</div>');$('#'+id).dialog({buttons:buttons,modal:true,width:width+50,close:function(){$('#'+id).dialog('destroy');$('#'+id).remove();if(onclose)
onclose();},resizable:false});return $('#'+id);}
function WindowWidth(){if(window.innerWidth!==undefined)
return window.innerWidth;else{var D=(document.documentElement.clientWidth)?document.documentElement:document.body;return D.clientWidth;}}
function WindowHeight(){if(window.innerHeight!==undefined)
return window.innerHeight;else{var D=(document.documentElement.clientHeight)?document.documentElement:document.body;return D.clientHeight;}}
function RoundAll(dupeObj,level){if(dupeObj==null)
return null;if(level==null)
level=0;if(level>100)
return null;if(typeof(dupeObj)=='object'){for(var objInd in dupeObj){var type=typeof(dupeObj[objInd]);if(type=='object'){RoundAll(dupeObj[objInd],level+1);}else if(type=='number'){dupeObj[objInd]=Math.round(dupeObj[objInd]*100)/100;}}}}
function CopyObject(dupeObj,level){if(dupeObj==null)
return null;if(level==null)
level=0;if(level>100){return null;}
var retObj=new Object();if(typeof(dupeObj)=='object'){if(typeof(dupeObj.length)!='undefined')
var retObj=new Array();for(var objInd in dupeObj){var type=typeof(dupeObj[objInd]);if(type=='object'){retObj[objInd]=CopyObject(dupeObj[objInd],level+1);}else if(type=='string'){retObj[objInd]=dupeObj[objInd];}else if(type=='number'){retObj[objInd]=dupeObj[objInd];}else if(type=='boolean'){((dupeObj[objInd]==true)?retObj[objInd]=true:retObj[objInd]=false);}}}
return retObj;}
function IsArray(o){return typeof(o)=='object'&&typeof(o.length)!='undefined';}
function ObjectSize(o){var ret=0;for(var k in o){if(o.hasOwnProperty(k))
ret++;}
return ret;}
function jqWidth(f){if($(f).size()==0)
return 0;return $(f).get(0).offsetWidth;}
function jqHeight(f){if($(f).size()==0)
return 0;return $(f).get(0).offsetHeight;}
function jqClientWidth(f){if($(f).size()==0)
return 0;return $(f).get(0).clientWidth;}
function jqClientHeight(f){if($(f).size()==0)
return 0;return $(f).get(0).clientHeight;}
function SetupLayout(LayoutSettings,Area){if(Area==null){if(is_firefox&&is_mac){SetupLayout(LayoutSettings,{x:0,y:0,w:Math.max(400,WindowWidth())-40,h:Math.max(400,WindowHeight())-40});}
SetupLayout(LayoutSettings,{x:0,y:0,w:Math.max(400,WindowWidth()),h:Math.max(400,WindowHeight())});return;}
for(var i=0;i<LayoutSettings.length;i++){var item=LayoutSettings[i];var rect=CopyObject(Area);if(item.wd)rect.w+=item.wd;if(item.hd)rect.h+=item.hd;if(item.Dock=='top'){if(item.Size==null&&item.DOM!=null){if(item.AutoSize!=false)$(item.DOM).css({'height':'auto'});item.Size=jqHeight(item.DOM);}
rect.h=item.Size;Area.y+=item.Size;Area.h-=item.Size;if(item.w)rect.w=item.w;}
else if(item.Dock=='left'){if(item.Size==null&&item.DOM!=null){if(item.AutoSize!=false)$(item.DOM).css({'width':'auto'});item.Size=jqWidth(item.DOM);}
rect.w=item.Size;Area.x+=item.Size;Area.w-=item.Size;if(item.h)rect.h=item.h;if(item.Align=='bottom'){if(!is_ie6){if(item.h==null)item.h=jqHeight(item.DOM);rect.y+=rect.h-item.h;rect.h=item.h;}}}
else if(item.Dock=='right'){if(item.Size==null&&item.DOM!=null){if(item.AutoSize!=false)$(item.DOM).css({'width':'auto'});item.Size=jqWidth(item.DOM);}
rect.w=item.Size;Area.w-=item.Size;rect.x=Area.x+Area.w;if(item.h)rect.h=item.h;if(item.Align=='bottom'){if(!is_ie6){if(item.h==null)item.h=jqHeight(item.DOM);rect.y+=rect.h-item.h;rect.h=item.h;}}}
else if(item.Dock=='bottom'){if(item.Size==null&&item.DOM!=null){if(item.AutoSize!=false)$(item.DOM).css({'height':'auto'});item.Size=jqHeight(item.DOM);}
rect.h=item.Size;Area.h-=item.Size;rect.y=Area.y+Area.h;if(item.w)rect.w=item.w;}
if(item.DOM){if(item.DOM!=null){rect.w-=jqWidth(item.DOM)-$(item.DOM).width();rect.h-=jqHeight(item.DOM)-$(item.DOM).height();}
$(item.DOM).css({position:'absolute',left:rect.x+'px',top:rect.y+'px',width:rect.w+'px',height:rect.h+'px'});}
if(item.Children)
SetupLayout(item.Children,rect);}}
function ProjectPointOntoRay(p,p1,n){var u=n;var v={x:p.x-p1.x,y:p.y-p1.y};var c=(u.x*v.x+u.y*v.y)/(u.x*u.x+u.y*u.y);var project={x:c*u.x,y:c*u.y};return{x:project.x+p1.x,y:project.y+p1.y};}
function DistanceFromLineSegment(cx,cy,ax,ay,bx,by){var r_numerator=(cx-ax)*(bx-ax)+(cy-ay)*(by-ay);var r_denomenator=(bx-ax)*(bx-ax)+(by-ay)*(by-ay);var r=r_numerator/r_denomenator;var px=ax+r*(bx-ax);var py=ay+r*(by-ay);var s=((ay-cy)*(bx-ax)-(ax-cx)*(by-ay))/r_denomenator;var distanceLine=Math.abs(s)*Math.sqrt(r_denomenator);var distanceSegment;var xx=px;var yy=py;if((r>=0)&&(r<=1)){distanceSegment=distanceLine;}
else{var dist1=(cx-ax)*(cx-ax)+(cy-ay)*(cy-ay);var dist2=(cx-bx)*(cx-bx)+(cy-by)*(cy-by);if(dist1<dist2){xx=ax;yy=ay;distanceSegment=Math.sqrt(dist1);}
else{xx=bx;yy=by;distanceSegment=Math.sqrt(dist2);}}
return distanceSegment;}
function ClosestPointOnLineSegment(cx,cy,ax,ay,bx,by,infinite){var r_numerator=(cx-ax)*(bx-ax)+(cy-ay)*(by-ay);var r_denomenator=(bx-ax)*(bx-ax)+(by-ay)*(by-ay);var r=r_numerator/r_denomenator;var s=((ay-cy)*(bx-ax)-(ax-cx)*(by-ay))/r_denomenator;if(infinite||((r>=0)&&(r<=1))){return{x:ax+r*(bx-ax),y:ay+r*(by-ay),d:Math.abs(s)*Math.sqrt(r_denomenator),t:r};}
else{var dist1=(cx-ax)*(cx-ax)+(cy-ay)*(cy-ay);var dist2=(cx-bx)*(cx-bx)+(cy-by)*(cy-by);if(dist1<dist2)
return{x:ax,y:ay,d:Math.sqrt(dist1),t:0};else
return{x:bx,y:by,d:Math.sqrt(dist2),t:1};}}
function LineIntersectsRectangle(lx1,ly1,lx2,ly2,rx1,ry1,rx2,ry2){if(lx1<rx1&&lx2<rx1)
return false;if(ly1<ry1&&ly2<ry1)
return false;if(lx1>rx2&&lx2>rx2)
return false;if(ly1>ry2&&ly2>ry2)
return false;if(lx1>=rx1&&lx1<=rx2&&ly1>=ry1&&ly1<=ry2&&lx2>=rx1&&lx2<=rx2&&ly2>=ry1&&ly2<=ry2)
return true;if(LinesIntersect({x:lx1,y:ly1},{x:lx2,y:ly2},{x:rx1,y:ry1},{x:rx2,y:ry1}))
return true;if(LinesIntersect({x:lx1,y:ly1},{x:lx2,y:ly2},{x:rx2,y:ry1},{x:rx2,y:ry2}))
return true;if(LinesIntersect({x:lx1,y:ly1},{x:lx2,y:ly2},{x:rx2,y:ry2},{x:rx1,y:ry2}))
return true;if(LinesIntersect({x:lx1,y:ly1},{x:lx2,y:ly2},{x:rx1,y:ry2},{x:rx1,y:ry1}))
return true;return false;}
function LinesIntersect(a1,a2,b1,b2){if(Math.max(a1.y,a2.y)<Math.min(b1.y,b2.y))
return false;if(Math.min(a1.y,a2.y)>Math.max(b1.y,b2.y))
return false;if(Math.max(a1.x,a2.x)<Math.min(b1.x,b2.x))
return false;if(Math.min(a1.x,a2.x)>Math.max(b1.x,b2.x))
return false;var ua_t=(b2.x-b1.x)*(a1.y-b1.y)-(b2.y-b1.y)*(a1.x-b1.x);var ub_t=(a2.x-a1.x)*(a1.y-b1.y)-(a2.y-a1.y)*(a1.x-b1.x);var u_b=(b2.y-b1.y)*(a2.x-a1.x)-(b2.x-b1.x)*(a2.y-a1.y);if(u_b!=0){var ua=ua_t/u_b;var ub=ub_t/u_b;if(0<=ua&&ua<=1&&0<=ub&&ub<=1){return{x:a1.x+ua*(a2.x-a1.x),y:a1.y+ua*(a2.y-a1.y),t:ua};}else{return false;}}else{if(ua_t==0||ub_t==0){return true;}else{return false;}}};function RaysIntersection(a1,n1,b1,n2){var a2={x:a1.x+n1.x,y:a1.y+n1.y};var b2={x:b1.x+n2.x,y:b1.y+n2.y};var ua_t=(b2.x-b1.x)*(a1.y-b1.y)-(b2.y-b1.y)*(a1.x-b1.x);var ub_t=(a2.x-a1.x)*(a1.y-b1.y)-(a2.y-a1.y)*(a1.x-b1.x);var u_b=(b2.y-b1.y)*(a2.x-a1.x)-(b2.x-b1.x)*(a2.y-a1.y);if(u_b!=0){var ua=ua_t/u_b;var ub=ub_t/u_b;if(0<=ua&&0<=ub){return{x:a1.x+n1.x*ua,y:a1.y+n1.y*ua};}else{return false;}}else{if(ua_t==0||ub_t==0){return a1;}else{return false;}}};function calculateSplinePoints(cp,numPointsFunc){var ret=[];function calculateSplineSegment(p1,p2,p3,p4){function AddPoint(t){ret.push({x:(1-t)*(1-t)*(1-t)*p1.x+3*(1-t)*(1-t)*t*p2.x+3*(1-t)*t*t*p3.x+t*t*t*p4.x,y:(1-t)*(1-t)*(1-t)*p1.y+3*(1-t)*(1-t)*t*p2.y+3*(1-t)*t*t*p3.y+t*t*t*p4.y});}
var dx=p4.x-p1.x;var dy=p4.y-p1.y;var NumPoints=numPointsFunc(Math.sqrt(dx*dx+dy*dy));for(var t=0;t<1;t+=1/NumPoints)
AddPoint(t);}
for(var i=0;i<cp.length-1;i++){calculateSplineSegment(cp[i],{x:cp[i].x+cp[i].nx,y:cp[i].y+cp[i].ny},{x:cp[i+1].x-cp[i+1].nx,y:cp[i+1].y-cp[i+1].ny},cp[i+1]);}
ret.push({x:cp[i].x,y:cp[i].y});return ret;}
function findSplineSlope(x,y,p1,p2,p3,p4){var minDistSq=99999999;var finalT=0;for(var t=0;t<1;t+=0.001){var lx=(1-t)*(1-t)*(1-t)*p1.x+3*(1-t)*(1-t)*t*p2.x+3*(1-t)*t*t*p3.x+t*t*t*p4.x;var ly=(1-t)*(1-t)*(1-t)*p1.y+3*(1-t)*(1-t)*t*p2.y+3*(1-t)*t*t*p3.y+t*t*t*p4.y;var dx=x-lx;var dy=y-ly;var distSq=dx*dx+dy*dy;if(distSq<minDistSq){finalT=t;minDistSq=distSq;}}
t=finalT;return{x:(-3*(1-t)*(1-t)*p1.x+3*(1-t)*(1-t)*p2.x-6*p2.x*t*(1-t)-3*p3.x*t*t+6*p3.x*t*(1-t)+3*p4.x*t*t)/6,y:(-3*(1-t)*(1-t)*p1.y+3*(1-t)*(1-t)*p2.y-6*p2.y*t*(1-t)-3*p3.y*t*t+6*p3.y*t*(1-t)+3*p4.y*t*t)/6};}
function EllipseArcControlPoints(x,y,w,h,s,e,IncludeInitialMove){if(s==null)s=0;if(e==null)e=Math.PI*2;var Reverse=false;if(s>e){Reverse=true;var temp=s;s=e;e=temp;}
var xr=w/2;var yr=h/2;var k=0.5522847498;var PointAt=function(t){return{t:t,x:x+xr+Math.cos(t)*xr,y:y+yr+Math.sin(t)*yr,xt:function(k){return x+xr+xr*(Math.cos(t)-k*Math.sin(t));},yt:function(k){return y+yr+yr*(Math.sin(t)+k*Math.cos(t));},xt2:function(k){return x+xr+xr*(Math.cos(t)-(-k*Math.sin(t)));},yt2:function(k){return y+yr+yr*(Math.sin(t)+-k*Math.cos(t));}};}
var points=[];for(var t=s;t<e;t+=Math.PI*0.5)
points.push(PointAt(t));points.push(PointAt(e));var ret=[];if(IncludeInitialMove)
ret.push({x:x+xr+Math.cos(Reverse?e:s)*xr,y:y+yr+Math.sin(Reverse?e:s)*yr});if(Reverse)
points.reverse();for(var i=0;i<points.length-1;i++){var kval=k*(points[i+1].t-points[i].t)/(Math.PI/2);ret.push({x1:points[i].xt(kval),y1:points[i].yt(kval),x2:points[i+1].xt2(kval),y2:points[i+1].yt2(kval),x3:points[i+1].x,y3:points[i+1].y});}
return ret;}
function setTimeoutFunction(f,timeout){var handle=setInterval(function(){clearInterval(handle);f();},timeout);}
function arrayIndexOf(a,e){for(var idx in a){if(a[idx]==e)
return idx;}
return-1;}
function trim(s){if(s==null)return'';return s.replace(/^\s+|\s+$/g,'');}
function ltrim(s){if(s==null)return'';return s.replace(/^\s+/g,'');}
function EventInElement(e,el){var x=e.pageX;var y=e.pageY;var offset=$(el).offset();return(x>=offset.left&&x<=offset.left+jqWidth(el)&&y>=offset.top&&y<=offset.top+jqHeight(el));}
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=Utf8.encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}
output=output+
this._keyStr.charAt(enc1)+this._keyStr.charAt(enc2)+
this._keyStr.charAt(enc3)+this._keyStr.charAt(enc4);}
return output;},decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2);}
if(enc4!=64){output=output+String.fromCharCode(chr3);}}
output=Utf8.decode(output);return output;}}
function lzw_encode(s){s=Utf8.encode(s);var dict={};var data=(s+"").split("");var out=[];var currChar;var phrase=data[0];var code=256;var phrase2;for(var i=1;i<data.length;i++){currChar=data[i];phrase2=phrase+currChar;if(dict[phrase2]!=null){phrase=phrase2;}
else{out.push(phrase.length>1?dict[phrase]:phrase.charCodeAt(0));dict[phrase2]=code;code++;phrase=currChar;}}
out.push(phrase.length>1?dict[phrase]:phrase.charCodeAt(0));for(var i=0;i<out.length;i++){out[i]=String.fromCharCode(out[i]);}
return out.join("");}
function lzw_decode(s){var dict={};var data=(s+"").split("");var currChar=data[0];var oldPhrase=currChar;var out=[currChar];var code=256;var phrase;for(var i=1;i<data.length;i++){var currCode=data[i].charCodeAt(0);if(currCode<256){phrase=data[i];}
else{phrase=dict[currCode]?dict[currCode]:(oldPhrase+currChar);}
out.push(phrase);currChar=phrase.charAt(0);dict[code]=oldPhrase+currChar;code++;oldPhrase=phrase;}
return Utf8.decode(out.join(""));}
$(function(){$('#bignotice,#bignotice a').css({'background-color':'#ff0000','color':'#ffffff'});$('#bignotice.green,#bignotice.green a').css({'background-color':'#009900','color':'#ffffff'});setTimeoutFunction(function(){$('#bignotice,#bignotice a').animate({backgroundColor:'#ffffff',color:'#000000'},1000);},1000);if(trim($('#NewFlash').text()).length>0){$('#NewFlash').css({width:Math.min(400,$('#NewFlash').width())+'px'});var h=$('#NewFlash').height();$('#NewFlash').css({display:'none',right:'0',top:'-'+(h+26)+'px'}).fadeIn(500);setTimeoutFunction(function(){$('#NewFlash').fadeOut(500);},30000);}
$('.report tr[class!=header]').hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');});});function StringBuilder(value){this.strings=new Array("");this.append(value);}
StringBuilder.prototype.append=function(value){if(value!=null)
this.strings.push(value);return this;}
StringBuilder.prototype.clear=function(){this.strings.length=1;}
StringBuilder.prototype.toString=function(){return this.strings.join("");}
var Utf8={encode:function(string){var utftext=[];for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext.push(String.fromCharCode(c));}
else if((c>127)&&(c<2048)){utftext.push(String.fromCharCode((c>>6)|192));utftext.push(String.fromCharCode((c&63)|128));}
else{utftext.push(String.fromCharCode((c>>12)|224));utftext.push(String.fromCharCode(((c>>6)&63)|128));utftext.push(String.fromCharCode((c&63)|128));}}
return utftext.join("");},decode:function(utftext){var string=[];var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string.push(String.fromCharCode(c));i++;}
else if((c>191)&&(c<224)){c2=utftext.charCodeAt(i+1);string.push(String.fromCharCode(((c&31)<<6)|(c2&63)));i+=2;}
else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string.push(String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63)));i+=3;}}
return string.join("");}}
function mysqlTimeStampToDate(timestamp){var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);}
function mysqlDateDiffSeconds(early,late){var a=mysqlTimeStampToDate(early);var b=mysqlTimeStampToDate(late);return(b.getTime()-a.getTime())/1000;}
function htmlspecialchars(p_string){if(p_string==null)
return null;p_string=p_string.replace(/&/g,'&amp;');p_string=p_string.replace(/</g,'&lt;');p_string=p_string.replace(/>/g,'&gt;');p_string=p_string.replace(/"/g,'&quot;');return p_string;};function var_dump(v){jqAlert(htmlspecialchars(JSON.stringify(v)));}
var ConsolidatedFunctionCall=function(f,timeout){this.Function=f;this.Timeout=timeout;this.Count=0;}
ConsolidatedFunctionCall.prototype.Queue=function(timeout){if(timeout==null)
timeout=this.Timeout;var me=this;this.Count++;setTimeoutFunction(function(){me.Count--;if(me.Count>0)
return;me.Function();},timeout);}
function EmbedVideo(url){var EmbedVideoIdx=0;document.write('<div class="something" url="'+htmlspecialchars(url)+'" style="height:500px;">&nbsp;</div>');$(function(){$('.something').each(function(){var s1=new SWFObject("/video/player.swf","ply","640","420","9","#1a1a1a");s1.addParam("quality","best");s1.addParam("allowfullscreen","true");s1.addParam("allowscriptaccess","always");s1.addParam("flashvars","file="+$(this).attr('url'));$(this).attr('id','embed_video_'+(EmbedVideoIdx++)).css({height:'auto'});s1.write(this.id);});});}
$(function(){var VideoIdx=0;$('.inlinevideo').each(function(){var s1=new SWFObject("/video/player.swf","ply","640","480","9","#1a1a1a");s1.addParam("quality","best");s1.addParam("allowfullscreen","true");s1.addParam("allowscriptaccess","always");s1.addParam("flashvars","file="+encodeURIComponent("http://lucidchart.s3.amazonaws.com/video/"+$(this).attr('url')));$(this).attr('id','video_'+(VideoIdx++));s1.write(this.id);});});Array.prototype.unique=function(){var r=new Array();o:for(var i=0,n=this.length;i<n;i++)
{for(var x=0,y=r.length;x<y;x++)
{if(r[x]==this[i])
{continue o;}}
r[r.length]=this[i];}
return r;}
function date(format,timestamp){var jsdate=((typeof(timestamp)=='undefined')?new Date():(typeof(timestamp)=='number')?new Date(timestamp*1000):new Date(timestamp));var pad=function(n,c){if((n=n+"").length<c){return new Array(++c-n.length).join("0")+n;}else{return n;}};var _dst=function(t){var dst=0;var jan1=new Date(t.getFullYear(),0,1,0,0,0,0);var june1=new Date(t.getFullYear(),6,1,0,0,0,0);var temp=jan1.toUTCString();var jan2=new Date(temp.slice(0,temp.lastIndexOf(' ')-1));temp=june1.toUTCString();var june2=new Date(temp.slice(0,temp.lastIndexOf(' ')-1));var std_time_offset=(jan1-jan2)/(1000*60*60);var daylight_time_offset=(june1-june2)/(1000*60*60);if(std_time_offset===daylight_time_offset){dst=0;}
else{var hemisphere=std_time_offset-daylight_time_offset;if(hemisphere>=0){std_time_offset=daylight_time_offset;}
dst=1;}
return dst;};var ret='';var txt_weekdays=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];var txt_ordin={1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};var txt_months=["","January","February","March","April","May","June","July","August","September","October","November","December"];var f={d:function(){return pad(f.j(),2);},D:function(){var t=f.l();return t.substr(0,3);},j:function(){return jsdate.getDate();},l:function(){return txt_weekdays[f.w()];},N:function(){return f.w()+1;},S:function(){return txt_ordin[f.j()]?txt_ordin[f.j()]:'th';},w:function(){return jsdate.getDay();},z:function(){return(jsdate-new Date(jsdate.getFullYear()+"/1/1"))/864e5>>0;},W:function(){var a=f.z(),b=364+f.L()-a;var nd2,nd=(new Date(jsdate.getFullYear()+"/1/1").getDay()||7)-1;if(b<=2&&((jsdate.getDay()||7)-1)<=2-b){return 1;}
if(a<=2&&nd>=4&&a>=(6-nd)){nd2=new Date(jsdate.getFullYear()-1+"/12/31");return date("W",Math.round(nd2.getTime()/1000));}
return(1+(nd<=3?((a+nd)/7):(a-(7-nd))/7)>>0);},F:function(){return txt_months[f.n()];},m:function(){return pad(f.n(),2);},M:function(){var t=f.F();return t.substr(0,3);},n:function(){return jsdate.getMonth()+1;},t:function(){var n;if((n=jsdate.getMonth()+1)==2){return 28+f.L();}
if(n&1&&n<8||!(n&1)&&n>7){return 31;}
return 30;},L:function(){var y=f.Y();return(!(y&3)&&(y%1e2||!(y%4e2)))?1:0;},o:function(){if(f.n()===12&&f.W()===1){return jsdate.getFullYear()+1;}
if(f.n()===1&&f.W()>=52){return jsdate.getFullYear()-1;}
return jsdate.getFullYear();},Y:function(){return jsdate.getFullYear();},y:function(){return(jsdate.getFullYear()+"").slice(2);},a:function(){return jsdate.getHours()>11?"pm":"am";},A:function(){return f.a().toUpperCase();},B:function(){var off=(jsdate.getTimezoneOffset()+60)*60;var theSeconds=(jsdate.getHours()*3600)+
(jsdate.getMinutes()*60)+
jsdate.getSeconds()+off;var beat=Math.floor(theSeconds/86.4);if(beat>1000){beat-=1000;}
if(beat<0){beat+=1000;}
if((String(beat)).length==1){beat="00"+beat;}
if((String(beat)).length==2){beat="0"+beat;}
return beat;},g:function(){return jsdate.getHours()%12||12;},G:function(){return jsdate.getHours();},h:function(){return pad(f.g(),2);},H:function(){return pad(jsdate.getHours(),2);},i:function(){return pad(jsdate.getMinutes(),2);},s:function(){return pad(jsdate.getSeconds(),2);},u:function(){return pad(jsdate.getMilliseconds()*1000,6);},e:function(){return'UTC';},I:function(){return _dst(jsdate);},O:function(){var t=pad(Math.abs(jsdate.getTimezoneOffset()/60*100),4);t=(jsdate.getTimezoneOffset()>0)?"-"+t:"+"+t;return t;},P:function(){var O=f.O();return(O.substr(0,3)+":"+O.substr(3,2));},T:function(){return'UTC';},Z:function(){return-jsdate.getTimezoneOffset()*60;},c:function(){return f.Y()+"-"+f.m()+"-"+f.d()+"T"+f.h()+":"+f.i()+":"+f.s()+f.P();},r:function(){return f.D()+', '+f.d()+' '+f.M()+' '+f.Y()+' '+f.H()+':'+f.i()+':'+f.s()+' '+f.O();},U:function(){return Math.round(jsdate.getTime()/1000);}};return format.replace(/[\\]?([a-zA-Z])/g,function(t,s){if(t!=s){ret=s;}else if(f[s]){ret=f[s]();}else{ret=s;}
return ret;});}
function strtotime(str,now){var i,match,s,strTmp='',parse='';strTmp=str;strTmp=strTmp.replace(/\s{2,}|^\s|\s$/g,' ');strTmp=strTmp.replace(/[\t\r\n]/g,'');if(strTmp=='now'){return(new Date()).getTime()/1000;}else if(!isNaN(parse=Date.parse(strTmp))){return(parse/1000);}else if(now){now=new Date(now*1000);}else{now=new Date();}
strTmp=strTmp.toLowerCase();var __is={day:{'sun':0,'mon':1,'tue':2,'wed':3,'thu':4,'fri':5,'sat':6},mon:{'jan':0,'feb':1,'mar':2,'apr':3,'may':4,'jun':5,'jul':6,'aug':7,'sep':8,'oct':9,'nov':10,'dec':11}};var process=function(m){var ago=(m[2]&&m[2]=='ago');var num=(num=m[0]=='last'?-1:1)*(ago?-1:1);switch(m[0]){case'last':case'next':switch(m[1].substring(0,3)){case'yea':now.setFullYear(now.getFullYear()+num);break;case'mon':now.setMonth(now.getMonth()+num);break;case'wee':now.setDate(now.getDate()+(num*7));break;case'day':now.setDate(now.getDate()+num);break;case'hou':now.setHours(now.getHours()+num);break;case'min':now.setMinutes(now.getMinutes()+num);break;case'sec':now.setSeconds(now.getSeconds()+num);break;default:var day;if(typeof(day=__is.day[m[1].substring(0,3)])!='undefined'){var diff=day-now.getDay();if(diff==0){diff=7*num;}else if(diff>0){if(m[0]=='last'){diff-=7;}}else{if(m[0]=='next'){diff+=7;}}
now.setDate(now.getDate()+diff);}}
break;default:if(/\d+/.test(m[0])){num*=parseInt(m[0],10);switch(m[1].substring(0,3)){case'yea':now.setFullYear(now.getFullYear()+num);break;case'mon':now.setMonth(now.getMonth()+num);break;case'wee':now.setDate(now.getDate()+(num*7));break;case'day':now.setDate(now.getDate()+num);break;case'hou':now.setHours(now.getHours()+num);break;case'min':now.setMinutes(now.getMinutes()+num);break;case'sec':now.setSeconds(now.getSeconds()+num);break;}}else{return false;}
break;}
return true;};match=strTmp.match(/^(\d{2,4}-\d{2}-\d{2})(?:\s(\d{1,2}:\d{2}(:\d{2})?)?(?:\.(\d+))?)?$/);if(match!=null){if(!match[2]){match[2]='00:00:00';}else if(!match[3]){match[2]+=':00';}
s=match[1].split(/-/g);for(i in __is.mon){if(__is.mon[i]==s[1]-1){s[1]=i;}}
s[0]=parseInt(s[0],10);s[0]=(s[0]>=0&&s[0]<=69)?'20'+(s[0]<10?'0'+s[0]:s[0]+''):(s[0]>=70&&s[0]<=99)?'19'+s[0]:s[0]+'';return parseInt(this.strtotime(s[2]+' '+s[1]+' '+s[0]+' '+match[2])+(match[4]?match[4]/1000:''),10);}
var regex='([+-]?\\d+\\s'+'(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'+'|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'+'|thu\.?|thursday|fri\.?|friday|sat\.?|saturday)'+'|(last|next)\\s'+'(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'+'|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'+'|thu\.?|thursday|fri\.?|friday|sat\.?|saturday))'+'(\\sago)?';match=strTmp.match(new RegExp(regex,'g'));if(match==null){return false;}
for(i in match){if(!process(match[i].split(' '))){return false;}}
return(now.getTime()/1000);}
function isEmpty(ob){for(var i in ob){return false;}
return true;}
function ucfirst(str){str+='';var f=str.charAt(0).toUpperCase();return f+str.substr(1);}
function RoundRenderData(ret,Rounding){if(Rounding==0)
return ret;function len(x,y,x2,y2){var dx=x2-x;var dy=y2-y;return Math.sqrt(dx*dx+dy*dy);}
function norm(x,y,x2,y2){var dx=x2-x;var dy=y2-y;var l=Math.sqrt(dx*dx+dy*dy);return{x:dx/l,y:dy/l};}
var x=0;var y=0;for(var i=0;i<ret.length;i++){if(ret[i].NoRounding)continue;for(var j=0;j<ret[i].Actions.length-1;j++){var a1=ret[i].Actions[j];var a2=ret[i].Actions[j+1];if(a2.Action=='close'){a2={Action:'line',x:ret[i].Actions[0].x,y:ret[i].Actions[0].y};}
if(a1.Action=='line'&&a2.Action=='line'){var n1=norm(a1.x,a1.y,x,y);var n2=norm(a1.x,a1.y,a2.x,a2.y);var l1=len(a1.x,a1.y,x,y);var l2=len(a1.x,a1.y,a2.x,a2.y);if(l1<Rounding||l2<Rounding){x=a1.x;y=a1.y;}
else{ret[i].Actions.splice(j+1,0,{Action:'curve',Control:[{x1:a1.x,y1:a1.y,x2:a1.x,y2:a1.y,x3:a1.x+n2.x*Rounding,y3:a1.y+n2.y*Rounding}]});x=a1.x+n2.x*Rounding;y=a1.y+n2.y*Rounding;a1.x+=n1.x*Rounding;a1.y+=n1.y*Rounding;j++;}}
else if(a1.Action=='move'||a1.Action=='line'){x=a1.x;y=a1.y;}
else if(a1.Action=='curve'){x=a1.Control[a1.Control.length-1].x3;y=a1.Control[a1.Control.length-1].y3;}}
if(ret[i].Actions[ret[i].Actions.length-1].Action=='close'){if(ret[i].Actions[0].Action=='move'&&ret[i].Actions[1].Action=='line'){var a2=ret[i].Actions[1];var n1=norm(ret[i].Actions[0].x,ret[i].Actions[0].y,x,y);var n2=norm(ret[i].Actions[0].x,ret[i].Actions[0].y,a2.x,a2.y);ret[i].Actions.splice(1,0,{Action:'curve',Control:[{x1:ret[i].Actions[0].x,y1:ret[i].Actions[0].y,x2:ret[i].Actions[0].x,y2:ret[i].Actions[0].y,x3:ret[i].Actions[0].x+n2.x*Rounding,y3:ret[i].Actions[0].y+n2.y*Rounding}]});ret[i].Actions[0].x+=n1.x*Rounding;ret[i].Actions[0].y+=n1.y*Rounding;}}}
return ret;}


function InitCanvas(c){c=$(c).get(0);if(window.G_vmlCanvasManager){c=G_vmlCanvasManager.initElement(c);}
c._Context=c.getContext('2d');c.getContext=function(type){return this._Context;}
c._Context.StrokeAndFill=function(f){this.beginPath();f.call(this);this.fill();this.beginPath();f.call(this);this.stroke();};c.BindedEvents=[];c.Bind=function(type,f){this.BindedEvents.push(type);$(this).bind(type,f);};c.Cursor=function(c){$(this).css({cursor:c});}
c._Context.ellipse=function(x,y,w,h,s,e){var pts=EllipseArcControlPoints(x,y,w,h,s,e,true);this.moveTo(pts[0].x,pts[0].y);for(var i=1;i<pts.length;i++){var p=pts[i];this.bezierCurveTo(p.x1,p.y1,p.x2,p.y2,p.x3,p.y3);}}
c._Context.StrokeChunk=function(data,scale){if(scale==null)scale=1;for(var i=0;i<data.length;i++){if(data[i].Action=='move')
this.moveTo(data[i].x*scale,data[i].y*scale);else if(data[i].Action=='line')
this.lineTo(data[i].x*scale,data[i].y*scale);else if(data[i].Action=='close')
this.closePath();else if(data[i].Action=='curve'){for(var cp=0;cp<data[i].Control.length;cp++){p=data[i].Control[cp];this.bezierCurveTo(p.x1*scale,p.y1*scale,p.x2*scale,p.y2*scale,p.x3*scale,p.y3*scale);}}}}
c._Context.DrawRenderData=function(RenderData,Selected){if(Selected){for(var i=0;i<RenderData.length;i++){if(RenderData[i].StrokeColor){this.strokeStyle='rgba(136,51,51,.5)';this.lineWidth=RenderData[i].LineWidth+8;this.beginPath();this.StrokeChunk(RenderData[i].Actions);this.stroke();}}}
for(var i=0;i<RenderData.length;i++){if(RenderData[i].Image!=null){try{this.drawImage(RenderData[i].Image,RenderData[i].BoundingBox.x,RenderData[i].BoundingBox.y,RenderData[i].BoundingBox.w,RenderData[i].BoundingBox.h);}catch(err){this.fillStyle='#aaaaaa';this.fillRect(RenderData[i].BoundingBox.x,RenderData[i].BoundingBox.y,RenderData[i].BoundingBox.w,RenderData[i].BoundingBox.h);}}
else{if(RenderData[i].FillColor){this.fillStyle=RenderData[i].FillColor;this.beginPath();this.StrokeChunk(RenderData[i].Actions);this.fill();}
if(RenderData[i].StrokeColor){this.strokeStyle=RenderData[i].StrokeColor;this.lineWidth=RenderData[i].LineWidth;this.beginPath();this.StrokeChunk(RenderData[i].Actions);this.stroke();}}}}
return c;}


function SuperCanvas(w,h){g_Client.Log.Log('sc','new SuperCanvas ('+w+','+h+')');this.layers=[];this.id='SuperCanvas'+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000);this.container=$(document.createElement('div'));this.container.attr('id',this.id);this.container.css({position:'relative',overflow:'hidden'});this.resize(w,h);}
SuperCanvas.prototype.resize=function(w,h){g_Client.Log.Log('sc','SuperCanvas.resize ('+w+','+h+')');this.width=w;this.height=h;this.container.css({width:this.width+'px',height:this.height+'px'});}
SuperCanvas.prototype.addLayer=function(l){g_Client.Log.Log('sc','addLayer ('+l.width+','+l.height+')');if($.inArray(l,this.layers)==-1){this.layers.push(l);this.container.append(l.container);return true;}
return false;}
SuperCanvas.prototype.removeLayer=function(l){g_Client.Log.Log('sc','removeLayer ('+l.width+','+l.height+')');var idx=$.inArray(l,this.layers);if(idx!=-1){this.layers.splice(idx,1);l.container.remove();}}
SuperCanvas.prototype.removeLayerByAttribute=function(a,v){for(var i=0;i<this.layers.length;i++){if(this.layers[i][a]==v){this.removeLayer(this.layers[i]);i--;}}}
SuperCanvas.prototype.bind=function(event,fn){$('#'+this.id+', #'+this.id+' *').live(event,fn);}
SuperCanvas.prototype.cursor=function(c){this.container.css({cursor:c});}
function SuperCanvasLayer(x,y,w,h,padding){g_Client.Log.Log('sc','new Layer ('+w+','+h+')');this.container=$(document.createElement('div'));this.canvas=$(document.createElement('canvas'));this.container.append(this.canvas);this.canvas.css({position:'absolute',left:0,top:0});this.move(x,y,w,h,padding==null?5:padding);if(window.G_vmlCanvasManager)
this.canvas=$(G_vmlCanvasManager.initElement(this.canvas.get(0)));}
SuperCanvasLayer.prototype.move=function(x,y,w,h,padding){g_Client.Log.Log('sc','move ('+w+','+h+')');if((x==null||x==this.x)&&(y==null||y==this.y)&&(w==null||w==this.width)&&(h==null||h==this.height)&&(padding==null||padding==this.padding))
return;if(x!=null)this.x=x;if(y!=null)this.y=y;if(w!=null)this.width=w;if(h!=null)this.height=h;if(padding!=null&&padding!=this.padding){this.container.find('div').each(function(){if($(this).attr('layerOverlayX')!=null)
$(this).css('left',(parseFloat($(this).attr('layerOverlayX'))+padding)+'px');if($(this).attr('layerOverlayY')!=null)
$(this).css('top',(parseFloat($(this).attr('layerOverlayY'))+padding)+'px');});this.padding=padding;}
this._updatePosition();}
SuperCanvasLayer.prototype.addDiv=function(x,y,w,h){g_Client.Log.Log('sc','addDiv ('+this.width+','+this.height+')');var div=$(document.createElement('div'));var me=this;div.move=function(x,y,w,h){var css={position:'absolute'};if(x!=null)css.left=Math.round(x+me.padding)+'px';if(y!=null)css.top=Math.round(y+me.padding)+'px';if(w!=null)css.width=w+'px';if(h!=null)css.height=h+'px';div.css(css);if(x!=null)div.attr('layerOverlayX',x);if(y!=null)div.attr('layerOverlayY',y);}
div.move(x,y,w,h);this.container.append(div);return div;}
SuperCanvasLayer.prototype._updatePosition=function(){if(this.canvas.attr('width')!=this.width+this.padding*2)
this.canvas.attr('width',this.width+this.padding*2);if(this.canvas.attr('height')!=this.height+this.padding*2)
this.canvas.attr('height',this.height+this.padding*2);this.container.css({position:'absolute',left:(this.x-this.padding)+'px',top:(this.y-this.padding)+'px',width:(this.width+this.padding*2)+'px',height:(this.height+this.padding*2)+'px'});}
SuperCanvasLayer.prototype.getContext=function(){var me=this;g_Client.Log.Log('sc','getContext ('+this.width+','+this.height+')');if(this.context==null){var ctx=this.canvas.get(0).getContext('2d');ctx.StrokeChunk=function(data,scale){if(scale==null)scale=1;for(var i=0;i<data.length;i++){if(data[i].Action=='move')
this.moveTo(data[i].x*scale,data[i].y*scale);else if(data[i].Action=='line')
this.lineTo(data[i].x*scale,data[i].y*scale);else if(data[i].Action=='close')
this.closePath();else if(data[i].Action=='curve'){for(var cp=0;cp<data[i].Control.length;cp++){p=data[i].Control[cp];this.bezierCurveTo(p.x1*scale,p.y1*scale,p.x2*scale,p.y2*scale,p.x3*scale,p.y3*scale);}}}}
ctx.ellipse=function(x,y,w,h,s,e){var pts=EllipseArcControlPoints(x,y,w,h,s,e,true);this.moveTo(pts[0].x,pts[0].y);for(var i=1;i<pts.length;i++){var p=pts[i];this.bezierCurveTo(p.x1,p.y1,p.x2,p.y2,p.x3,p.y3);}}
this.context=ctx;this.context.save();}
this.context.restore();this.context.save();this.context.clearRect(0,0,me.width+me.padding*2,me.height+me.padding*2);this.context.translate(this.padding,this.padding);return this.context;}


var RGBColor=function(color_string){this.ok=false;if(color_string.charAt(0)=='#'){color_string=color_string.substr(1,6);}
color_string=color_string.replace(/ /g,'');color_string=color_string.toLowerCase();var simple_colors=RGBColor.SimpleColors;for(var key in simple_colors){if(color_string==key){color_string=simple_colors[key];}}
var color_defs=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:['rgb(123, 234, 45)','rgb(255,234,245)'],process:function(bits){return[parseInt(bits[1]),parseInt(bits[2]),parseInt(bits[3])];}},{re:/^rgba\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*([\d\.]+)\)$/,example:['rgba(123, 234, 45,.1)','rgba(255,234,245,.5)'],process:function(bits){return[parseInt(bits[1]),parseInt(bits[2]),parseInt(bits[3]),parseFloat(bits[4])];}},{re:/^(\w{2})(\w{2})(\w{2})$/,example:['#00ff00','336699'],process:function(bits){return[parseInt(bits[1],16),parseInt(bits[2],16),parseInt(bits[3],16)];}},{re:/^(\w{1})(\w{1})(\w{1})$/,example:['#fb0','f0f'],process:function(bits){return[parseInt(bits[1]+bits[1],16),parseInt(bits[2]+bits[2],16),parseInt(bits[3]+bits[3],16)];}}];for(var i=0;i<color_defs.length;i++){var re=color_defs[i].re;var processor=color_defs[i].process;var bits=re.exec(color_string);if(bits){g_Client.Log.Log('color',color_string+' was found by '+re);channels=processor(bits);this.r=channels[0];this.g=channels[1];this.b=channels[2];if(channels.length==4)
this.a=channels[3];this.ok=true;}}
this.r=(this.r<0||isNaN(this.r))?0:((this.r>255)?255:this.r);this.g=(this.g<0||isNaN(this.g))?0:((this.g>255)?255:this.g);this.b=(this.b<0||isNaN(this.b))?0:((this.b>255)?255:this.b);this.toRGB=function(){return'rgb('+this.r+', '+this.g+', '+this.b+')';}
this.toHex=function(){var r=this.r.toString(16);var g=this.g.toString(16);var b=this.b.toString(16);if(r.length==1)r='0'+r;if(g.length==1)g='0'+g;if(b.length==1)b='0'+b;return'#'+r+g+b;}}
RGBColor.prototype.Multiply=function(f){var r=Math.round(Math.max(0,Math.min(this.r*f,255)));var g=Math.round(Math.max(0,Math.min(this.g*f,255)));var b=Math.round(Math.max(0,Math.min(this.b*f,255)));return new RGBColor("rgb("+r+","+g+","+b+")");}
RGBColor.prototype.Lighten=function(f){var r=Math.round(Math.max(0,Math.min(this.r*(1-f)+255*f,255)));var g=Math.round(Math.max(0,Math.min(this.g*(1-f)+255*f,255)));var b=Math.round(Math.max(0,Math.min(this.b*(1-f)+255*f,255)));return new RGBColor("rgb("+r+","+g+","+b+")");}
RGBColor.prototype.GetPDFData=function(){return{r:this.r/255,g:this.g/255,b:this.b/255};}
RGBColor.SimpleColors={aliceblue:'f0f8ff',antiquewhite:'faebd7',aqua:'00ffff',aquamarine:'7fffd4',azure:'f0ffff',beige:'f5f5dc',bisque:'ffe4c4',black:'000000',blanchedalmond:'ffebcd',blue:'0000ff',blueviolet:'8a2be2',brown:'a52a2a',burlywood:'deb887',cadetblue:'5f9ea0',chartreuse:'7fff00',chocolate:'d2691e',coral:'ff7f50',cornflowerblue:'6495ed',cornsilk:'fff8dc',crimson:'dc143c',cyan:'00ffff',darkblue:'00008b',darkcyan:'008b8b',darkgoldenrod:'b8860b',darkgray:'a9a9a9',darkgreen:'006400',darkkhaki:'bdb76b',darkmagenta:'8b008b',darkolivegreen:'556b2f',darkorange:'ff8c00',darkorchid:'9932cc',darkred:'8b0000',darksalmon:'e9967a',darkseagreen:'8fbc8f',darkslateblue:'483d8b',darkslategray:'2f4f4f',darkturquoise:'00ced1',darkviolet:'9400d3',deeppink:'ff1493',deepskyblue:'00bfff',dimgray:'696969',dodgerblue:'1e90ff',feldspar:'d19275',firebrick:'b22222',floralwhite:'fffaf0',forestgreen:'228b22',fuchsia:'ff00ff',gainsboro:'dcdcdc',ghostwhite:'f8f8ff',gold:'ffd700',goldenrod:'daa520',gray:'808080',green:'008000',greenyellow:'adff2f',honeydew:'f0fff0',hotpink:'ff69b4',indianred:'cd5c5c',indigo:'4b0082',ivory:'fffff0',khaki:'f0e68c',lavender:'e6e6fa',lavenderblush:'fff0f5',lawngreen:'7cfc00',lemonchiffon:'fffacd',lightblue:'add8e6',lightcoral:'f08080',lightcyan:'e0ffff',lightgoldenrodyellow:'fafad2',lightgrey:'d3d3d3',lightgreen:'90ee90',lightpink:'ffb6c1',lightsalmon:'ffa07a',lightseagreen:'20b2aa',lightskyblue:'87cefa',lightslateblue:'8470ff',lightslategray:'778899',lightsteelblue:'b0c4de',lightyellow:'ffffe0',lime:'00ff00',limegreen:'32cd32',linen:'faf0e6',magenta:'ff00ff',maroon:'800000',mediumaquamarine:'66cdaa',mediumblue:'0000cd',mediumorchid:'ba55d3',mediumpurple:'9370d8',mediumseagreen:'3cb371',mediumslateblue:'7b68ee',mediumspringgreen:'00fa9a',mediumturquoise:'48d1cc',mediumvioletred:'c71585',midnightblue:'191970',mintcream:'f5fffa',mistyrose:'ffe4e1',moccasin:'ffe4b5',navajowhite:'ffdead',navy:'000080',oldlace:'fdf5e6',olive:'808000',olivedrab:'6b8e23',orange:'ffa500',orangered:'ff4500',orchid:'da70d6',palegoldenrod:'eee8aa',palegreen:'98fb98',paleturquoise:'afeeee',palevioletred:'d87093',papayawhip:'ffefd5',peachpuff:'ffdab9',peru:'cd853f',pink:'ffc0cb',plum:'dda0dd',powderblue:'b0e0e6',purple:'800080',red:'ff0000',rosybrown:'bc8f8f',royalblue:'4169e1',saddlebrown:'8b4513',salmon:'fa8072',sandybrown:'f4a460',seagreen:'2e8b57',seashell:'fff5ee',sienna:'a0522d',silver:'c0c0c0',skyblue:'87ceeb',slateblue:'6a5acd',slategray:'708090',snow:'fffafa',springgreen:'00ff7f',steelblue:'4682b4',tan:'d2b48c',teal:'008080',thistle:'d8bfd8',tomato:'ff6347',turquoise:'40e0d0',violet:'ee82ee',violetred:'d02090',wheat:'f5deb3',white:'ffffff',whitesmoke:'f5f5f5',yellow:'ffff00',yellowgreen:'9acd32'};


if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return"";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;


var bkExtend=function(){var args=arguments;if(args.length==1)args=[this,args[0]];for(var prop in args[1])args[0][prop]=args[1][prop];return args[0];};function bkClass(){}
bkClass.prototype.construct=function(){};bkClass.extend=function(def){var classDef=function(){if(arguments[0]!==bkClass){return this.construct.apply(this,arguments);}};var proto=new this(bkClass);bkExtend(proto,def);classDef.prototype=proto;classDef.extend=this.extend;return classDef;};var bkElement=bkClass.extend({construct:function(elm,d){if(typeof(elm)=="string"){elm=(d||document).createElement(elm);}
elm=$BK(elm);return elm;},appendTo:function(elm){elm.appendChild(this);return this;},appendBefore:function(elm){elm.parentNode.insertBefore(this,elm);return this;},addEvent:function(type,fn){bkLib.addEvent(this,type,fn);return this;},setContent:function(c){this.innerHTML=c;return this;},pos:function(){var curleft=curtop=0;var o=obj=this;if(obj.offsetParent){do{curleft+=obj.offsetLeft;curtop+=obj.offsetTop;if(obj.scrollLeft)
curleft-=obj.scrollLeft;if(obj.scrollTop)
curtop-=obj.scrollTop;}while(obj=obj.offsetParent);}
var b=(!window.opera)?parseInt(this.getStyle('border-width')||this.style.border)||0:0;return[curleft+b,curtop+b+this.offsetHeight];},noSelect:function(){bkLib.noSelect(this);return this;},parentTag:function(t){var elm=this;do{if(elm&&elm.nodeName&&elm.nodeName.toUpperCase()==t){return elm;}
elm=elm.parentNode;}while(elm);return false;},hasClass:function(cls){return this.className.match(new RegExp('(\\s|^)nicEdit-'+cls+'(\\s|$)'));},addClass:function(cls){if(!this.hasClass(cls)){this.className+=" nicEdit-"+cls};return this;},removeClass:function(cls){if(this.hasClass(cls)){this.className=this.className.replace(new RegExp('(\\s|^)nicEdit-'+cls+'(\\s|$)'),' ');}
return this;},setStyle:function(st){var elmStyle=this.style;for(var itm in st){switch(itm){case'float':elmStyle['cssFloat']=elmStyle['styleFloat']=st[itm];break;case'opacity':elmStyle.opacity=st[itm];elmStyle.filter="alpha(opacity="+Math.round(st[itm]*100)+")";break;case'className':this.className=st[itm];break;default:elmStyle[itm]=st[itm];}}
return this;},getStyle:function(cssRule,d){var doc=(!d)?document.defaultView:d;if(this.nodeType==1)
return(doc&&doc.getComputedStyle)?doc.getComputedStyle(this,null).getPropertyValue(cssRule):this.currentStyle[bkLib.camelize(cssRule)];},remove:function(){this.parentNode.removeChild(this);return this;},setAttributes:function(at){for(var itm in at){this[itm]=at[itm];}
return this;}});var bkLib={isMSIE:(navigator.appVersion.indexOf("MSIE")!=-1),addEvent:function(obj,type,fn){(obj.addEventListener)?obj.addEventListener(type,fn,false):obj.attachEvent("on"+type,fn);},toArray:function(iterable){var length=iterable.length,results=new Array(length);while(length--){results[length]=iterable[length]};return results;},noSelect:function(element){if(element.setAttribute&&element.nodeName.toLowerCase()!='input'&&element.nodeName.toLowerCase()!='textarea'){element.setAttribute('unselectable','on');}
for(var i=0;i<element.childNodes.length;i++){bkLib.noSelect(element.childNodes[i]);}},camelize:function(s){return s.replace(/\-(.)/g,function(m,l){return l.toUpperCase()});},inArray:function(arr,item){return(bkLib.search(arr,item)!=null);},search:function(arr,itm){for(var i=0;i<arr.length;i++){if(arr[i]==itm)
return i;}
return null;},cancelEvent:function(e){e=e||window.event;if(e.preventDefault&&e.stopPropagation){e.preventDefault();e.stopPropagation();}
return false;},domLoad:[],domLoaded:function(){if(arguments.callee.done)return;arguments.callee.done=true;for(i=0;i<bkLib.domLoad.length;i++)bkLib.domLoad[i]();},onDomLoaded:function(fireThis){this.domLoad.push(fireThis);if(document.addEventListener){document.addEventListener("DOMContentLoaded",bkLib.domLoaded,null);}else if(bkLib.isMSIE){document.write("<style>.nicEdit-main p { margin: 0; }</style><scr"+"ipt id=__ie_onload defer "+((location.protocol=="https:")?"src='javascript:void(0)'":"src=//0")+"><\/scr"+"ipt>");$BK("__ie_onload").onreadystatechange=function(){if(this.readyState=="complete"){bkLib.domLoaded();}};}
window.onload=bkLib.domLoaded;}};function $BK(elm){if(typeof(elm)=="string"){elm=document.getElementById(elm);}
return(elm&&!elm.appendTo)?bkExtend(elm,bkElement.prototype):elm;}
var bkEvent={addEvent:function(evType,evFunc){if(evFunc){this.eventList=this.eventList||{};this.eventList[evType]=this.eventList[evType]||[];this.eventList[evType].push(evFunc);}
return this;},fireEvent:function(){var args=bkLib.toArray(arguments),evType=args.shift();if(this.eventList&&this.eventList[evType]){for(var i=0;i<this.eventList[evType].length;i++){this.eventList[evType][i].apply(this,args);}}}};function __(s){return s;}
Function.prototype.closure=function(){var __method=this,args=bkLib.toArray(arguments),obj=args.shift();return function(){if(typeof(bkLib)!='undefined'){return __method.apply(obj,args.concat(bkLib.toArray(arguments)));}};}
Function.prototype.closureListener=function(){var __method=this,args=bkLib.toArray(arguments),object=args.shift();return function(e){e=e||window.event;if(e.target){var target=e.target;}else{var target=e.srcElement};return __method.apply(object,[e,target].concat(args));};}
var nicEditorConfig=bkClass.extend({buttons:{'bold':{name:__('Click to Bold'),command:'Bold',tags:['B','STRONG'],css:{'font-weight':'bold'},key:'b'},'italic':{name:__('Click to Italic'),command:'Italic',tags:['EM','I'],css:{'font-style':'italic'},key:'i'},'underline':{name:__('Click to Underline'),command:'Underline',tags:['U'],css:{'text-decoration':'underline'},key:'u'},'left':{name:__('Left Align'),command:'justifyleft',noActive:true},'center':{name:__('Center Align'),command:'justifycenter',noActive:true},'right':{name:__('Right Align'),command:'justifyright',noActive:true},'justify':{name:__('Justify Align'),command:'justifyfull',noActive:true},'ol':{name:__('Insert Ordered List'),command:'insertorderedlist',tags:['OL']},'ul':{name:__('Insert Unordered List'),command:'insertunorderedlist',tags:['UL']},'subscript':{name:__('Click to Subscript'),command:'subscript',tags:['SUB']},'superscript':{name:__('Click to Superscript'),command:'superscript',tags:['SUP']},'strikethrough':{name:__('Click to Strike Through'),command:'strikeThrough',css:{'text-decoration':'line-through'}},'removeformat':{name:__('Remove Formatting'),command:'removeformat',noActive:true},'indent':{name:__('Indent Text'),command:'indent',noActive:true},'outdent':{name:__('Remove Indent'),command:'outdent',noActive:true},'hr':{name:__('Horizontal Rule'),command:'insertHorizontalRule',noActive:true}},iconsPath:'/scratch/javascript/nicedit/nicEditorIcons.gif',buttonList:['save','bold','italic','underline','left','center','right','justify','ol','ul','fontSize','fontFamily','fontFormat','indent','outdent','image','upload','link','unlink','forecolor','bgcolor'],iconList:{"bgcolor":1,"forecolor":2,"bold":3,"center":4,"hr":5,"indent":6,"italic":7,"justify":8,"left":9,"ol":10,"outdent":11,"removeformat":12,"right":13,"save":24,"strikethrough":15,"subscript":16,"superscript":17,"ul":18,"underline":19,"image":20,"link":21,"unlink":22,"close":23,"arrow":25}});var nicEditors={nicPlugins:[],editors:[],registerPlugin:function(plugin,options){this.nicPlugins.push({p:plugin,o:options});},allTextAreas:function(nicOptions){var textareas=document.getElementsByTagName("textarea");for(var i=0;i<textareas.length;i++){nicEditors.editors.push(new nicEditor(nicOptions).panelInstance(textareas[i]));}
return nicEditors.editors;},findEditor:function(e){var editors=nicEditors.editors;for(var i=0;i<editors.length;i++){if(editors[i].instanceById(e)){return editors[i].instanceById(e);}}}};var nicEditor=bkClass.extend({construct:function(o){this.options=new nicEditorConfig();bkExtend(this.options,o);this.nicInstances=new Array();this.loadedPlugins=new Array();var plugins=nicEditors.nicPlugins;for(var i=0;i<plugins.length;i++){this.loadedPlugins.push(new plugins[i].p(this,plugins[i].o));}
nicEditors.editors.push(this);bkLib.addEvent(document.body,'mousedown',this.selectCheck.closureListener(this));},panelInstance:function(e,o){e=this.checkReplace($BK(e));var panelElm=new bkElement('DIV').setStyle({width:(parseInt(e.getStyle('width'))||e.clientWidth)+'px'}).appendBefore(e);this.setPanel(panelElm);return this.addInstance(e,o);},checkReplace:function(e){var r=nicEditors.findEditor(e);if(r){r.removeInstance(e);r.removePanel();}
return e;},addInstance:function(e,o){e=this.checkReplace($BK(e));if(e.contentEditable||!!window.opera){var newInstance=new nicEditorInstance(e,o,this);}else{var newInstance=new nicEditorIFrameInstance(e,o,this);}
this.nicInstances.push(newInstance);return newInstance;},removeInstance:function(e){e=$BK(e);var instances=this.nicInstances;for(var i=0;i<instances.length;i++){if(instances[i].e==e){instances[i].remove();this.nicInstances.splice(i,1);}}},removePanel:function(e){if(this.nicPanel){this.nicPanel.remove();this.nicPanel=null;}},instanceById:function(e){e=$BK(e);var instances=this.nicInstances;for(var i=0;i<instances.length;i++){if(instances[i].e==e){return instances[i];}}},setPanel:function(e){this.nicPanel=new nicEditorPanel($BK(e),this.options,this);this.fireEvent('panel',this.nicPanel);return this;},nicCommand:function(cmd,args){if(this.selectedInstance){this.selectedInstance.nicCommand(cmd,args);}},getIcon:function(iconName,options){var icon=this.options.iconList[iconName];var file=(options.iconFiles)?options.iconFiles[iconName]:'';return{backgroundImage:"url('"+((icon)?this.options.iconsPath:file)+"')",backgroundPosition:((icon)?((icon-1)*-18):0)+'px 0px'};},selectCheck:function(e,t){var found=false;do{if(t.className&&t.className.indexOf('nicEdit')!=-1){return false;}}while(t=t.parentNode);this.fireEvent('blur',this.selectedInstance,t);this.lastSelectedInstance=this.selectedInstance;this.selectedInstance=null;return false;}});nicEditor=nicEditor.extend(bkEvent);var nicEditorInstance=bkClass.extend({isSelected:false,construct:function(e,options,nicEditor){this.ne=nicEditor;this.elm=this.e=e;this.options=options||{};newX=parseInt(e.getStyle('width'))||e.clientWidth;newY=parseInt(e.getStyle('height'))||e.clientHeight;this.initialHeight=newY-8;var isTextarea=(e.nodeName.toLowerCase()=="textarea");if(isTextarea||this.options.hasPanel){var ie7s=(bkLib.isMSIE&&!((typeof document.body.style.maxHeight!="undefined")&&document.compatMode=="CSS1Compat"))
var s={width:newX+'px',border:'1px solid #ccc',borderTop:0,overflowY:'auto',overflowX:'hidden'};s[(ie7s)?'height':'maxHeight']=(this.ne.options.maxHeight)?this.ne.options.maxHeight+'px':null;this.editorContain=new bkElement('DIV').setStyle(s).appendBefore(e);var editorElm=new bkElement('DIV').setStyle({width:(newX-8)+'px',margin:'4px',minHeight:newY+'px'}).addClass('main').appendTo(this.editorContain);e.setStyle({display:'none'});editorElm.innerHTML=e.innerHTML;if(isTextarea){editorElm.setContent(e.value);this.copyElm=e;var f=e.parentTag('FORM');if(f){bkLib.addEvent(f,'submit',this.saveContent.closure(this));}}
editorElm.setStyle((ie7s)?{height:newY+'px'}:{overflow:'hidden'});this.elm=editorElm;}
this.ne.addEvent('blur',this.blur.closure(this));this.init();this.blur();},init:function(){this.elm.setAttribute('contentEditable','true');if(this.getContent()==""){this.setContent('<br />');}
this.instanceDoc=document.defaultView;this.elm.addEvent('mousedown',this.selected.closureListener(this)).addEvent('keypress',this.keyDown.closureListener(this)).addEvent('focus',this.selected.closure(this)).addEvent('blur',this.blur.closure(this)).addEvent('keyup',this.selected.closure(this));this.ne.fireEvent('add',this);},remove:function(){this.saveContent();if(this.copyElm||this.options.hasPanel){this.editorContain.remove();this.e.setStyle({'display':'block'});this.ne.removePanel();}
this.disable();this.ne.fireEvent('remove',this);},disable:function(){this.elm.setAttribute('contentEditable','false');},getSel:function(){var ret=(window.getSelection)?window.getSelection():document.selection;if(ret.createRange==null){ret.createRange=function(){if(window.createRange)
var range=window.createRange();else if(document.createRange)
var range=document.createRange();else
return null;if(this.baseNode==null||this.extentNode==null)
return range;range.setStart(this.baseNode,this.baseOffset);range.setEnd(this.extentNode,this.extentOffset);if(range.collapsed){range.setStart(this.extentNode,this.extentOffset);range.setEnd(this.baseNode,this.baseOffset);}
return range;}}
return ret;},getRng:function(){var s=this.getSel();if(!s){return null;}
return(s.rangeCount>0)?s.getRangeAt(0):s.createRange();},selRng:function(rng,s){if(window.getSelection){s.removeAllRanges();s.addRange(rng);}else{rng.select();}},select:function(n,c){var t=this,r=t.getRng(),s=t.getSel(),b,fn,ln,d=document;function first(n){return n?d.createTreeWalker(n,NodeFilter.SHOW_TEXT,null,false).nextNode():null;};function last(n){var c,o,w;if(!n)
return null;w=d.createTreeWalker(n,NodeFilter.SHOW_TEXT,null,false);while(c=w.nextNode())
o=c;return o;};if(is_ie){try{b=d.body;if(/^(IMG|TABLE)$/.test(n.nodeName)){r=b.createControlRange();r.addElement(n);}else{r=b.createTextRange();r.moveToElementText(n);}
r.select();}catch(ex){}}else{if(c){fn=first(n);ln=last(n);if(fn&&ln){r=d.createRange();r.setStart(fn,0);r.setEnd(ln,ln.nodeValue.length);}else
r.selectNode(n);}else
r.selectNode(n);t.setRng(r);}
return n;},setRng:function(r){var s;if(!is_ie){s=this.getSel();if(s){s.removeAllRanges();s.addRange(r);}}else{try{r.select();}catch(ex){}}},selElm:function(){var r=this.getRng();if(r.startContainer){var contain=r.startContainer;if(r.cloneContents().childNodes.length==1){for(var i=0;i<contain.childNodes.length;i++){var rng=contain.childNodes[i].ownerDocument.createRange();rng.selectNode(contain.childNodes[i]);if(r.compareBoundaryPoints(Range.START_TO_START,rng)!=1&&r.compareBoundaryPoints(Range.END_TO_END,rng)!=-1){return $BK(contain.childNodes[i]);}}}
return $BK(contain);}else{return $BK((this.getSel().type=="Control")?r.item(0):r.parentElement());}},saveRng:function(){this.savedRange=this.getRng();this.savedSel=this.getSel();},restoreRng:function(){if(this.savedRange){this.selRng(this.savedRange,this.savedSel);}},keyDown:function(e,t){if(e.ctrlKey){this.ne.fireEvent('key',this,e);}},selected:function(e,t){if(!t){t=this.selElm()}
if(!e.ctrlKey){var selInstance=this.ne.selectedInstance;if(selInstance!=this){if(selInstance){this.ne.fireEvent('blur',selInstance,t);}
this.ne.selectedInstance=this;this.ne.fireEvent('focus',selInstance,t);}
this.ne.fireEvent('selected',selInstance,t);this.isFocused=true;this.elm.addClass('selected');}
return false;},blur:function(){this.isFocused=false;this.elm.removeClass('selected');},saveContent:function(){if(this.copyElm||this.options.hasPanel){this.ne.fireEvent('save',this);(this.copyElm)?this.copyElm.value=this.getContent():this.e.innerHTML=this.getContent();}},getElm:function(){return this.elm;},getContent:function(){this.content=this.getElm().innerHTML;this.ne.fireEvent('get',this);return this.content;},setContent:function(e){this.content=e;this.ne.fireEvent('set',this);this.elm.innerHTML=this.content;},wrapSelectionWithTag:function(element){var range=this.getRng();if(range.surroundContents){range.surroundContents(element);}
else{var tmpParent=window.document.createElement('div');tmpParent.appendChild(element);element.innerHTML+=range.htmlText;range.pasteHTML(tmpParent.innerHTML);range.select();}
return element;},hookedCommands:{},hookCommand:function(cmd,f){this.hookedCommands[cmd]=f;},nicCommand:function(cmd,args){if(this.hookedCommands[cmd]!=null){this.hookedCommands[cmd].call(this,args);}
else{document.execCommand(cmd,false,args);}}});var nicEditorPanel=bkClass.extend({construct:function(e,options,nicEditor){this.elm=e;this.options=options;this.ne=nicEditor;this.panelButtons=new Array();this.buttonList=bkExtend([],this.ne.options.buttonList);this.panelContain=new bkElement('DIV').setStyle({overflow:'hidden',width:'100%',border:'1px solid #cccccc',backgroundColor:'#efefef'}).addClass('panelContain');this.panelElm=new bkElement('DIV').setStyle({margin:'2px',marginTop:'0px',zoom:1,overflow:'hidden'}).addClass('panel').appendTo(this.panelContain);this.panelContain.appendTo(e);var opt=this.ne.options;var buttons=opt.buttons;for(button in buttons){this.addButton(button,opt,true);}
this.reorder();e.noSelect();},addButton:function(buttonName,options,noOrder){var button=options.buttons[buttonName];var type=(button['type'])?eval('(typeof('+button['type']+') == "undefined") ? null : '+button['type']+';'):nicEditorButton;var hasButton=bkLib.inArray(this.buttonList,buttonName);if(type&&(hasButton||this.ne.options.fullPanel)){this.panelButtons.push(new type(this.panelElm,buttonName,options,this.ne));if(!hasButton){this.buttonList.push(buttonName);}}},findButton:function(itm){for(var i=0;i<this.panelButtons.length;i++){if(this.panelButtons[i].name==itm)
return this.panelButtons[i];}},reorder:function(){var bl=this.buttonList;for(var i=0;i<bl.length;i++){var button=this.findButton(bl[i]);if(button){this.panelElm.appendChild(button.margin);}}},remove:function(){this.elm.remove();}});var nicEditorButton=bkClass.extend({construct:function(e,buttonName,options,nicEditor){this.options=options.buttons[buttonName];this.name=buttonName;this.ne=nicEditor;this.elm=e;this.margin=new bkElement('DIV').setStyle({'float':'left',marginTop:'2px'}).appendTo(e);this.contain=new bkElement('DIV').setStyle({width:'20px',height:'20px'}).addClass('buttonContain').appendTo(this.margin);this.border=new bkElement('DIV').setStyle({backgroundColor:'#efefef',border:'1px solid #efefef'}).appendTo(this.contain);this.button=new bkElement('DIV').setStyle({width:'18px',height:'18px',overflow:'hidden',zoom:1,cursor:'pointer'}).addClass('button').setStyle(this.ne.getIcon(buttonName,options)).appendTo(this.border);this.button.addEvent('mouseover',this.hoverOn.closure(this)).addEvent('mouseout',this.hoverOff.closure(this)).addEvent('mousedown',this.mouseClick.closure(this)).noSelect();if(!window.opera){this.button.onmousedown=this.button.onclick=bkLib.cancelEvent;}
nicEditor.addEvent('selected',this.enable.closure(this)).addEvent('blur',this.disable.closure(this)).addEvent('key',this.key.closure(this));this.disable();this.init();},init:function(){},hide:function(){this.contain.setStyle({display:'none'});},updateState:function(){if(this.isDisabled){this.setBg();}
else if(this.isHover){this.setBg('hover');}
else if(this.isActive){this.setBg('active');}
else{this.setBg();}},setBg:function(state){switch(state){case'hover':var stateStyle={border:'1px solid #666',backgroundColor:'#ddd'};break;case'active':var stateStyle={border:'1px solid #666',backgroundColor:'#ccc'};break;default:var stateStyle={border:'1px solid #efefef',backgroundColor:'#efefef'};}
this.border.setStyle(stateStyle).addClass('button-'+state);},checkNodes:function(e){var elm=e;do{if(this.options.tags&&bkLib.inArray(this.options.tags,elm.nodeName)){this.activate();return true;}}while(elm=elm.parentNode&&elm.className!="nicEdit");elm=$BK(e);while(elm.nodeType==3){elm=$BK(elm.parentNode);}
if(this.options.css){for(itm in this.options.css){if(elm.getStyle(itm,this.ne.selectedInstance.instanceDoc)==this.options.css[itm]){this.activate();return true;}}}
this.deactivate();return false;},activate:function(){if(!this.isDisabled){this.isActive=true;this.updateState();this.ne.fireEvent('buttonActivate',this);}},deactivate:function(){this.isActive=false;this.updateState();if(!this.isDisabled){this.ne.fireEvent('buttonDeactivate',this);}},enable:function(ins,t){this.isDisabled=false;this.contain.setStyle({'opacity':1}).addClass('buttonEnabled');this.updateState();this.checkNodes(t);},disable:function(ins,t){this.isDisabled=true;this.contain.setStyle({'opacity':0.6}).removeClass('buttonEnabled');this.updateState();},toggleActive:function(){(this.isActive)?this.deactivate():this.activate();},hoverOn:function(){if(!this.isDisabled){this.isHover=true;this.updateState();this.ne.fireEvent("buttonOver",this);}},hoverOff:function(){this.isHover=false;this.updateState();this.ne.fireEvent("buttonOut",this);},mouseClick:function(){if(this.options.command){this.ne.nicCommand(this.options.command,this.options.commandArgs);if(!this.options.noActive){this.toggleActive();}}
this.ne.fireEvent("buttonClick",this);},key:function(nicInstance,e){if(this.options.key&&e.ctrlKey&&String.fromCharCode(e.keyCode||e.charCode).toLowerCase()==this.options.key){this.mouseClick();if(e.preventDefault)e.preventDefault();}}});var nicPlugin=bkClass.extend({construct:function(nicEditor,options){this.options=options;this.ne=nicEditor;this.ne.addEvent('panel',this.loadPanel.closure(this));this.init();},loadPanel:function(np){var buttons=this.options.buttons;for(var button in buttons){np.addButton(button,this.options);}
np.reorder();},init:function(){}});var nicPaneOptions={};var nicEditorPane=bkClass.extend({construct:function(elm,nicEditor,options,openButton){this.ne=nicEditor;this.elm=elm;this.pos=elm.pos();this.contain=new bkElement('div').setStyle({zIndex:'99999',overflow:'hidden',position:'absolute',left:this.pos[0]+'px',top:this.pos[1]+'px'})
this.pane=new bkElement('div').setStyle({fontSize:'12px',border:'1px solid #ccc','overflow':'hidden',padding:'4px',textAlign:'left',backgroundColor:'#ffffc9'}).addClass('pane').setStyle(options).appendTo(this.contain);if(openButton&&!openButton.options.noClose){this.close=new bkElement('div').setStyle({'float':'right',height:'16px',width:'16px',cursor:'pointer'}).setStyle(this.ne.getIcon('close',nicPaneOptions)).addEvent('mousedown',openButton.removePane.closure(this)).appendTo(this.pane);}
this.contain.noSelect().appendTo(document.body);this.position();this.init();},init:function(){},position:function(){if(this.ne.nicPanel){var panelElm=this.ne.nicPanel.elm;var panelPos=panelElm.pos();var newLeft=panelPos[0]+parseInt(panelElm.getStyle('width'))-(parseInt(this.pane.getStyle('width'))+8);if(newLeft<this.pos[0]){this.contain.setStyle({left:newLeft+'px'});}}},toggle:function(){this.isVisible=!this.isVisible;this.contain.setStyle({display:((this.isVisible)?'block':'none')});},remove:function(){if(this.contain){this.contain.remove();this.contain=null;}},append:function(c){c.appendTo(this.pane);},setContent:function(c){this.pane.setContent(c);}});var nicEditorAdvancedButton=nicEditorButton.extend({init:function(){this.ne.addEvent('selected',this.removePane.closure(this)).addEvent('blur',this.removePane.closure(this));},mouseClick:function(){if(!this.isDisabled){if(this.pane&&this.pane.pane){this.removePane();}else{this.pane=new nicEditorPane(this.contain,this.ne,{width:(this.width||'270px'),backgroundColor:'#fff'},this);this.addPane();this.ne.selectedInstance.saveRng();}}},addForm:function(f,elm){this.form=new bkElement('form').addEvent('submit',this.submit.closureListener(this));this.pane.append(this.form);this.inputs={};for(itm in f){var field=f[itm];var val='';if(elm){val=elm.getAttribute(itm);}
if(!val){val=field['value']||'';}
var type=f[itm].type;if(type=='title'){new bkElement('div').setContent(field.txt).setStyle({fontSize:'14px',fontWeight:'bold',padding:'0px',margin:'2px 0'}).appendTo(this.form);}else{var contain=new bkElement('div').setStyle({overflow:'hidden',clear:'both'}).appendTo(this.form);if(field.txt){new bkElement('label').setAttributes({'for':itm}).setContent(field.txt).setStyle({margin:'2px 4px',fontSize:'13px',width:'50px',lineHeight:'20px',textAlign:'right','float':'left'}).appendTo(contain);}
switch(type){case'text':this.inputs[itm]=new bkElement('input').setAttributes({id:itm,'value':val,'type':'text'}).setStyle({margin:'2px 0',fontSize:'13px','float':'left',height:'20px',border:'1px solid #ccc',overflow:'hidden'}).setStyle(field.style).appendTo(contain);break;case'select':this.inputs[itm]=new bkElement('select').setAttributes({id:itm}).setStyle({border:'1px solid #ccc','float':'left',margin:'2px 0'}).appendTo(contain);for(opt in field.options){var o=new bkElement('option').setAttributes({value:opt,selected:(opt==val)?'selected':''}).setContent(field.options[opt]).appendTo(this.inputs[itm]);}
break;case'content':this.inputs[itm]=new bkElement('textarea').setAttributes({id:itm}).setStyle({border:'1px solid #ccc','float':'left'}).setStyle(field.style).appendTo(contain);this.inputs[itm].value=val;}}}
new bkElement('input').setAttributes({'type':'submit'}).setStyle({backgroundColor:'#efefef',border:'1px solid #ccc',margin:'3px 0','float':'left','clear':'both'}).appendTo(this.form);this.form.onsubmit=bkLib.cancelEvent;},submit:function(){},findElm:function(tag,attr,val){var list=this.ne.selectedInstance.getElm().getElementsByTagName(tag);for(var i=0;i<list.length;i++){if(list[i].getAttribute(attr)==val){return $BK(list[i]);}}},removePane:function(){if(this.pane){this.pane.remove();this.pane=null;this.ne.selectedInstance.restoreRng();}}});var nicButtonTips=bkClass.extend({construct:function(nicEditor){this.ne=nicEditor;nicEditor.addEvent('buttonOver',this.show.closure(this)).addEvent('buttonOut',this.hide.closure(this)).addEvent('remove',this.hide.closure(this));},show:function(button){this.timer=setTimeout(this.create.closure(this,button),400);},create:function(button){this.timer=null;if(!this.pane){this.pane=new nicEditorPane(button.button,this.ne,{fontSize:'12px',marginTop:'5px'});this.pane.setContent(button.options.name);}},hide:function(button){if(this.timer){clearTimeout(this.timer);}
if(this.pane){this.pane=this.pane.remove();}}});nicEditors.registerPlugin(nicButtonTips);var nicSelectOptions={buttons:{'fontSize':{name:__('Select Font Size'),type:'nicEditorFontSizeSelect',command:'fontsize'},'fontFamily':{name:__('Select Font Family'),type:'nicEditorFontFamilySelect',command:'fontname'},'fontFormat':{name:__('Select Font Format'),type:'nicEditorFontFormatSelect',command:'formatBlock'}}};var nicEditorSelect=bkClass.extend({construct:function(e,buttonName,options,nicEditor){this.options=options.buttons[buttonName];this.elm=e;this.ne=nicEditor;this.name=buttonName;this.selOptions=new Array();this.margin=new bkElement('div').setStyle({'float':'left',margin:'2px 1px 0 1px'}).appendTo(this.elm);this.contain=new bkElement('div').setStyle({width:'90px',height:'20px',cursor:'pointer',overflow:'hidden'}).addClass('selectContain').addEvent('click',this.toggle.closure(this)).appendTo(this.margin);this.items=new bkElement('div').setStyle({overflow:'hidden',zoom:1,border:'1px solid #ccc',paddingLeft:'3px',backgroundColor:'#fff'}).appendTo(this.contain);this.control=new bkElement('div').setStyle({overflow:'hidden','float':'right',height:'18px',width:'16px'}).addClass('selectControl').setStyle(this.ne.getIcon('arrow',options)).appendTo(this.items);this.txt=new bkElement('div').setStyle({overflow:'hidden','float':'left',width:'66px',height:'14px',marginTop:'1px',fontFamily:'sans-serif',textAlign:'center',fontSize:'12px'}).addClass('selectTxt').appendTo(this.items);if(!window.opera){this.contain.onmousedown=this.control.onmousedown=this.txt.onmousedown=bkLib.cancelEvent;}
this.margin.noSelect();this.ne.addEvent('selected',this.enable.closure(this)).addEvent('blur',this.disable.closure(this));this.disable();this.init();},disable:function(){this.isDisabled=true;this.close();this.contain.setStyle({opacity:0.6});},enable:function(t){this.isDisabled=false;this.close();this.contain.setStyle({opacity:1});},setDisplay:function(txt){this.txt.setContent(txt);},toggle:function(){if(!this.isDisabled){(this.pane)?this.close():this.open();}},open:function(){this.pane=new nicEditorPane(this.items,this.ne,{width:'180px',padding:'0px',borderTop:0,borderLeft:'1px solid #ccc',borderRight:'1px solid #ccc',borderBottom:'0px',backgroundColor:'#fff'});for(var i=0;i<this.selOptions.length;i++){var opt=this.selOptions[i];var itmContain=new bkElement('div').setStyle({overflow:'hidden',borderBottom:'1px solid #ccc',width:'180px',textAlign:'left',overflow:'hidden',cursor:'pointer'});var itm=new bkElement('div').setStyle({padding:'0px 4px'}).setContent(opt[1]).appendTo(itmContain).noSelect();itm.addEvent('click',this.update.closure(this,opt[0])).addEvent('mouseover',this.over.closure(this,itm)).addEvent('mouseout',this.out.closure(this,itm)).setAttributes('id',opt[0]);this.pane.append(itmContain);if(!window.opera){itm.onmousedown=bkLib.cancelEvent;}}},close:function(){if(this.pane){this.pane=this.pane.remove();}},over:function(opt){opt.setStyle({backgroundColor:'#ccc'});},out:function(opt){opt.setStyle({backgroundColor:'#fff'});},add:function(k,v){this.selOptions.push(new Array(k,v));},update:function(elm){this.ne.nicCommand(this.options.command,elm);this.close();}});var nicEditorFontSizeSelect=nicEditorSelect.extend({sel:{9:'Very small',12:'Small',18:'Normal',24:'Large',36:'Very Large',72:'Title'},init:function(){this.setDisplay('Font&nbsp;Size...');for(itm in this.sel){this.add(itm,'<span style="font-size:'+itm+'px;">'+this.sel[itm]+'</span>');}}});var nicEditorFontFamilySelect=nicEditorSelect.extend({sel:{'arial':'Arial','comic sans ms':'Comic Sans','courier new':'Courier New','georgia':'Georgia','helvetica':'Helvetica','impact':'Impact','times new roman':'Times','trebuchet ms':'Trebuchet','verdana':'Verdana'},init:function(){this.setDisplay('Font&nbsp;Family...');for(itm in this.sel){this.add(itm,'<font face="'+itm+'">'+this.sel[itm]+'</font>');}}});var nicEditorFontFormatSelect=nicEditorSelect.extend({sel:{'p':'Paragraph','pre':'Pre','h6':'Heading&nbsp;6','h5':'Heading&nbsp;5','h4':'Heading&nbsp;4','h3':'Heading&nbsp;3','h2':'Heading&nbsp;2','h1':'Heading&nbsp;1'},init:function(){this.setDisplay('Font&nbsp;Format...');for(itm in this.sel){var tag=itm.toUpperCase();this.add('<'+tag+'>','<'+itm+' style="padding: 0px; margin: 0px;">'+this.sel[itm]+'</'+tag+'>');}}});nicEditors.registerPlugin(nicPlugin,nicSelectOptions);var nicLinkOptions={buttons:{'link':{name:'Add Link',type:'nicLinkButton',tags:['A']},'unlink':{name:'Remove Link',command:'unlink',noActive:true}}};var nicLinkButton=nicEditorAdvancedButton.extend({addPane:function(){this.ln=this.ne.selectedInstance.selElm().parentTag('A');this.addForm({'':{type:'title',txt:'Add/Edit Link'},'href':{type:'text',txt:'URL',value:'http://',style:{width:'150px'}},'title':{type:'text',txt:'Title'},'target':{type:'select',txt:'Open In',options:{'':'Current Window','_blank':'New Window'},style:{width:'100px'}}},this.ln);},submit:function(e){var url=this.inputs['href'].value;if(url=="http://"||url==""){alert("You must enter a URL to Create a Link");return false;}
this.removePane();if(!this.ln){var tmp='javascript:nicTemp();';this.ne.nicCommand("createlink",tmp);this.ln=this.findElm('A','href',tmp);}
if(this.ln){this.ln.setAttributes({href:this.inputs['href'].value,title:this.inputs['title'].value,target:this.inputs['target'].options[this.inputs['target'].selectedIndex].value});}}});nicEditors.registerPlugin(nicPlugin,nicLinkOptions);var nicColorOptions={buttons:{'forecolor':{name:__('Change Text Color'),command:'ChooseColor',noActive:true},'bgcolor':{name:__('Change Background Color'),type:'nicEditorBgColorButton',noClose:true}}};var nicEditorColorButton=nicEditorAdvancedButton.extend({addPane:function(){var me=this;$(this.pane.elm).colorPicker({immediate:true,done:function(id,val){me.colorSelect(val);}});},colorSelect:function(c){this.ne.nicCommand('foreColor',c);this.removePane();},on:function(colorBorder){colorBorder.setStyle({border:'2px solid #000'});},off:function(colorBorder,colorCode){colorBorder.setStyle({border:'2px solid '+colorCode});}});var nicEditorBgColorButton=nicEditorColorButton.extend({colorSelect:function(c){this.ne.nicCommand('hiliteColor',c);this.removePane();}});nicEditors.registerPlugin(nicPlugin,nicColorOptions);var nicImageOptions={buttons:{'image':{name:'Add Image',type:'nicImageButton',tags:['IMG']}}};var nicImageButton=nicEditorAdvancedButton.extend({addPane:function(){this.im=this.ne.selectedInstance.selElm().parentTag('IMG');this.addForm({'':{type:'title',txt:'Add/Edit Image'},'src':{type:'text',txt:'URL','value':'http://',style:{width:'150px'}},'alt':{type:'text',txt:'Alt Text',style:{width:'100px'}},'align':{type:'select',txt:'Align',options:{none:'Default','left':'Left','right':'Right'}}},this.im);},submit:function(e){var src=this.inputs['src'].value;if(src==""||src=="http://"){alert("You must enter a Image URL to insert");return false;}
this.removePane();if(!this.im){var tmp='javascript:nicImTemp();';this.ne.nicCommand("insertImage",tmp);this.im=this.findElm('IMG','src',tmp);}
if(this.im){this.im.setAttributes({src:this.inputs['src'].value,alt:this.inputs['alt'].value,align:this.inputs['align'].value});}}});nicEditors.registerPlugin(nicPlugin,nicImageOptions);var nicSaveOptions={buttons:{'save':{name:__('Save this content'),type:'nicEditorSaveButton'}}};var nicEditorSaveButton=nicEditorButton.extend({init:function(){if(!this.ne.options.onSave){this.margin.setStyle({'display':'none'});}},mouseClick:function(){var onSave=this.ne.options.onSave;var selectedInstance=this.ne.selectedInstance;onSave(selectedInstance.getContent(),selectedInstance.elm.id,selectedInstance);}});nicEditors.registerPlugin(nicPlugin,nicSaveOptions);


var InlineEditor={ClosestMatch:function(needle,haystack){var mindist=null;var ret=null;for(var i=0;i<haystack.length;i++){var dist=Math.abs(haystack[i]-needle);if(mindist==null||dist<mindist){mindist=dist;ret=haystack[i];}}
return ret;},GetTextDecoration:function(s){if(s==null)
return'none';var raw=s.style?s.style.textDecoration:'';if(raw.toLowerCase()=='none')
return'none';else if(raw.toLowerCase()=='underline')
return'underline';else if(raw.toLowerCase()=='line-through')
return'line-through';if($(s).attr('IsEditing'))
return'none';return InlineEditor.GetTextDecoration(s.parentNode);},GetRealFontSize:function(e,scale){if(scale==null)scale=1;var re=/^([0-9\.]+)px/;var match=re.exec($(e).css('font-size'));if(match){var ret=parseFloat(match[1]);}else{var id='fyds789afyhdsua9fuhds9afydhs9a8';$(e).append('<span style="position:absolute;top:0;left:0;" id="'+id+'">I</span>');var ret=Math.round($('#'+id).get(0).offsetHeight*.85*100)/100;$('#'+id).remove();}
return InlineEditor.ClosestMatch(ret,[9*scale,12*scale,18*scale,24*scale,36*scale,72*scale])/scale;},CanonicalCSS:function(e,p){var ret=$(e).css(p);if(p=='font-weight'){if(ret=='400')ret='normal';if(ret=='700')ret='bold'}
else if(p=='color'){var c=new RGBColor(ret);ret=c.toHex();}
else if(p=='text-decoration'){ret=InlineEditor.GetTextDecoration(e);}
return ret;},WhollyStyled:function(e,style,val){var ret=true;var HasTextNode=false;for(var i=0;i<e.childNodes.length;i++){if(e.childNodes[i].nodeType==3)
HasTextNode=true;else
ret=ret&&InlineEditor.WhollyStyled(e.childNodes[i],style,val);}
if(HasTextNode)
ret=ret&&InlineEditor.CanonicalCSS(e,style)==val;return ret;},StripStyleFromChildren:function(filter,style){$(filter).find('*').each(function(){if(this.style[style]&&this.style[style]!='')
this.style[style]=$(filter).get(0).style[style];});for(var p=$(filter).parent().get(0);p!=null&&!$(p).attr('IsEditing');p=p.parentNode){if($(p).text()==$(filter).text()&&p.style[style]&&p.style[style]!='')
p.style[style]=$(filter).get(0).style[style];}},StyleChange:function(div,i,scale){var ret='';function AddProp(p){if(InlineEditor.CanonicalCSS(div,p)!=InlineEditor.CanonicalCSS(div.childNodes[i],p))
ret+=p+':'+InlineEditor.CanonicalCSS(div.childNodes[i],p)+';';}
AddProp('font-weight');AddProp('font-style');AddProp('color');AddProp('text-decoration');var DivSize=InlineEditor.GetRealFontSize(div,scale);var ISize=InlineEditor.GetRealFontSize(div.childNodes[i],scale);if(DivSize!=ISize){ret+='font-size:'+ISize+'px;';}
return ret;},LineHasNonWhitespace:false,ProcessHTML:function(div,AfterFirst,scale){$(div).find('[class^=f]').each(function(){this.style.fontSize=(this.className.substr(1)*scale)+'px';});var ret='';if(!AfterFirst){ret='<span style="font-size:'+InlineEditor.GetRealFontSize(div,scale)+'px;">';InlineEditor.LineHasNonWhitespace=false;}
for(var i=0;i<div.childNodes.length;i++){if(div.childNodes[i].nodeType==3){var text=htmlspecialchars(div.childNodes[i].nodeValue);if(!InlineEditor.LineHasNonWhitespace){text=ltrim(text);if(text.length>0)
InlineEditor.LineHasNonWhitespace=true;}
ret+=text;}
else if(div.childNodes[i].nodeType==8){}
else if(div.childNodes[i].tagName&&div.childNodes[i].tagName.toLowerCase()=='br'){ret+='<br/>';}
else{try{$(div.childNodes[i]).css('display');}
catch(e){alert(div.childNodes[i].nodeType);}
if($(div.childNodes[i]).css('display')=='block'&&i>0){var prevIdx=i-1;var prevNode=div.childNodes[prevIdx];while(prevNode.nodeType==3&&trim(prevNode.nodeValue).length==0){prevIdx--;if(prevIdx<0){prevNode=null;break;}
prevNode=div.childNodes[prevIdx];}
if(prevNode!=null){if(prevNode.tagName&&prevNode.tagName.toLowerCase()!='br'){ret+='<br/>';InlineEditor.LineHasNonWhitespace=false;}}}
var style=InlineEditor.StyleChange(div,i,scale);if(style!='')
ret+='<span style="'+style+'">';ret+=InlineEditor.ProcessHTML(div.childNodes[i],true,scale);if(style!='')
ret+='</span>';}}
if(!AfterFirst)
ret+='</span>';g_Client.Log.Log('InlineEditor','ProcessHTML ('+ret.length+')');return ret;},CurrentId:null,StartProfileTimer:function(){this.ProfileTime=new Date();},ProfileTimer:function(msg){var t=new Date();g_Client.Log.Log('ile',(t.getTime()-this.ProfileTime.getTime())+'ms: '+msg);this.ProfileTime=t;},Create:function(id,scale,done,WantReturn){this.StartProfileTimer();var Div=$('#'+id);if(Div.attr('IsEditing')||Div.size()==0)
return;Div.wrap('<div></div>');Div.parent().css({position:'absolute',left:Div.css('left'),top:Div.css('top')});Div.css({position:'static',left:'0px',top:'0px'});$('body').attr('spellcheck',false);Div.attr('spellcheck','false');if(InlineEditor.CurrentId!=null)
$('#'+InlineEditor.CurrentId).blur();InlineEditor.CurrentId=id;var TextPanelId='text_panel'+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000);Div.parent().append('<div id="'+TextPanelId+'"></div>');$('#'+TextPanelId).css({position:'absolute',left:Div.css('left'),top:(parseFloat(Div.css('top').replace('px',''))+Div.get(0).offsetHeight)+'px',width:Math.max(100,Div.get(0).offsetWidth)});Div.attr('IsEditing','on');this.ProfileTimer('IsEditing on');var nicedit=new nicEditor({buttonList:['bold','italic','underline','strikethrough','forecolor','removeformat','fontSize'],iconsPath:'/js/nicedit/nicEditorIcons.gif'});this.ProfileTimer('new nicEditor');nicedit.setPanel(TextPanelId);var area=nicedit.addInstance(id);area.hookCommand('fontsize',function(args){var spanid='span_id_wrapper_thingy_4y8329483'+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000);this.wrapSelectionWithTag($('<span id="'+spanid+'" style="font-size:'+(args*scale)+'px;"></span>').get(0));InlineEditor.StripStyleFromChildren('#'+spanid,'fontSize');if($('#'+spanid).text()=='')
area.select($('#'+spanid).get(0).childNodes[0]);else
area.select($('#'+spanid).get(0));});area.hookCommand('ChooseColor',function(args){var me=this;$('#'+TextPanelId).colorPicker({immediate:true,done:function(id,args){var spanid='span_id_wrapper_thingy_4y8329483'+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000);me.wrapSelectionWithTag($('<span id="'+spanid+'" style="color:'+args+';"><span></span></span>').get(0));InlineEditor.StripStyleFromChildren('#'+spanid,'color');if($('#'+spanid).text()=='')
area.select($('#'+spanid).get(0).childNodes[0]);else
area.select($('#'+spanid).get(0));}});});function HookCommand(Command,Style,CamelStyle,Value,NonValue){area.hookCommand(Command,function(args){var spanid='span_id_wrapper_thingy_4y8329483'+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000)+Math.floor(Math.random()*1000000);this.wrapSelectionWithTag($('<span id="'+spanid+'"><span></span></span>').get(0));if(InlineEditor.WhollyStyled($('#'+spanid).get(0),Style,Value))
$('#'+spanid).css(Style,NonValue);else
$('#'+spanid).css(Style,Value);InlineEditor.StripStyleFromChildren('#'+spanid,CamelStyle);if($('#'+spanid).text()=='')
area.select($('#'+spanid).get(0).childNodes[0]);else
area.select($('#'+spanid).get(0));});}
HookCommand('Bold','font-weight','fontWeight','bold','normal');HookCommand('Italic','font-style','fontStyle','italic','normal');HookCommand('Underline','text-decoration','textDecoration','underline','none');HookCommand('strikeThrough','text-decoration','textDecoration','line-through','none');var ResizeInterval=setInterval(function(){$('#'+TextPanelId).css({position:'absolute',left:Div.css('left'),top:(parseFloat(Div.css('top').replace('px',''))+Div.get(0).offsetHeight)+'px',width:Math.max(100,Div.get(0).offsetWidth)});},250);if(!WantReturn){Div.keydown(function(e){if(e.keyCode==13||e.which==13){if(e.shiftKey){}
else{Div.blur();return false;}}});}
this.ProfileTimer('Hooked all the commands');setTimeoutFunction(function(){g_Client.Log.Log('Render','Inlineeditor focus');Div.focus();InlineEditor.ProfileTimer('Div focused');var ToSelect=Div.children().get(0);if(!is_ie){while(ToSelect.childNodes&&ToSelect.childNodes.length==1)
ToSelect=ToSelect.childNodes[0];}
area.select(ToSelect);area.selected({ctrlKey:false});InlineEditor.ProfileTimer('Stuff selected');if(is_ie){var DocMouseDown=function(e){if(EventInElement(e,Div))return;if(EventInElement(e,'#'+TextPanelId))return;var InPanel=false;$('.nicEdit-pane,#iColorPicker').each(function(){if(EventInElement(e,this))
InPanel=true;});if(InPanel)
return;Div.blur();}
$(document).bind('mousedown',DocMouseDown);}
Div.one('blur',function(){if(is_ie)
$(document).unbind('mousedown',DocMouseDown);InlineEditor.ProfileTimer('Blur called');nicedit.removeInstance(id);$('#'+TextPanelId).remove();Div.removeAttr('IsEditing');Div.unbind('keydown');clearInterval(ResizeInterval);var ret=InlineEditor.Finalize(id,Div.html(),scale);if(done!=null)
done(ret);InlineEditor.CurrentId=null;Div.css({position:'absolute',left:Div.parent().css('left'),top:Div.parent().css('top')});Div.parent().replaceWith(Div);var ff=$('<input type="text"/>');$('body').append(ff);ff.focus();ff.remove();});InlineEditor.ProfileTimer('Blur event set');},1);g_Client.Log.Log('Render','SetTimeout for inlineeditor focus');return Div;},Finalize:function(id,val,scale,FromCanonical){$('#'+id).css({'font-size':(InlineEditor.DefaultSize*scale)+'px'});$('#'+id).html(val);if(FromCanonical&&InlineEditor.IsCanonical(id)){var CanonicalText=val;}
else{var CanonicalText=InlineEditor.ProcessHTML($('#'+id).get(0),null,scale);$('#'+id).html(CanonicalText);}
$('#'+id).find('span').each(function(){try{this.style.fontSize=(parseFloat(this.style.fontSize.replace('px',''))*scale)+'px';}
catch(e){}});return CanonicalText;},IsCanonical:function(id){if($('#'+id).children().size()!=1)
return false;var top=$('#'+id).children().get(0);if(top.tagName.toLowerCase()!='span')
return false;if($('#'+id).find('p').size()>0)
return false;if($('#'+id).find('div').size()>0)
return false;if($('#'+id).find('[class]').size()>0)
return false;return true;},DefaultSize:18}


var LucidMenuItem=function(Label,OnClick,OnShow,Hotkey,Icon){this.Label=Label;this.OnClick=OnClick==null?function(){}:OnClick;this.OnShow=OnShow==null?function(){return true;}:OnShow;this.Hotkey=Hotkey;this.Icon=Icon;this.Children=[];}
var LucidMenu=function(IsContextMenu,id,Context){this.MenuItems=[];this.IsContextMenu=IsContextMenu;this.Contexts=[];if(Context!=null)
this.Contexts.push(Context);if(id==null)
id='menu';this.id=id;g_Client._RegisterMarkupItem(this,function(){if(this.Div==null){if(this.IsContextMenu)
$('body').append("<div style='display:none;' class='contextMenu' id='"+id+"'></div>");else
$('body').append("<div id='"+id+"' style='float:left;'></div>");this.Div=$('#'+id);}
else{if(!this.IsContextMenu)
this.Div.find('ul:first').jdMenuUnbind();}
if(this.IsContextMenu){this.Div.html(this._GetMarkup());this._ReattachContexts();}
else{this.Div.html(this._GetMarkup()).find('ul:first').jdMenu();this._SetEvents();}});}
LucidMenu.prototype.GetTargetWidth=function(){var ret=2;if(this.Div!=null){this.Div.find('li').each(function(){ret+=jqWidth(this);});}
return ret;}
LucidMenu.prototype._ReattachContexts=function(){for(var i=0;i<this.Contexts.length;i++)
this.AttachContextMenu(this.Contexts[i]);}
LucidMenu.prototype.AttachContextMenu=function(Context){if(!this.IsContextMenu||Context==null)
return;if(arrayIndexOf(this.Contexts,Context)==-1)
this.Contexts.push(Context);var me=this;$(Context).contextMenu(this.id,{bindings:this._GetBindings(Context),onContextMenu:function(event){return!$(Context).attr('IsEditing')&&g_Client.CanEdit();},onShowMenu:function(event,menu){var fns=me._GetAllOnShows(Context);for(var key in fns){if(!fns[key]())
$('#'+key,menu).remove();}
return menu;}});}
LucidMenu.prototype._GetBindings=function(Context,MenuItems,Path){if(MenuItems==null){MenuItems=this.MenuItems;Path=this.id;}
Path+='_';var ret={};for(var i=0;i<MenuItems.length;i++){var id=Path+MenuItems[i].Label.replace(/[^a-zA-Z0-9]/g,'');ret[id]=(function(m){return function(menu,pos){pos.x-=$(g_Client.Viewport.Canvas.container).offset().left;pos.y-=$(g_Client.Viewport.Canvas.container).offset().top;pos.x/=g_Client.Viewport.Scale;pos.y/=g_Client.Viewport.Scale;if(m.OnShow(Context))
m.OnClick(Context,pos);}})(MenuItems[i]);if(MenuItems[i].Children.length>0){var child=this._GetBindings(Context,MenuItems[i].Children,id);for(var key in child)
ret[key]=child[key];}}
return ret;}
LucidMenu.prototype._GetAllOnShows=function(Context,MenuItems,Path){if(MenuItems==null){MenuItems=this.MenuItems;Path=this.id;}
Path+='_';var ret={};for(var i=0;i<MenuItems.length;i++){var id=Path+MenuItems[i].Label.replace(/[^a-zA-Z0-9]/g,'');ret[id]=(function(m){return function(){return m.OnShow(Context);}})(MenuItems[i]);if(MenuItems[i].Children.length>0){var child=this._GetAllOnShows(Context,MenuItems[i].Children,id);for(var key in child)
ret[key]=child[key];}}
return ret;}
LucidMenu.prototype._SetEvents=function(MenuItems,Path){if(MenuItems==null){MenuItems=this.MenuItems;Path=this.id;}
Path+='_';for(var i=0;i<MenuItems.length;i++){var id=Path+MenuItems[i].Label.replace(/[^a-zA-Z0-9]/g,'');$('#'+id).click((function(m){return function(){if(m.OnShow())
m.OnClick();}})(MenuItems[i]));if(MenuItems[i].Children.length>0)
this._SetEvents(MenuItems[i].Children,id);}}
LucidMenu.prototype.RemoveMenuItem=function(Path){var MenuItems=this.MenuItems;var Parts=Path.split('/');for(var p=0;p<Parts.length;p++){var Found=false;for(var m=0;m<MenuItems.length;m++){if(MenuItems[m].Label==Parts[p]){if(p==Parts.length-1){this.MarkupDirty=true;MenuItems.splice(m,1);return;}
else{Found=true;MenuItems=MenuItems[m].Children;break;}}}
if(!Found)
return;}}
LucidMenu.prototype.AddMenuItem=function(Path,OnClick,OnShow,Hotkey,Icon,Before){this.MarkupDirty=true;var MenuItems=this.MenuItems;var Parts=Path.split('/');for(var p=0;p<Parts.length;p++){var Found=false;for(var m=0;m<MenuItems.length;m++){if(MenuItems[m].Label==Parts[p]){Found=true;MenuItems=MenuItems[m].Children;break;}}
if(!Found){if(p<Parts.length-1){var New=new LucidMenuItem(Parts[p]);MenuItems.push(New);MenuItems=New.Children;}
else{var m;for(m=0;m<MenuItems.length;m++){if(MenuItems[m].Label==Before)
break;}
var New=new LucidMenuItem(Parts[p],OnClick,OnShow,Hotkey,Icon);MenuItems.splice(m,0,New);if(Hotkey!=null){$(document).bind('keydown',Hotkey,function(){if(!g_Client.KeyboardInputHasFocus()&&New.OnShow()){New.OnClick();return false;}});}}}}}
LucidMenu.prototype._GetMarkup=function(MenuItems,Path){var ret='<ul>';if(MenuItems==null){MenuItems=this.MenuItems;if(!this.IsContextMenu)
ret="<ul class='jd_menu'>";Path=this.id;}
Path+='_';for(var i=0;i<MenuItems.length;i++){var id=Path+MenuItems[i].Label.replace(/[^a-zA-Z0-9]/g,'');ret+='<li id="'+id+'">';if(MenuItems[i].Hotkey!=null)
ret+='<span style="float:right;">'+MenuItems[i].Hotkey+'</span>';if(MenuItems[i].Icon!=null){g_Client.ImageManager.GetImage('/img/icons/'+MenuItems[i].Icon);ret+='<img style="width:16px;height:16px;" src="/img/icons/'+MenuItems[i].Icon+'"/>';}
ret+=MenuItems[i].Label;if(MenuItems[i].Children.length>0)
ret+=this._GetMarkup(MenuItems[i].Children,id);ret+='</li>';}
ret+='</ul>';return ret;}


var LucidToolboxItem=function(ClassName,DefaultProperties){this.ClassName=ClassName;this.DefaultProperties=DefaultProperties==null?function(){return{};}:DefaultProperties;}
var LucidToolboxGroup=function(Label){this.Label=Label;this.Items=[];this.id='toolboxgroup_'+Label.replace(/[^a-zA-Z0-9]/g,'');}
var LucidToolbox=function(){this.Groups=[];this.DraggingBlockClass=null;this.DroppingBlock=false;this.SelectedGroup=null;g_Client._RegisterMarkupItem(this,function(){if(this.Div==null){$('body').append('<div id="toolboxdiv"><div id="toolbar"></div></div>');this.Div=$('#toolboxdiv');this.UL=$('#toolbar');this.Div.css({'overflow-y':'scroll','overflow-x':'hidden','padding-right':'4px'});}
else{this.UL.accordion('destroy');}
this.MarkupDirty=false;var html='';var canvases=[];for(var g=0;g<this.Groups.length;g++){html+="<div index='"+g+"'><a href='#' id='ToolboxGroupHeader"+g+"'>"+this.Groups[g].Label+"</a></div><div id='"+this.Groups[g].id+"'>";if(this.Groups[g].CustomHTMLHeader!=null)
html+=this.Groups[g].CustomHTMLHeader;for(var i=0;i<this.Groups[g].Items.length;i++){var id='toolbox_'+g+'_'+i;this.Groups[g].Items[i].CanvasId=id;var Class=eval(this.Groups[g].Items[i].ClassName);canvases.push({ToolGroupDivId:this.Groups[g].id,CanvasId:id,BlockClass:this.Groups[g].Items[i].ClassName});html+="<div class='canvasholder' id='holder"+id+"'></div>";}
if(this.Groups[g].CustomHTMLFooter!=null)
html+=this.Groups[g].CustomHTMLFooter;html+="</div>";}
var options={autoHeight:false,collapsible:true,change:function(event,ui){g_Client.Toolbox.SelectedGroup=ui.newHeader.attr('index');}};if(this.SelectedGroup!=null)
options.active=parseInt(this.SelectedGroup);if(is_ie6)
options.animated=false;this.UL.html(html).accordion(options);var SampleSize=50;for(var i=0;i<canvases.length;i++){$('#holder'+canvases[i].CanvasId).replaceWith($(document.createElement('canvas')).attr('id',canvases[i].CanvasId).attr('blockclass',canvases[i].BlockClass).attr({width:SampleSize,height:SampleSize}));}
var SampleInnerSize=42;var SampleBorder=(SampleSize-SampleInnerSize)/2;for(var g=0;g<this.Groups.length;g++){for(var i=0;i<this.Groups[g].Items.length;i++){var id='toolbox_'+g+'_'+i;var Class=eval(this.Groups[g].Items[i].ClassName);var Canvas=InitCanvas($('#'+id));var prop=this.Groups[g].Items[i].DefaultProperties();var Scale=Math.min(SampleInnerSize/Class.DefaultSize.w,SampleInnerSize/Class.DefaultSize.h);var w=Class.DefaultSize.w*Scale;var h=Class.DefaultSize.h*Scale;var Sample=new Class('');Sample.SetPropertyValue('BoundingBox',{x:SampleBorder+(SampleInnerSize-w)/2,y:SampleBorder+(SampleInnerSize-h)/2,w:w,h:h});for(var key in prop)
Sample.SetPropertyValue(key,prop[key]);Sample.RenderSample(Canvas);(function(Class,id,p){$('#'+id).tooltip({delay:0,track:true,showURL:false,bodyHandler:function(){return Class.Title;}}).draggable({helper:'original',revert:true,revertDuration:0,containment:is_ie6?'parent':false}).bind('dragstart',function(){g_Client.Log.Log('tb','Dragging class '+Class.ClassName);g_Client.Toolbox.DraggingBlockClass=Class;g_Client.Toolbox.DraggingBlockProperties=p();g_Client.Toolbox.DraggingBlockSize=Class.DefaultSize;}).bind('dragstop',function(){setTimeoutFunction(function(){g_Client.Log.Log('tb','Dragging class cleared');g_Client.Toolbox.DraggingBlockClass=null;g_Client.Viewport.Invalidate();g_Client.Toolbox.DroppingBlock=false;},1);});})(Class,id,this.Groups[g].Items[i].DefaultProperties);}}});}
LucidToolbox.prototype.ItemFromCanvasId=function(CanvasId){for(var g=0;g<this.Groups.length;g++){for(var i=0;i<this.Groups[g].Items.length;i++){if(this.Groups[g].Items[i].CanvasId==CanvasId)
return this.Groups[g].Items[i];}}
return null;}
LucidToolbox.prototype.AddGroup=function(Label,Before){var i;for(i=0;i<this.Groups.length;i++){if(this.Groups[i].Label==Before)
break;}
var New=new LucidToolboxGroup(Label);this.Groups.splice(i,0,New);this.MarkupDirty=true;return New;}
LucidToolbox.prototype.GetGroup=function(Label){for(var i=0;i<this.Groups.length;i++){if(this.Groups[i].Label==Label)
return this.Groups[i];}
return this.AddGroup(Label);}
LucidToolboxGroup.prototype.AddItem=function(ClassName,Before,DefaultProperties){var New=new LucidToolboxItem(ClassName,DefaultProperties);var i;for(i=0;i<this.Items.length;i++){if(this.Items[i].ClassName==Before)
break;}
this.Items.splice(i,0,New);g_Client.Toolbox.MarkupDirty=true;return New;}
LucidToolboxGroup.prototype.RemoveItem=function(CanvasId){for(var i=0;i<this.Items.length;i++){if(this.Items[i].CanvasId==CanvasId){this.Items.splice(i,1);g_Client.Toolbox.MarkupDirty=true;return true;}}
return false;}
LucidToolbox.prototype.ReRenderHelper=function(ClassName){var SampleSize=50;var SampleInnerSize=42;var SampleBorder=(SampleSize-SampleInnerSize)/2;for(var g=0;g<this.Groups.length;g++){for(var i=0;i<this.Groups[g].Items.length;i++){if(this.Groups[g].Items[i].ClassName==ClassName){var id='toolbox_'+g+'_'+i;var Class=eval(this.Groups[g].Items[i].ClassName);var Canvas=$('#'+id).get(0);$(Canvas).attr({width:SampleSize,height:SampleSize});var prop=this.Groups[g].Items[i].DefaultProperties();var Scale=Math.min(SampleInnerSize/Class.DefaultSize.w,SampleInnerSize/Class.DefaultSize.h);var w=Class.DefaultSize.w*Scale;var h=Class.DefaultSize.h*Scale;var Sample=new Class('');Sample.SetPropertyValue('BoundingBox',{x:SampleBorder+(SampleInnerSize-w)/2,y:SampleBorder+(SampleInnerSize-h)/2,w:w,h:h});for(var key in prop)
Sample.SetPropertyValue(key,prop[key]);Sample.RenderSample(Canvas);}}}}


var LucidViewport=function(){$('body').append('<div id="viewport"></div>');this.Div=$('#viewport').get(0);this.Canvas=new SuperCanvas(800,600);$(this.Div).append(this.Canvas.container);this.BackgroundLayer=new SuperCanvasLayer(0,0,800,600);this.UIHintLayer=new SuperCanvasLayer(0,0,800,600);this.Canvas.addLayer(this.BackgroundLayer);this.Canvas.addLayer(this.UIHintLayer);this.LastMouseX=0;this.LastMouseY=0;this.DrawLineMode=false;this.NoGrid=false;this.InputLocked=false;if(Configure.default_zoom==null)
Configure.default_zoom=.75;this.Scale=Configure.default_zoom;this.ScaleMode='normal';if(g_Client.User&&g_Client.User.preferences)
this.ScaleMode=g_Client.User.preferences.DefaultZoom;$(this.Div).css({overflow:'scroll'});this.Dirty=false;this.DirtyBackground=false;this._Tick=function(){if(g_Client.Viewport.Dirty||g_Client.Viewport.DirtyBackground){g_Client.Log.Log('Render','Dirty tick');g_Client.Viewport._UpdateZoom();var before=new Date();g_Client.Viewport.Render(g_Client.Viewport.DirtyBackground);var after=new Date();g_Client.Log.Log('Render',(after.getTime()-before.getTime())+'ms: Overall render');g_Client.Viewport.Dirty=false;g_Client.Viewport.DirtyBackground=false;g_Client.Thumbnail.MoveViewportRect();if(g_Client.TabControl.SelectedPanel!=null&&g_Client.TabControl.SelectedPanel.Name=='Properties')
g_Client.PropertiesTab.UpdateProperties();g_Client.Viewport.LastRenderTime=new Date();}};setInterval(this._Tick,20);$(this.Div).bind('scroll',function(){g_Client.Thumbnail.MoveViewportRect();});this.Canvas.bind('selectstart',function(){if(InlineEditor.CurrentId==null)
return false;});this.Canvas.bind('mousedown',function(e){g_Client.Log.Log('vpe','*MouseDown');if(g_Client.Viewport.SelectedPage!=null){var offset=$(g_Client.Viewport.Canvas.container).offset();var x=e.pageX-offset.left;var y=e.pageY-offset.top;if(g_Client.CanEdit()&&!this.InputLocked)
g_Client.Viewport._MouseDown(x/g_Client.Viewport.Scale,y/g_Client.Viewport.Scale,e);g_Client.Viewport._ReadOnlyMouseDown(x/g_Client.Viewport.Scale,y/g_Client.Viewport.Scale,e);}});this.Canvas.bind('mousemove',function(e){var offset=$(g_Client.Viewport.Canvas.container).offset();var x=e.pageX-offset.left;var y=e.pageY-offset.top;if(!g_Client.CanEdit()||this.InputLocked){g_Client.Viewport._SetReadOnlyCursor(x/g_Client.Viewport.Scale,y/g_Client.Viewport.Scale,e);return;}
if(g_Client.Viewport.SelectedPage!=null){g_Client.Log.Log('mm','MouseMove started');g_Client.Viewport._MouseMove(x/g_Client.Viewport.Scale,y/g_Client.Viewport.Scale,e);g_Client.Log.Log('mm','MouseMove done');}
if(g_Client.Toolbox.DroppingBlock==false){if(!is_safari)
g_Client.Viewport._Tick();}});this.Canvas.bind('mouseup',function(e){g_Client.Log.Log('vpe','*MouseUp');if(!g_Client.CanEdit()||this.InputLocked)return;if(g_Client.Viewport.SelectedPage!=null){var offset=$(g_Client.Viewport.Canvas.container).offset();var x=e.pageX-offset.left;var y=e.pageY-offset.top;g_Client.Viewport._MouseUp(x/g_Client.Viewport.Scale,y/g_Client.Viewport.Scale,e);}});this.Canvas.bind('dblclick',function(e){g_Client.Log.Log('vpe','*MouseUp');if(!g_Client.CanEdit()||this.InputLocked)return;if(g_Client.Viewport.SelectedPage!=null){var offset=$(g_Client.Viewport.Canvas.container).offset();var x=e.pageX-offset.left;var y=e.pageY-offset.top;g_Client.Viewport._DoubleClick(x/g_Client.Viewport.Scale,y/g_Client.Viewport.Scale,e);}});this.IsMouseDown=false;this.DragHit=null;this.DragAnchor=null;this.DragItems=[];this.Offsets={};this.DragLine=null;this.DragSelectLayer=new SuperCanvasLayer(0,0,1,1,0);this.DragSelectLayer.container.css({border:'1px solid black'});var me=this;g_Client.Document.HookActions(function(a){me.Invalidate();if(a.Action=='RemovePage'){if(me.SelectedPage!=null&&a.id==me.SelectedPage.id)
me.SelectFirstPage();}
else if(a.Action=='SetProperty'){if(me.SelectedPage!=null&&a.id==me.SelectedPage.id&&(a.Property=='FillColor'||a.Property=='Margin'))
me.InvalidateBackground();}});}
LucidViewport.prototype.EnterDrawLineMode=function(){if(!this.IsMouseDown){this.DrawLineMode=true;g_Client.LogAction('drawLineMode');}}
LucidViewport.prototype.SelectFirstPage=function(){var p=g_Client.Document.GetOrderedPages();if(p.length>0)
this.SelectPage(p[0]);}
LucidViewport.prototype._DoubleClick=function(x,y,e){g_Client.Log.Log('vpe','DoubleClick at '+x+','+y);if(e.button==left_button){var hit=this.SelectedPage.HitTest(x,y,null,e.altKey);if(hit!=null&&hit.Item&&hit.Item.IsBlock){this.SelectedPage.UnselectAll();$.map(this.SelectedPage.EverythingDownstream(hit.Item),function(item){g_Client.Viewport.SelectedPage.SelectItem(item);});}
else if(hit!=null&&hit.Item&&hit.Item.IsLine){var ta=hit.Item.GetPropertyValue('TextAreas');if(ta.Text==null){g_Client.Document.RunAction({Action:'SetProperty',id:hit.Item.id,Property:'TextAreas',Value:{Text:{Location:.5,Side:0,Value:'Text'}}});}
g_Client.Document._FindObject(hit.Item.id)._EditText('Text');g_Client.LogAction('addTextToLine');}}}
LucidViewport.prototype._ReadOnlyMouseDown=function(x,y,e){var DragHit=this.SelectedPage.HitTest(x,y,null,e.altKey);if(DragHit&&DragHit.ReadOnlyClick)
DragHit.ReadOnlyClick();}
LucidViewport.prototype._MouseDown=function(x,y,e){g_Client.Log.Log('vpe','MouseDown at '+x+','+y);if(e.button==left_button){if(this.IsMouseDown)
this._MouseUp(x,y,e);this.IsMouseDown=true;this.Offsets={};this.DraggingLineText=false;if(this.DrawLineMode){this.DragAnchor={x:x,y:y};this.DragLine=new LucidLine('DragLine');this.DragLine.SetPropertyValue('Shape','curve');this.DragLine.SetPropertyValue('LineWidth',g_Client.Document.GetPropertyValue('DefaultLineLineWidth'));this.DragLine.SetPropertyValue('LineColor',g_Client.Document.GetPropertyValue('DefaultLineLineColor'));this.DragLine.SetPropertyValue('StrokeStyle',g_Client.Document.GetPropertyValue('DefaultLineStrokeStyle'));this.DragLine.SetPropertyValue('Font',g_Client.Document.GetPropertyValue('DefaultFont'));this.DragLine.SetPropertyValue('Endpoint1',{x:x,y:y,Block:null,LinkX:null,LinkY:null});this.DragLine.SetPropertyValue('Endpoint2',{x:x,y:y,Block:null,LinkX:null,LinkY:null});this.DragHit={Action:'linkpoint',Item:this.DragLine};this.DrawLineMode=false;}
else{this.DragHit=this.SelectedPage.HitTest(x,y,null,e.altKey);if(this.DragHit!=null&&this.DragHit.Action=='text'){if(e.shiftKey&&this.DragHit.Item.IsLine)
this.DraggingLineText=true;else
this.DragHit.Click();}
else if(this.DragHit!=null){this.DragAnchor={x:x,y:y};if(this.DragHit.Item.Selected){if(e.ctrlKey)
this.SelectedPage.UnselectItem(this.DragHit.Item);this.DragItems=this.SelectedPage.GetSelection();}
else{if(!e.ctrlKey&&!e.shiftKey)
this.SelectedPage.UnselectAll();this.SelectedPage.SelectItem(this.DragHit.Item);this.DragItems=this.SelectedPage.GetSelection();}
if(this.DragHit.Action=='linkpoint'){this.DragLine=new LucidLine('DragLine');this.DragLine.SetPropertyValue('Shape',g_Client.Document.GetPropertyValue('DefaultLineShape'));this.DragLine.SetPropertyValue('LineWidth',g_Client.Document.GetPropertyValue('DefaultLineLineWidth'));this.DragLine.SetPropertyValue('LineColor',g_Client.Document.GetPropertyValue('DefaultLineLineColor'));this.DragLine.SetPropertyValue('StrokeStyle',g_Client.Document.GetPropertyValue('DefaultLineStrokeStyle'));this.DragLine.SetPropertyValue('Font',g_Client.Document.GetPropertyValue('DefaultFont'));this.DragLine.SetPropertyValue('Endpoint1',{x:this.DragHit.Item.RelativeX(this.DragHit.x),y:this.DragHit.Item.RelativeY(this.DragHit.y),Block:this.DragHit.Item.id,LinkX:this.DragHit.x,LinkY:this.DragHit.y});this.DragLine.SetPropertyValue('Endpoint2',{x:this.DragHit.Item.RelativeX(this.DragHit.x),y:this.DragHit.Item.RelativeY(this.DragHit.y),Block:null,LinkX:null,LinkY:null});}}
else{g_Client.Log.Log('vpe','Starting drag rectangle');this.DragItems=[];this.DragAnchor={x:x,y:y};}}}
else if(e.button==right_button){var Hit=this.SelectedPage.HitTest(x,y,null,e.altKey);if(Hit!=null){if(!Hit.Item.Selected){this.SelectedPage.UnselectAll();this.SelectedPage.SelectItem(Hit.Item);}}
else{this.SelectedPage.UnselectAll();}}}
LucidViewport.prototype._SetReadOnlyCursor=function(x,y,e){var Hit=this.SelectedPage.HitTest(x,y,null,e.altKey);if(Hit&&Hit.ReadOnlyClick)
this.Canvas.cursor(Hit.Cursor);else
this.Canvas.cursor('default');}
LucidViewport.prototype._MouseMove=function(x,y,e){this.LastMouseX=x;this.LastMouseY=y;var AutoScroll=function(){var ScrollTop=g_Client.Viewport.Div.scrollTop;var ScrollLeft=g_Client.Viewport.Div.scrollLeft;var Width=g_Client.Viewport.Div.offsetWidth;var Height=g_Client.Viewport.Div.offsetHeight;var ScrollDist=75;if(x*g_Client.Viewport.Scale<ScrollLeft+ScrollDist)
g_Client.Viewport.Div.scrollLeft-=10;if(y*g_Client.Viewport.Scale<ScrollTop+ScrollDist)
g_Client.Viewport.Div.scrollTop-=10;if(x*g_Client.Viewport.Scale>ScrollLeft+Width-ScrollDist)
g_Client.Viewport.Div.scrollLeft+=10;if(y*g_Client.Viewport.Scale>ScrollTop+Height-ScrollDist)
g_Client.Viewport.Div.scrollTop+=10;}
if(g_Client.Toolbox.DraggingBlockClass!=null){AutoScroll();this.DragBlockX=x;this.DragBlockY=y;this.Invalidate();}
else if(this.DrawLineMode){this.Canvas.cursor('crosshair');}
else if(this.DraggingLineText){this.Canvas.cursor('move');}
else{var Hit=this.SelectedPage.HitTest(x,y,null,e.altKey);if(Hit!=null&&!this.IsMouseDown){if(Hit.Action=='move'||Hit.Action=='dragline')
this.Canvas.cursor('move');else if(Hit.Action=='se')
this.Canvas.cursor('se-resize');else if(Hit.Action=='sw')
this.Canvas.cursor('sw-resize');else if(Hit.Action=='ne')
this.Canvas.cursor('ne-resize');else if(Hit.Action=='nw')
this.Canvas.cursor('nw-resize');else if(Hit.Action=='slidex')
this.Canvas.cursor('e-resize');else if(Hit.Action=='slidey')
this.Canvas.cursor('n-resize');else if(Hit.Action=='linkpoint')
this.Canvas.cursor('crosshair');else if(Hit.Action=='text'){if(Hit.Item.IsLine&&e.shiftKey)
this.Canvas.cursor('move');else
this.Canvas.cursor(Hit.Cursor);}
else
this.Canvas.cursor('default');}
else{this.Canvas.cursor('default');}}
if(this.IsMouseDown){AutoScroll();if(this.DragHit!=null){var bb=this.DragHit.Item.GetPropertyValue('BoundingBox');if(e.shiftKey){if(this.DragHit.Action=='se'||this.DragHit.Action=='nw'){var p=ClosestPointOnLineSegment(x,y,bb.x,bb.y,bb.x+bb.w,bb.y+bb.h,true);x=p.x;y=p.y;}
else if(this.DragHit.Action=='sw'||this.DragHit.Action=='ne'){var p=ClosestPointOnLineSegment(x,y,bb.x+bb.w,bb.y,bb.x,bb.y+bb.h,true);x=p.x;y=p.y;}}
if(this.DraggingLineText){var t=this.DragHit.Item.ClosestRelativePoint(x,y,true);var ta=this.DragHit.Item.GetPropertyValue('TextAreas');ta=ta[this.DragHit.Key];ta.Location=t;this.DragHit.Item._PlaceText(this.Canvas,this.DragHit.Key,ta,this.DragHit.Item.GetBoundingBox());}
else if(this.DragHit.Action=='move'){for(var i=0;i<this.DragItems.length;i++){this.Offsets[this.DragItems[i].id]={x:x-this.DragAnchor.x,y:y-this.DragAnchor.y,w:0,h:0};}}
else if(this.DragHit.Action=='se'){this.Offsets[this.DragHit.Item.id]={x:0,y:0,w:Math.max(x,bb.x+40)-this.DragAnchor.x,h:Math.max(y,bb.y+40)-this.DragAnchor.y};}
else if(this.DragHit.Action=='sw'){this.Offsets[this.DragHit.Item.id]={w:-(Math.min(x,bb.x+bb.w-40)-this.DragAnchor.x),x:Math.min(x,bb.x+bb.w-40)-this.DragAnchor.x,h:Math.max(y,bb.y+40)-this.DragAnchor.y,y:0};}
else if(this.DragHit.Action=='nw'){this.Offsets[this.DragHit.Item.id]={w:-(Math.min(x,bb.x+bb.w-40)-this.DragAnchor.x),x:Math.min(x,bb.x+bb.w-40)-this.DragAnchor.x,h:-(Math.min(y,bb.y+bb.h-40)-this.DragAnchor.y),y:Math.min(y,bb.y+bb.h-40)-this.DragAnchor.y};}
else if(this.DragHit.Action=='ne'){this.Offsets[this.DragHit.Item.id]={w:Math.max(x,bb.x+40)-this.DragAnchor.x,h:-(Math.min(y,bb.y+bb.h-40)-this.DragAnchor.y),y:Math.min(y,bb.y+bb.h-40)-this.DragAnchor.y,x:0};}
else if(this.DragHit.Action=='linkpoint'||this.DragHit.Action=='dragline'){if(this.DragHit.Action=='linkpoint'){var line=this.DragLine;var prop='Endpoint2';}
else{var line=this.DragHit.Item;var prop=this.DragHit.Property;}
Hit=this.SelectedPage.HitTest(x,y,line,e.altKey);if(Hit!=null&&Hit.Action=='linkpoint'&&(Hit.Item!=this.DragHit.Item||Hit.x!=this.DragHit.x||Hit.y!=this.DragHit.y)){line.SetPropertyValue(prop,{x:Hit.Item.RelativeX(Hit.x),y:Hit.Item.RelativeY(Hit.y),Block:Hit.Item.id,LinkX:Hit.x,LinkY:Hit.y});}
else{line.SetPropertyValue(prop,{x:x,y:y,Block:null,LinkX:null,LinkY:null});}}
else if(this.DragHit.Action=='slidex'){var p=CopyObject(this.DragHit.Points);p[this.DragHit.Index].x=this.SelectedPage.SnapToGrid(Math.min(this.DragHit.Max,Math.max(this.DragHit.Min,x)),2);p[this.DragHit.Index+1].x=this.SelectedPage.SnapToGrid(Math.min(this.DragHit.Max,Math.max(this.DragHit.Min,x)),2);this.DragHit.Item.SetPropertyValue('Points',p);}
else if(this.DragHit.Action=='slidey'){var p=CopyObject(this.DragHit.Points);p[this.DragHit.Index].y=this.SelectedPage.SnapToGrid(Math.min(this.DragHit.Max,Math.max(this.DragHit.Min,y)),2);p[this.DragHit.Index+1].y=this.SelectedPage.SnapToGrid(Math.min(this.DragHit.Max,Math.max(this.DragHit.Min,y)),2);this.DragHit.Item.SetPropertyValue('Points',p);}
this.Invalidate();}
else{g_Client.Log.Log('vpe','Dragging selection rectangle');this.Canvas.addLayer(this.DragSelectLayer);this.DragSelectLayer.move(Math.min(x,this.DragAnchor.x)*g_Client.Viewport.Scale,Math.min(y,this.DragAnchor.y)*g_Client.Viewport.Scale,Math.abs(x-this.DragAnchor.x)*g_Client.Viewport.Scale,Math.abs(y-this.DragAnchor.y)*g_Client.Viewport.Scale);}}}
LucidViewport.prototype._AttachCoincidentLinesToBlock=function(block){var Tolerance=this.SelectedPage.GetPropertyValue('GridSpacing');this.SelectedPage.EachLine(function(){var ep1=this.GetPropertyValue('Endpoint1',true);var ep2=this.GetPropertyValue('Endpoint2',true);for(var i=0;i<block.LinkPoints.length;i++){var x=block.RelativeX(block.LinkPoints[i].x);var y=block.RelativeY(block.LinkPoints[i].y);if(Math.abs(x-ep1.x)<Tolerance&&Math.abs(y-ep1.y)<Tolerance&&(ep1.Block==null||g_Client.Document._FindObject(ep1.Block)==null)){g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'Endpoint1',Value:{x:x,y:y,Block:block.id,LinkX:block.LinkPoints[i].x,LinkY:block.LinkPoints[i].y}});}
if(Math.abs(x-ep2.x)<Tolerance&&Math.abs(y-ep2.y)<Tolerance&&(ep2.Block==null||g_Client.Document._FindObject(ep2.Block)==null)){g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'Endpoint2',Value:{x:x,y:y,Block:block.id,LinkX:block.LinkPoints[i].x,LinkY:block.LinkPoints[i].y}});}}});}
LucidViewport.prototype._MouseUp=function(x,y,e){g_Client.Log.Log('vpe','MouseUp at '+x+','+y);var PageSize=this.SelectedPage.GetPropertyValue('Size');var TotalDistanceMoved=this.DragAnchor?Math.sqrt((this.DragAnchor.x-x)*(this.DragAnchor.x-x)+(this.DragAnchor.y-y)*(this.DragAnchor.y-y)):0;if(g_Client.Toolbox.DraggingBlockClass!=null){if(x>0&&y>0&&x<PageSize.w&&y<PageSize.h){g_Client.Toolbox.DroppingBlock=true;g_Client.Document.StartUndoBatch();var a={Action:'CreateBlock',Class:new g_Client.Toolbox.DraggingBlockClass('',{}).Class,Properties:{ZOrder:this.SelectedPage.MaxProperty('ZOrder',0)+1,LineWidth:g_Client.Document.GetPropertyValue('DefaultBlockLineWidth'),LineColor:g_Client.Document.GetPropertyValue('DefaultBlockLineColor'),FillColor:g_Client.Document.GetPropertyValue('DefaultBlockFillColor'),Font:g_Client.Document.GetPropertyValue('DefaultFont'),BoundingBox:this.SelectedPage.SnapToGrid({x:x-g_Client.Toolbox.DraggingBlockSize.w/2,y:y-g_Client.Toolbox.DraggingBlockSize.h/2,w:g_Client.Toolbox.DraggingBlockSize.w,h:g_Client.Toolbox.DraggingBlockSize.h})},Page:this.SelectedPage.id};for(var key in g_Client.Toolbox.DraggingBlockProperties)
a.Properties[key]=g_Client.Toolbox.DraggingBlockProperties[key];if(g_Client.Document.RunAction(a)){var block=this.SelectedPage.Blocks[a.id];block.OnCreate();this._AttachCoincidentLinesToBlock(block);this.SelectedPage.UnselectAll();this.SelectedPage.SelectItem(g_Client.Document._FindObject(a.id));}
g_Client.Document.EndUndoBatch();}
g_Client.Toolbox.DraggingBlockClass=null;}
else if(e.button==left_button){if(!this.IsMouseDown)
return;if(this.DragHit!=null){this._MouseMove(x,y,e);if(this.DraggingLineText){var t=this.DragHit.Item.ClosestRelativePoint(x,y,true);var val={};val[this.DragHit.Key]={Location:t};g_Client.Document.RunAction({Action:'SetProperty',id:this.DragHit.Item.id,Property:'TextAreas',Value:val});this.DraggingLineText=false;}
else if(this.DragHit.Action=='move'){g_Client.Document.StartUndoBatch();this.MoveItems(this.DragItems,this.Offsets);g_Client.Document.EndUndoBatch();}
else if(this.DragHit.Action=='se'||this.DragHit.Action=='sw'||this.DragHit.Action=='nw'||this.DragHit.Action=='ne'){var Offset=this.Offsets[this.DragHit.Item.id];if(this._IsSignificantOffset(Offset)){var bb=this.DragHit.Item.GetPropertyValue('BoundingBox');g_Client.Document.RunAction({Action:'SetProperty',id:this.DragHit.Item.id,Property:'BoundingBox',Value:this.SelectedPage.SnapToGrid({x:Offset.x+bb.x,y:Offset.y+bb.y,w:Offset.w+bb.w,h:Offset.h+bb.h})});}}
else if(this.DragHit.Action=='linkpoint'&&TotalDistanceMoved>20){var ep1=this.DragLine.GetPropertyValue('Endpoint1');var ep2=this.DragLine.GetPropertyValue('Endpoint2');if(ep1.Block==null){ep1.x=this.SelectedPage.SnapToGrid(ep1.x);ep1.y=this.SelectedPage.SnapToGrid(ep1.y);this.DragLine.SetPropertyValue('Endpoint1',ep1);}
if(ep2.Block==null){ep2.x=this.SelectedPage.SnapToGrid(ep2.x);ep2.y=this.SelectedPage.SnapToGrid(ep2.y);this.DragLine.SetPropertyValue('Endpoint2',ep2);}
if(Math.abs(ep1.x-ep2.x)>10||Math.abs(ep1.y-ep2.y)>10){var PromptNextBlock=1;if(g_Client.User&&g_Client.User.preferences)
PromptNextBlock=g_Client.User.preferences.PromptNextBlock;PromptNextBlock=PromptNextBlock==1&&ep1.Block!=null&&this.SelectedPage.Blocks[ep1.Block]!=null;PromptNextBlock=PromptNextBlock&&(ep2.Block==null||this.SelectedPage.Blocks[ep2.Block]==null);if(PromptNextBlock){var classes=LucidBlock.NextBlockClasses[this.SelectedPage.Blocks[ep1.Block].Class];PromptNextBlock=classes&&classes.length>0;}
var a={Action:'CreateLine',Page:this.SelectedPage.id,Properties:this.DragLine.GetAllProperties()};a.Properties.ZOrder=this.SelectedPage.MaxProperty('ZOrder',0)+1;g_Client.Document.StartUndoBatch();g_Client.Document.RunAction(a);if(ep1.Block!=null&&this.SelectedPage.Blocks[ep1.Block]!=null){var count=0;this.SelectedPage.EachLine(function(){if(this.GetPropertyValue('Endpoint1').Block==ep1.Block)
count++;});this.SelectedPage.Blocks[ep1.Block].LineDrawn(a.id,count,!PromptNextBlock);}
g_Client.Document.EndUndoBatch();if(PromptNextBlock){function PlaceNextBlock(ClassName,LineId){g_Client.Log.Log('b',ClassName);var Class=eval(ClassName);var bb,LinkX,LinkY;var angle=Math.atan2(ep2.y-ep1.y,ep2.x-ep1.x);if(angle>=-Math.PI/4&&angle<=Math.PI/4){bb={x:ep2.x,y:ep2.y-Class.DefaultSize.h/2,w:Class.DefaultSize.w,h:Class.DefaultSize.h};LinkX=0;LinkY=0.5;}
else if(angle>=Math.PI*1/4&&angle<=Math.PI*3/4){bb={x:ep2.x-Class.DefaultSize.w/2,y:ep2.y,w:Class.DefaultSize.w,h:Class.DefaultSize.h};LinkX=.5;LinkY=0;}
else if(angle>=Math.PI*3/4||angle<=-Math.PI*3/4){bb={x:ep2.x-Class.DefaultSize.w,y:ep2.y-Class.DefaultSize.h/2,w:Class.DefaultSize.w,h:Class.DefaultSize.h};LinkX=1;LinkY=0.5;}
else{bb={x:ep2.x-Class.DefaultSize.w/2,y:ep2.y-Class.DefaultSize.h,w:Class.DefaultSize.w,h:Class.DefaultSize.h};LinkX=.5;LinkY=1;}
var a={Action:'CreateBlock',Class:ClassName,Properties:{ZOrder:g_Client.Viewport.SelectedPage.MaxProperty('ZOrder',0)+1,LineWidth:g_Client.Document.GetPropertyValue('DefaultBlockLineWidth'),LineColor:g_Client.Document.GetPropertyValue('DefaultBlockLineColor'),FillColor:g_Client.Document.GetPropertyValue('DefaultBlockFillColor'),Font:g_Client.Document.GetPropertyValue('DefaultFont'),BoundingBox:bb},Page:g_Client.Viewport.SelectedPage.id};g_Client.Document.StartUndoBatch();if(g_Client.Document.RunAction(a)){var block=g_Client.Document._FindObject(a.id);var lp=block.ClosestLinkPoint(ep2.x,ep2.y);g_Client.Document.RunAction({Action:'SetProperty',id:LineId,Property:'Endpoint2',Value:{x:bb.x+bb.w*lp.x,y:bb.y+bb.h*lp.y,Block:a.id,LinkX:lp.x,LinkY:lp.y}});g_Client.Document._FindObject(a.id).OnCreate();}
g_Client.Document.EndUndoBatch();}
if(classes.length==1){PlaceNextBlock(classes[0],a.id);}
else{var helpers=new StringBuilder();for(var i=0;i<classes.length;i++)
helpers.append("<div class='canvasholder' ClassName='"+classes[i]+"' id='popup_"+i+"'></div>");var SampleSize=25;var SampleInnerSize=23;var SampleBorder=(SampleSize-SampleInnerSize)/2;var SampleScale=2;$.popupMenu({x:e.pageX,y:e.pageY,content:helpers.toString(),css:{width:((SampleSize+2)*3)+'px',height:((SampleSize+2)*Math.ceil(classes.length/3))+'px'}});$.popupMenu.div.find('.canvasholder').each(function(i){var Canvas=$(document.createElement('canvas')).attr({width:SampleSize,height:SampleSize});$(this).append(Canvas);$(this).css({width:SampleSize+'px',height:SampleSize+'px','float':'left',border:'1px solid white'});if(!is_ie6){$(this).hover(function(){$(this).css({border:''}).addClass('ui-state-default');},function(){$(this).removeClass('ui-state-default').css({border:'1px solid white'});});}
if((i%3)==0)
$(this).css({clear:'left'});var Class=eval(classes[i]);Canvas=InitCanvas(Canvas);var Scale=Math.min(SampleInnerSize/Class.DefaultSize.w,SampleInnerSize/Class.DefaultSize.h);var w=Class.DefaultSize.w*Scale;var h=Class.DefaultSize.h*Scale;var Sample=new Class('');Sample.SetPropertyValue('BoundingBox',{x:SampleScale*(SampleBorder+(SampleInnerSize-w)/2),y:SampleScale*(SampleBorder+(SampleInnerSize-h)/2),w:SampleScale*w,h:SampleScale*h});Sample.RenderSample(Canvas,1/SampleScale);$(Canvas).tooltip({delay:0,track:true,showURL:false,bodyHandler:function(){return Class.Title;}});$(this).find('*').andSelf().click(function(e){e.stopPropagation();$.popupMenu.hide();PlaceNextBlock(Sample.Class,a.id);});});}}}}
else if(this.DragHit.Action=='dragline'){var ep=this.DragHit.Item.GetPropertyValue(this.DragHit.Property);if(ep.Block==null){ep.x=this.SelectedPage.SnapToGrid(ep.x);ep.y=this.SelectedPage.SnapToGrid(ep.y);this.DragHit.Item.SetPropertyValue(this.DragHit.Property,ep);}
this.DragHit.Item.SetPropertyValue(this.DragHit.Property,this.DragHit.Value);if(TotalDistanceMoved>5){g_Client.Document.RunAction({Action:'SetProperty',id:this.DragHit.Item.id,Property:this.DragHit.Property,Value:ep});}}
else if(this.DragHit.Action=='slidex'||this.DragHit.Action=='slidey'){var p=this.DragHit.Item.GetPropertyValue('Points');this.DragHit.Item.SetPropertyValue('Points',this.DragHit.Points);g_Client.Document.RunAction({Action:'SetProperty',id:this.DragHit.Item.id,Property:'Points',Value:LucidLine.RemoveExcessPoints(p)});}
this.DragItems=[];this.DragAnchor=null;this.DragHit=false;this.DragLine=null;this.Invalidate();}
else{this.Canvas.removeLayer(this.DragSelectLayer);if(!e.ctrlKey&&!e.shiftKey)
this.SelectedPage.UnselectAll();if(Math.abs(x-this.DragAnchor.x)>5||Math.abs(y-this.DragAnchor.y)>5){var da=this.DragAnchor;this.SelectedPage.EachItem(function(){if(this.RectTest(Math.min(x,da.x),Math.min(y,da.y),Math.max(x,da.x),Math.max(y,da.y)))
g_Client.Viewport.SelectedPage.SelectItem(this);});this.Invalidate();}}
this.IsMouseDown=false;}}
LucidViewport.prototype.MoveItems=function(Items,Offsets){for(var i=0;i<Items.length;i++){var Offset=Offsets[Items[i].id];if(this._IsSignificantOffset(Offset)){if(Items[i].IsBlock){var bb=Items[i].GetPropertyValue('BoundingBox');g_Client.Document.RunAction({Action:'SetProperty',id:Items[i].id,Property:'BoundingBox',Value:this.SelectedPage.SnapToGrid({x:Offset.x+bb.x,y:Offset.y+bb.y,w:Offset.w+bb.w,h:Offset.h+bb.h})});this._AttachCoincidentLinesToBlock(Items[i]);}
else if(Items[i].IsLine){var ep1=Items[i].GetPropertyValue('Endpoint1');if(ep1.Block==null||this.SelectedPage.Blocks[ep1.Block]==null){g_Client.Document.RunAction({Action:'SetProperty',id:Items[i].id,Property:'Endpoint1',Value:{Block:null,LinkX:null,LinkY:null,x:this.SelectedPage.SnapToGrid(ep1.x+Offset.x),y:this.SelectedPage.SnapToGrid(ep1.y+Offset.y)}});}
var ep2=Items[i].GetPropertyValue('Endpoint2');if(ep2.Block==null||this.SelectedPage.Blocks[ep2.Block]==null){g_Client.Document.RunAction({Action:'SetProperty',id:Items[i].id,Property:'Endpoint2',Value:{Block:null,LinkX:null,LinkY:null,x:this.SelectedPage.SnapToGrid(ep2.x+Offset.x),y:this.SelectedPage.SnapToGrid(ep2.y+Offset.y)}});}
if(Items[i].GetPropertyValue('Shape')=='curve'){var cp=Items[i].GetPropertyValue('ControlPoints');if(cp.middle){for(var cpi=0;cpi<cp.middle.length;cpi++){cp.middle[cpi].x+=this.SelectedPage.SnapToGrid(this.Offsets[Items[i].id].x);cp.middle[cpi].y+=this.SelectedPage.SnapToGrid(this.Offsets[Items[i].id].y);}}
g_Client.Document.RunAction({Action:'SetProperty',id:Items[i].id,Property:'ControlPoints',Value:cp});}}}}}
LucidViewport.prototype.SelectPageSegment=function(message,save){$('#selectsegmentoverlay').remove();$(this.Div).append('<div id="selectsegmentoverlay"><span>'+message+'</span></div>');$('#selectsegmentoverlay').css({position:'absolute',left:0,top:0,width:this.Canvas.width+'px',height:this.Canvas.height+'px',background:'#ffffaa','z-index':10000}).fadeTo(1000,.5);$('#selectsegmentoverlay span').css({position:'fixed',font:'bold 24px arial',margin:'4px',cursor:'default'});var keydown=null;keydown=function(e){if(e.which==27||e.keyCode==27){$('#selectsegmentoverlay').remove();$(document).unbind('keydown',keydown);}};$(document).keydown(keydown);g_Client.Document.OnNextAction(function(){$('#selectsegmentoverlay').remove();});var me=this;var Anchor=null;$('#selectsegmentoverlay,#selectsegmentoverlay').mousedown(function(e){var offset=$(me.Canvas.container).offset();var x=e.pageX-offset.left;var y=e.pageY-offset.top;Anchor={x:x,y:y};return false;}).mouseup(function(e){var offset=$(me.Canvas.container).offset();var x=e.pageX-offset.left;var y=e.pageY-offset.top;if(Anchor!=null){$('#selectsegmentoverlay').remove();save(Math.round(Math.min(x,Anchor.x)/me.Scale),Math.round(Math.min(y,Anchor.y)/me.Scale),Math.round(Math.abs(x-Anchor.x)/me.Scale),Math.round(Math.abs(y-Anchor.y)/me.Scale));}
Anchor=null;$('#selectsegmentbox').remove();return false;}).mousemove(function(e){var offset=$(me.Canvas.container).offset();var x=e.pageX-offset.left;var y=e.pageY-offset.top;if(Anchor!=null){var ScrollTop=me.Div.scrollTop;var ScrollLeft=me.Div.scrollLeft;var Width=me.Div.offsetWidth;var Height=me.Div.offsetHeight;var ScrollDist=75;if(x<ScrollLeft+ScrollDist)
me.Div.scrollLeft-=10;if(y<ScrollTop+ScrollDist)
me.Div.scrollTop-=10;if(x>ScrollLeft+Width-ScrollDist)
me.Div.scrollLeft+=10;if(y>ScrollTop+Height-ScrollDist)
me.Div.scrollTop+=10;$('#selectsegmentbox').remove();$('#selectsegmentoverlay').append('<div id="selectsegmentbox"></div>');$('#selectsegmentbox').css({position:'absolute',left:Math.min(x,Anchor.x)+'px',top:Math.min(y,Anchor.y)+'px',width:Math.abs(x-Anchor.x)+'px',height:Math.abs(y-Anchor.y)+'px',border:'2px solid black',background:'#aaaaaa'});}
return false;});}
LucidViewport.prototype.ZoomIn=function(){this.Scale*=1.1;this.ScaleMode='normal';this.Invalidate();this.InvalidateBackground();}
LucidViewport.prototype.ZoomOut=function(){this.Scale/=1.1;this.ScaleMode='normal';this.Invalidate();this.InvalidateBackground();}
LucidViewport.prototype.ZoomNormal=function(){this.Scale=Configure.default_zoom;this.ScaleMode='normal';this.Invalidate();this.InvalidateBackground();}
LucidViewport.prototype.ZoomWidth=function(){this.ScaleMode='width';this.Invalidate();this.InvalidateBackground();}
LucidViewport.prototype.ZoomPage=function(){this.ScaleMode='page';this.Invalidate();this.InvalidateBackground();}
LucidViewport.prototype._UpdateZoom=function(){if(this.SelectedPage==null)
return;var OldScale=this.Scale;if(this.ScaleMode=='width')
this.Scale=this.Div.clientWidth/this.SelectedPage.GetPropertyValue('Size').w;else if(this.ScaleMode=='page'){this.Scale=Math.min(this.Div.clientWidth/this.SelectedPage.GetPropertyValue('Size').w,this.Div.clientHeight/this.SelectedPage.GetPropertyValue('Size').h);}
if(this.Scale!=OldScale){this.Invalidate();this.InvalidateBackground();}}
LucidViewport.BlockClipboardGetAction=function(Page,Offset,o){this.LastAction=CopyObject(this.Action);this.LastAction.Page=Page.id;this.LastAction.Properties.BoundingBox.x+=Offset.x;this.LastAction.Properties.BoundingBox.y+=Offset.y;this.LastAction.Properties.ZOrder=Page.MaxProperty('ZOrder',0)+1;return this.LastAction;}
LucidViewport.LineClipboardGetAction=function(Page,Offset,o){this.LastAction=CopyObject(this.Action);this.LastAction.Page=Page.id;var p=this.LastAction.Properties.Points;for(var i=0;i<p.length;i++){p[i].x+=Offset.x;p[i].y+=Offset.y;}
this.LastAction.Properties.Endpoint1.x+=Offset.x;this.LastAction.Properties.Endpoint1.y+=Offset.y;this.LastAction.Properties.Endpoint2.x+=Offset.x;this.LastAction.Properties.Endpoint2.y+=Offset.y;this.LastAction.Properties.ZOrder=Page.MaxProperty('ZOrder',0)+1;if(this.LastAction.Properties.Endpoint1.Block!=null){var found=false;for(var i=0;i<o.length;i++){if(o[i].id==this.LastAction.Properties.Endpoint1.Block){this.LastAction.Properties.Endpoint1.Block=o[i].LastAction.id;found=true;break;}}
if(!found){delete this.LastAction.Properties.Endpoint1.Block;delete this.LastAction.Properties.Endpoint1.LinkX;delete this.LastAction.Properties.Endpoint1.LinkY;}}
if(this.LastAction.Properties.Endpoint2.Block!=null){var found=false;for(var i=0;i<o.length;i++){if(o[i].id==this.LastAction.Properties.Endpoint2.Block){this.LastAction.Properties.Endpoint2.Block=o[i].LastAction.id;found=true;break;}}
if(!found){delete this.LastAction.Properties.Endpoint2.Block;delete this.LastAction.Properties.Endpoint2.LinkX;delete this.LastAction.Properties.Endpoint2.LinkY;}}
return this.LastAction;}
LucidViewport.prototype.CopySelectionToClipboard=function(){if(this.SelectedPage==null)return;var s=this.SelectedPage.GetSelection();if(s.length==0)
return;this.ClipboardData=this.GetClipboardData(this.SelectedPage,s);$.ajax({type:"POST",url:'/users/setClipboard',data:'data[User][clipboard]='+encodeURIComponent(JSON.stringify(this.ClipboardData)),success:function(msg){}});}
LucidViewport.prototype.GetClipboardData=function(Page,s){var Size={minx:null,miny:null,maxx:null,maxy:null};var o=[];for(var i=0;i<s.length;i++){var bb=s[i].GetBoundingBox();if(Size.minx==null||bb.x<Size.minx)Size.minx=bb.x;if(Size.maxx==null||bb.x+bb.w>Size.maxx)Size.maxx=bb.x+bb.w;if(Size.miny==null||bb.y<Size.miny)Size.miny=bb.y;if(Size.maxy==null||bb.y+bb.h>Size.maxy)Size.maxy=bb.y+bb.h;}
for(var i=0;i<s.length;i++){if(s[i].IsBlock){o.push({id:s[i].id,IsBlock:true,Action:{Action:'CreateBlock',Class:s[i].Class,Properties:s[i].GetAllProperties()},GetAction:'LucidViewport.BlockClipboardGetAction'});}
else if(s[i].IsLine){o.push({id:s[i].id,IsLine:true,Action:{Action:'CreateLine',Properties:s[i].GetAllProperties()},GetAction:'LucidViewport.LineClipboardGetAction'});}}
return{Objects:o,Base:{x:(Size.maxx+Size.minx)/2,y:(Size.maxy+Size.miny)/2},Size:{w:Size.maxx-Size.minx,h:Size.maxy-Size.miny},Plugins:CopyObject(g_Client.Document.AllPlugins)};}
LucidViewport.prototype.PasteFromClipboard=function(x,y){if(this.SelectedPage==null)return;if(this.ClipboardData==null)return;this.PasteClipboardData(this.SelectedPage,this.ClipboardData,x,y);}
LucidViewport.prototype.PasteClipboardData=function(Page,data,x,y){var Offset=Page.SnapToGrid({x:x-data.Base.x,y:y-data.Base.y});g_Client.Document.StartUndoBatch();for(var i=0;i<data.Plugins.length;i++){var url=data.Plugins[i];if(arrayIndexOf(g_Client.Document.AllPlugins,url)==-1){$.ajax({async:false,type:'GET',url:url,success:function(msg){g_Client.Document.RunAction({Action:'LoadPlugin',URL:url,Code:msg});},error:function(){}});}}
for(var i=0;i<data.Objects.length;i++){var o=data.Objects[i];if(o.IsBlock)
g_Client.Document.RunAction(eval(o.GetAction).call(o,Page,Offset,data.Objects));}
for(var i=0;i<data.Objects.length;i++){var o=data.Objects[i];if(o.IsLine)
g_Client.Document.RunAction(eval(o.GetAction).call(o,Page,Offset,data.Objects));}
Page.MoveItemsIntoPageSize();g_Client.Document.EndUndoBatch();Page.UnselectAll();for(var i=0;i<data.Objects.length;i++){var o=data.Objects[i];Page.SelectItem(g_Client.Document._FindObject(o.LastAction.id));}}
LucidViewport.prototype.ViewableArea=function(){return{x:this.Div.scrollLeft/g_Client.Viewport.Scale,y:this.Div.scrollTop/g_Client.Viewport.Scale,w:Math.min(this.Div.offsetWidth/g_Client.Viewport.Scale,this.SelectedPage.GetPropertyValue('Size').w),h:Math.min(this.Div.offsetHeight/g_Client.Viewport.Scale,this.SelectedPage.GetPropertyValue('Size').h)}}
LucidViewport.prototype.SendSelectionToBack=function(){var MaxSelected=this.SelectedPage.MaxSelectedProperty('ZOrder');var Min=this.SelectedPage.MinProperty('ZOrder');var Delta=(Min-1)-MaxSelected;g_Client.Document.StartUndoBatch();this.SelectedPage.EachItem(function(){if(this.Selected){g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'ZOrder',Value:this.GetPropertyValue('ZOrder')+Delta});}});g_Client.Document.EndUndoBatch();this.Invalidate();}
LucidViewport.prototype.BringSelectionToFront=function(){var MinSelected=this.SelectedPage.MinSelectedProperty('ZOrder');var Max=this.SelectedPage.MaxProperty('ZOrder',0);var Delta=(Max+1)-MinSelected;g_Client.Document.StartUndoBatch();this.SelectedPage.EachItem(function(){if(this.Selected){g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'ZOrder',Value:this.GetPropertyValue('ZOrder')+Delta});}});g_Client.Document.EndUndoBatch();this.Invalidate();}
LucidViewport.prototype.DeleteSelection=function(){g_Client.Document.StartUndoBatch();this.SelectedPage.EachBlock(function(){if(this.Selected){g_Client.Document.RunAction({Action:'RemoveBlock',id:this.id});}});this.SelectedPage.EachLine(function(){if(this.Selected){g_Client.Document.RunAction({Action:'RemoveLine',id:this.id});}});g_Client.Document.EndUndoBatch();this.Invalidate();}
LucidViewport.prototype.SelectPageHooks=[];LucidViewport.prototype.HookSelectPage=function(f){this.SelectPageHooks.push(f);}
LucidViewport.prototype.SelectPage=function(page){if(page!=this.SelectedPage){if(InlineEditor.CurrentId!=null)
$('#'+InlineEditor.CurrentId).blur();this.SelectedPage=page;this.Invalidate();this.InvalidateBackground();for(var i=0;i<this.SelectPageHooks.length;i++)
this.SelectPageHooks[i](page);g_Client.PageList.MarkupDirty=true;}}
LucidViewport.prototype.Invalidate=function(){g_Client.Log.Log('Render','Invalidated');this.Dirty=true;}
LucidViewport.prototype.InvalidateBackground=function(){g_Client.Log.Log('Render','Invalidated background');this.DirtyBackground=true;}
LucidViewport.prototype.StartRenderTimer=function(){this.RenderTime=new Date();}
LucidViewport.prototype.RenderTimer=function(msg){var t=new Date();g_Client.Log.Log('Render',(t.getTime()-this.RenderTime.getTime())+'ms: '+msg);this.RenderTime=t;}
LucidViewport.prototype._RenderBackground=function(){var c=this.BackgroundLayer.getContext();this.Canvas.container.find('.overlay.line').css({backgroundColor:this.SelectedPage.GetPropertyValue('FillColor')});var scale=this.Scale;var Size=this.SelectedPage.GetPropertyValue('Size');var GridSpacing=this.SelectedPage.GetPropertyValue('GridSpacing');c.fillStyle=this.SelectedPage.GetPropertyValue('FillColor');c.fillRect(0,0,Size.w*scale,Size.h*scale);c.scale(scale,scale);var Margin=this.SelectedPage.GetPropertyValue('DPI')*this.SelectedPage.GetPropertyValue('Margin');c.fillStyle="rgba(0,0,0,.1)";c.fillRect(0,0,Size.w,Margin);c.fillRect(0,Size.h-Margin,Size.w,Margin);c.fillRect(0,Margin,Margin,Size.h-Margin*2);c.fillRect(Size.w-Margin,Margin,Margin,Size.h-Margin*2);if(g_Client.Document.ViewingHistory){c.fillStyle="rgb(255,255,230)";c.fillRect(Margin,Margin,Size.w-Margin*2,Size.h-Margin*2);}
else if(!g_Client.User||!g_Client.User.preferences||g_Client.User.preferences.HideGrid==0){if(!this.NoGrid){c.beginPath();c.strokeStyle="rgb(216,216,216)";c.lineWidth=1;for(var y=0;y<Size.h;y+=GridSpacing){c.moveTo(0,y+.5);c.lineTo(Size.w,y+.5);}
for(var x=0;x<Size.w;x+=GridSpacing){c.moveTo(x+.5,0);c.lineTo(x+.5,Size.h);}
c.stroke();}}
if(!g_Client.Document.ViewingHistory){for(var i=0;i<this.SelectedPage.PublishedSegments.length;i++){var seg=this.SelectedPage.PublishedSegments[i];c.strokeStyle="rgba(255,100,100,.5)";c.fillStyle="rgba(255,255,200,.5)";c.fillRect(parseInt(seg.x),parseInt(seg.y),parseInt(seg.w),parseInt(seg.h));c.strokeRect(parseInt(seg.x),parseInt(seg.y),parseInt(seg.w),parseInt(seg.h));}}}
LucidViewport.prototype._RenderUIHints=function(NewBlock){var scale=this.Scale;var Size=this.SelectedPage.GetPropertyValue('Size');var c=this.UIHintLayer.getContext();c.scale(scale,scale);var DragBlocks=[];if(NewBlock!=null)
DragBlocks.push(NewBlock);if(this.IsMouseDown&&this.DragHit!=null&&this.DragHit.Action=='move'){for(var i=0;i<this.DragItems.length;i++){if(this.DragItems[i].IsBlock)
DragBlocks.push(this.DragItems[i]);}}
if(DragBlocks.length==0&&(!this.IsMouseDown||this.DragHit==null)){return;}
var SetX={};var SetY={};this.SelectedPage.EachBlock(function(){if(arrayIndexOf(DragBlocks,this)==-1){for(var p=0;p<this.LinkPoints.length;p++){if(this.LinkPoints[p].x==0.5)
SetY[this.RelativeY(.5)]=true;if(this.LinkPoints[p].y==0.5)
SetX[this.RelativeX(.5)]=true;}}});SetX[this.SelectedPage.SnapToGrid(Size.w/2)]=true;SetY[this.SelectedPage.SnapToGrid(Size.h/2)]=true;c.beginPath();c.strokeStyle="rgba(255,71,10,.5)";c.lineWidth=2;for(var i=0;i<DragBlocks.length;i++){var block=DragBlocks[i];var bb=block.GetBoundingBox();var Snapped=this.SelectedPage.SnapToGrid(block.GetOffsetBoundingBox(this.Offsets[block.id]));var Offset={x:Snapped.x-bb.x,y:Snapped.y-bb.y,w:0,h:0};if(DragBlocks[i]==NewBlock||Offset.x!=0||Offset.y!=0){for(var p=0;p<DragBlocks[i].LinkPoints.length;p++){var x=DragBlocks[i].RelativeX(DragBlocks[i].LinkPoints[p].x,Offset);var y=DragBlocks[i].RelativeY(DragBlocks[i].LinkPoints[p].y,Offset);var n=DragBlocks[i].LinkPointNormal(DragBlocks[i].LinkPoints[p]);if(n.x==0&&SetX[x]){c.moveTo(x,0);c.lineTo(x,Size.h);}
if(n.y==0&&SetY[y]){c.moveTo(0,y);c.lineTo(Size.w,y);}}}}
c.stroke();if(this.IsMouseDown&&this.DragHit!=null){if(this.DragHit.Action=='linkpoint'||this.DragHit.Action=='dragline'){if(this.DragHit.Action=='linkpoint'){var line=this.DragLine;var prop='Endpoint2';}
else{var line=this.DragHit.Item;var prop=this.DragHit.Property;}
var ep=line.GetPropertyValue(prop);if(ep.Block!=null)
this._RenderHighlightCircle(c,ep.x,ep.y);}}
for(var i=0;i<DragBlocks.length;i++){var block=DragBlocks[i];var bb=block.GetBoundingBox();var Snapped=this.SelectedPage.SnapToGrid(block.GetOffsetBoundingBox(this.Offsets[block.id]));var Offset={x:Snapped.x-bb.x,y:Snapped.y-bb.y,w:0,h:0};var Tolerance=this.SelectedPage.GetPropertyValue('GridSpacing');this.SelectedPage.EachLine(function(){var ep1=this.GetPropertyValue('Endpoint1',true);var ep2=this.GetPropertyValue('Endpoint2',true);var checkEp1=(ep1.Block==null||g_Client.Viewport.SelectedPage.Blocks[ep1.Block]==null);var checkEp2=(ep2.Block==null||g_Client.Viewport.SelectedPage.Blocks[ep2.Block]==null);if(checkEp1||checkEp2){for(var i=0;i<block.LinkPoints.length;i++){var x=block.RelativeX(block.LinkPoints[i].x,Offset);var y=block.RelativeY(block.LinkPoints[i].y,Offset);if(checkEp1&&Math.abs(x-ep1.x)<Tolerance&&Math.abs(y-ep1.y)<Tolerance)
g_Client.Viewport._RenderHighlightCircle(c,ep1.x,ep1.y);if(checkEp2&&Math.abs(x-ep2.x)<Tolerance&&Math.abs(y-ep2.y)<Tolerance)
g_Client.Viewport._RenderHighlightCircle(c,ep2.x,ep2.y);}}});}}
LucidViewport.prototype.Render=function(DoBackground){if(this.SelectedPage==null)return;if(InlineEditor.CurrentId!=null){if(g_Client.Toolbox.DraggingBlockClass!=null){$('#'+InlineEditor.CurrentId).blur();}
else{return;}}
if(is_chrome||is_safari)
this.Canvas.container.css({overflow:'hidden'});g_Client.Log.Log('Render','Viewport.Render');var scale=g_Client.Viewport.Scale;var Size=this.SelectedPage.GetPropertyValue('Size');var GridSpacing=this.SelectedPage.GetPropertyValue('GridSpacing');this.StartRenderTimer();var width=Math.round(Size.w*scale);var height=Math.round(Size.h*scale);if(this.Canvas.width!=width||this.Canvas.height!=height){this.Canvas.resize(width,height);this.BackgroundLayer.move(0,0,width,height);this.UIHintLayer.move(0,0,width,height);DoBackground=true;}
this.RenderTimer('Set canvas size');if(DoBackground){this._RenderBackground();this.RenderTimer('Render background');}
for(var i=0;i<this.Canvas.layers.length;i++){var l=this.Canvas.layers[i];if(l.BlockId!=null&&this.SelectedPage.Blocks[l.BlockId]==null){this.Canvas.removeLayer(l);i--;}
else if(l.LineId!=null&&l.LineId!='DragLine'&&this.SelectedPage.Lines[l.LineId]==null){this.Canvas.removeLayer(l);i--;}
else if(l.LineId=='DragLine'&&this.DragLine==null){this.Canvas.removeLayer(l);i--;}}
this.RenderTimer('Remove extra layers');var lines=this.SelectedPage.GetOrderedLines();if(this.DragLine!=null)
lines.push(this.DragLine);this.RenderTimer('Get sorted lines');var PointsToReset={};var ControlPointsToReset={};if(this.IsMouseDown){for(var i=0;i<lines.length;i++){var ep1=lines[i].GetPropertyValue('Endpoint1');var ep2=lines[i].GetPropertyValue('Endpoint2');var changed=false;if(ep1.Block!=null&&this.Offsets[ep1.Block]!=null){var block=this.SelectedPage.Blocks[ep1.Block];if(block!=null){changed=true;ep1.x=block.RelativeX(ep1.LinkX,this.Offsets[ep1.Block]);ep1.y=block.RelativeY(ep1.LinkY,this.Offsets[ep1.Block]);}}
if(ep2.Block!=null&&this.Offsets[ep2.Block]!=null){var block=this.SelectedPage.Blocks[ep2.Block];if(block!=null){changed=true;ep2.x=block.RelativeX(ep2.LinkX,this.Offsets[ep2.Block]);ep2.y=block.RelativeY(ep2.LinkY,this.Offsets[ep2.Block]);}}
if(this.Offsets[lines[i].id]!=null){if(ep1.Block==null||this.SelectedPage.Blocks[ep1.Block]==null){changed=true;ep1.x+=this.Offsets[lines[i].id].x;ep1.y+=this.Offsets[lines[i].id].y;}
if(ep2.Block==null||this.SelectedPage.Blocks[ep2.Block]==null){changed=true;ep2.x+=this.Offsets[lines[i].id].x;ep2.y+=this.Offsets[lines[i].id].y;}
if(lines[i].GetPropertyValue('Shape')=='curve'){ControlPointsToReset[lines[i].id]=lines[i].GetPropertyValue('ControlPoints');var cp=lines[i].GetPropertyValue('ControlPoints');if(cp.middle){for(var cpi=0;cpi<cp.middle.length;cpi++){cp.middle[cpi].x+=this.Offsets[lines[i].id].x;cp.middle[cpi].y+=this.Offsets[lines[i].id].y;}}
lines[i].SetPropertyValue('ControlPoints',cp);}}
if(changed){PointsToReset[lines[i].id]=lines[i].GetPropertyValue('Points');lines[i].SetPropertyValue('Points',lines[i]._GetPoints(ep1,ep2));}}}
this.RenderTimer('Moving dragging lines');LucidLine._PreRender(lines);this.RenderTimer('Prerender lines');for(var i=0;i<lines.length;i++){lines[i].Render(this.Canvas);}
for(var i=0;i<lines.length;i++){if(PointsToReset[lines[i].id]!=null)
lines[i].SetPropertyValue('Points',PointsToReset[lines[i].id]);if(ControlPointsToReset[lines[i].id]!=null)
lines[i].SetPropertyValue('ControlPoints',ControlPointsToReset[lines[i].id]);}
this.RenderTimer('Render lines');var SortedBlocks=this.SelectedPage.GetOrderedBlocks();var IsDraggingEndpoint=this.IsMouseDown&&this.DragHit!=null&&(this.DragHit.Action=='linkpoint'||this.DragHit.Action=='dragline');for(var id in this.SelectedPage.Blocks)
this.SelectedPage.Blocks[id].Render(this.Canvas,false,this.IsMouseDown?this.Offsets[id]:null,IsDraggingEndpoint);this.RenderTimer('Render blocks');var PrevLayer=this.BackgroundLayer;$.map(SortedBlocks,function(b){if(b.IsContainer){if(PrevLayer.container.get(0).nextSibling!=b.Layer.container.get(0)){if(is_ie)
PrevLayer.container.get(0).insertAdjacentElement('afterEnd',b.Layer.container.get(0));else
b.Layer.container.insertAfter(PrevLayer.container);}
PrevLayer=b.Layer;}});$.map(lines,function(l){if(PrevLayer.container.get(0).nextSibling!=l.Layer.container.get(0)){if(is_ie)
PrevLayer.container.get(0).insertAdjacentElement('afterEnd',l.Layer.container.get(0));else
l.Layer.container.insertAfter(PrevLayer.container);}
PrevLayer=l.Layer;});$.map(SortedBlocks,function(b){if(!b.IsContainer){if(PrevLayer.container.get(0).nextSibling!=b.Layer.container.get(0)){if(is_ie)
PrevLayer.container.get(0).insertAdjacentElement('afterEnd',b.Layer.container.get(0));else
b.Layer.container.insertAfter(PrevLayer.container);}
PrevLayer=b.Layer;}});this.RenderTimer('Sort layers');var NewBlock=null;if(g_Client.Toolbox.DraggingBlockClass!=null&&!g_Client.Toolbox.DroppingBlock){NewBlock=new g_Client.Toolbox.DraggingBlockClass('');NewBlock.SetPropertyValue('BoundingBox',{x:this.DragBlockX-g_Client.Toolbox.DraggingBlockSize.w/2,y:this.DragBlockY-g_Client.Toolbox.DraggingBlockSize.h/2,w:g_Client.Toolbox.DraggingBlockSize.w,h:g_Client.Toolbox.DraggingBlockSize.h});for(var key in g_Client.Toolbox.DraggingBlockProperties)
NewBlock.SetPropertyValue(key,g_Client.Toolbox.DraggingBlockProperties[key]);NewBlock.SetPropertyValue('LineWidth',g_Client.Document.GetPropertyValue('DefaultBlockLineWidth'));NewBlock.SetPropertyValue('LineColor',g_Client.Document.GetPropertyValue('DefaultBlockLineColor'));NewBlock.SetPropertyValue('FillColor',g_Client.Document.GetPropertyValue('DefaultBlockFillColor'));NewBlock.Render(this.Canvas,true);}
this.RenderTimer('Render new block');this._RenderUIHints(NewBlock);this.RenderTimer('UI hints');this.RenderTimer('Finished');}
LucidViewport.prototype._RenderHighlightCircle=function(c,x,y){c.fillStyle='rgba(255,255,192,.5)';c.strokeStyle='rgba(128,51,51,.5)';c.lineWidth=4;c.beginPath();c.ellipse(x-20,y-20,40,40);c.fill();c.stroke();}
LucidViewport.prototype._IsSignificantOffset=function(Offset){var o=this.SelectedPage.SnapToGrid(Offset);return(o.x!=0||o.y!=0||o.w!=0||o.h!=0);}


LucidViewport.prototype.EditLinePoints=function(line){var Shape=line.GetPropertyValue('Shape');if(Shape=='curve')
this._EditCurveLinePoints(line);else if(Shape=='elbow')
this._EditElbowLinePoints(line);g_Client.LogAction('editLinePoints');}
LucidViewport.prototype._SetupEditLinePoints=function(line,page,MouseDown,MouseMove,MouseUp,DoubleClick){page.UnselectAll();page.SelectItem(line);$('#editlineoverlay').remove();$(this.Div).append('<div id="editlineoverlay"><span>Enter: Save Changes<br/>Escape: Cancel Changes<br/>Double-Click: Remove/Reset Point</span></div>');$('#editlineoverlay').css({position:'absolute',left:0,top:0,width:this.Canvas.width+'px',height:this.Canvas.height+'px','z-index':10000}).disableTextSelect();$('#editlineoverlay span').css({position:'fixed',font:'bold 24px arial',margin:'4px',cursor:'default'}).fadeTo(1000,.7);var md=function(e){var offset=$(g_Client.Viewport.Canvas.container).offset();var x=e.pageX-offset.left;var y=e.pageY-offset.top;MouseDown(x/g_Client.Viewport.Scale,y/g_Client.Viewport.Scale);};var mu=function(e){var offset=$(g_Client.Viewport.Canvas.container).offset();var x=e.pageX-offset.left;var y=e.pageY-offset.top;MouseUp(x/g_Client.Viewport.Scale,y/g_Client.Viewport.Scale);};var mm=function(e){var offset=$(g_Client.Viewport.Canvas.container).offset();var x=e.pageX-offset.left;var y=e.pageY-offset.top;MouseMove(x/g_Client.Viewport.Scale,y/g_Client.Viewport.Scale);};var dc=function(e){var offset=$(g_Client.Viewport.Canvas.container).offset();var x=e.pageX-offset.left;var y=e.pageY-offset.top;DoubleClick(x/g_Client.Viewport.Scale,y/g_Client.Viewport.Scale);};$('#editlineoverlay,#viewport').mousedown(md).mouseup(mu).mousemove(mm).dblclick(dc);this.InputLocked=true;this._TearDownEditLinePoints=function(){this.InputLocked=false;$('#editlineoverlay,#viewport').unbind('mousedown',md).unbind('mouseup',mu).unbind('mousemove',mm).unbind('dblclick',dc);}}
LucidViewport.prototype._EditElbowLinePoints=function(line){var scale=this.Scale;var Size=this.SelectedPage.GetPropertyValue('Size');var OldPoints=line.GetPropertyValue('Points');var Layer=new SuperCanvasLayer(0,0,Size.w*scale,Size.h*scale);this.Canvas.addLayer(Layer);var page=g_Client.Document._FindObjectPage(line.id);var renderInterval=null;var keydown=null;function Exit(Commit){g_Client.Viewport.Canvas.removeLayer(Layer);$('#editlineoverlay').remove();clearInterval(renderInterval);var p=line.GetPropertyValue('Points');line.SetPropertyValue('Points',OldPoints);if(Commit){g_Client.Document.StartUndoBatch();g_Client.Document.RunAction({Action:'SetProperty',id:line.id,Property:'Points',Value:LucidLine.RemoveExcessPoints(p)});g_Client.Document.EndUndoBatch();}
g_Client.Viewport.Invalidate();$(document).unbind('keydown',keydown);g_Client.Viewport._TearDownEditLinePoints();}
keydown=function(e){if(e.which==13||e.keyCode==13)
Exit(true);if(e.which==27||e.keyCode==27)
Exit();};$(document).keydown(keydown);g_Client.Document.OnNextAction(function(){Exit();});var DragHit=null;var MouseHit=null;function HitTest(x,y){var options=[];var p=line.GetPropertyValue('Points');for(var i=0;i<p.length;i++){if(i>0&&i<p.length-1){options.push({Action:'MovePoint',Index:i,x:p[i].x,y:p[i].y,Color:'rgb(0,255,0)'});}
p[i].t=line.ClosestRelativePoint(p[i].x,p[i].y);}
var minDistSq=99999999;var ret=null;for(var i=0;i<options.length;i++){var dx=options[i].x-x;var dy=options[i].y-y;var distSq=dx*dx+dy*dy;if(distSq<20*20&&distSq<minDistSq){minDistSq=distSq;ret=options[i];}}
if(ret==null){var t=line.ClosestRelativePoint(x,y,false);var rp=line._GetRelativePoint(t);var dx=rp.x-x;var dy=rp.y-y;var distSq=dx*dx+dy*dy;if(distSq<20*20){var after=0;for(var i=0;i<p.length;i++){if(p[i].t<t)
after=i;else
break;}
ret={Action:'AddPoint',x:rp.x,y:rp.y,After:after,Color:'rgb(255,0,0)'};}}
return ret;}
function Render(){scale=g_Client.Viewport.Scale;var Size=g_Client.Viewport.SelectedPage.GetPropertyValue('Size');Layer.move(0,0,Size.w*scale,Size.h*scale);var c=Layer.getContext();c.scale(scale,scale);c.fillStyle='rgba(255,255,170,0.5)';c.fillRect(0,0,Size.w,Size.h);var width=line.GetPropertyValue('LineWidth');var points=line.GetPropertyValue('Points');c.strokeStyle='rgb(0,0,0)';c.lineWidth=width+2;c.beginPath();c.moveTo(points[0].x,points[0].y);for(var i=1;i<points.length;i++)
c.lineTo(points[i].x,points[i].y);c.stroke();c.fillStyle='rgb(255,255,255)';c.strokeStyle='rgb(128,0,0)';c.lineWidth=2;for(var i=1;i<points.length-1;i++){c.beginPath();c.arc(points[i].x,points[i].y,5,0,Math.PI*2,false);c.closePath();c.stroke();c.fill();}
if(MouseHit){c.fillStyle=MouseHit.Color;c.strokeStyle='rgb(0,0,0)';c.lineWidth=2;c.beginPath();c.arc(MouseHit.x,MouseHit.y,5,0,Math.PI*2,false);c.closePath();c.stroke();c.fill();}}
var Invalidated=true;var Tick=function(){if(Invalidated||scale!=g_Client.Viewport.Scale){Invalidated=false;Render();}}
renderInterval=setInterval(Tick,20);function MouseDown(x,y){DragHit=HitTest(x,y);if(DragHit&&DragHit.Action=='AddPoint'){var p=line.GetPropertyValue('Points');p.splice(DragHit.After+1,0,{x:DragHit.x,y:DragHit.y});line.SetPropertyValue('Points',p);Invalidated=true;DragHit=HitTest(x,y);}}
function DoubleClick(x,y){DragHit=null;var hit=HitTest(x,y);if(hit&&hit.Action=='MovePoint'){var p=line.GetPropertyValue('Points');p.splice(hit.Index,1);line.SetPropertyValue('Points',p);Invalidated=true;}}
function MouseMove(x,y){MouseHit=HitTest(x,y);if(DragHit&&DragHit.Action=='MovePoint'){var p=line.GetPropertyValue('Points');p[DragHit.Index].x=page.SnapToGrid(x,2);p[DragHit.Index].y=page.SnapToGrid(y,2);line.SetPropertyValue('Points',p);if(!is_safari)
Tick();}
Invalidated=true;}
function MouseUp(x,y){DragHit=null;}
this._SetupEditLinePoints(line,page,MouseDown,MouseMove,MouseUp,DoubleClick);}
LucidViewport.prototype._EditCurveLinePoints=function(line){var scale=this.Scale;var Size=this.SelectedPage.GetPropertyValue('Size');var OldControlPoints=line.GetPropertyValue('ControlPoints');g_Client.Log.Log('elp',JSON.stringify(OldControlPoints));var Layer=new SuperCanvasLayer(0,0,Size.w*scale,Size.h*scale);this.Canvas.addLayer(Layer);var page=g_Client.Document._FindObjectPage(line.id);var renderInterval=null;var keydown=null;function Exit(Commit){g_Client.Viewport.Canvas.removeLayer(Layer);$('#editlineoverlay').remove();clearInterval(renderInterval);var cp=line.GetPropertyValue('ControlPoints');line.SetPropertyValue('ControlPoints',OldControlPoints);if(Commit){g_Client.Document.StartUndoBatch();g_Client.Document.RunAction({Action:'SetProperty',id:line.id,Property:'ControlPoints',Value:cp});g_Client.Document.EndUndoBatch();}
g_Client.Viewport.Invalidate();$(document).unbind('keydown',keydown);g_Client.Viewport._TearDownEditLinePoints();}
keydown=function(e){if(e.which==13||e.keyCode==13)
Exit(true);if(e.which==27||e.keyCode==27)
Exit();};$(document).keydown(keydown);g_Client.Document.OnNextAction(function(){Exit();});var DragHit=null;var MouseHit=null;function HitTest(x,y){var options=[];var cp=line._GetControlPoints();for(var i=0;i<cp.length;i++){if(i>0&&i<cp.length-1){options.push({Action:'MoveControlPoint',Index:i,x:cp[i].x,y:cp[i].y,Color:'rgb(0,255,0)'});}
options.push({Action:'MoveTangent',Index:i,x:cp[i].x+cp[i].nx/2,y:cp[i].y+cp[i].ny/2,Factor:.5,Color:'rgb(0,255,0)'});options.push({Action:'MoveTangent',Index:i,x:cp[i].x-cp[i].nx/2,y:cp[i].y-cp[i].ny/2,Factor:-.5,Color:'rgb(0,255,0)'});cp[i].t=line.ClosestRelativePoint(cp[i].x,cp[i].y);}
var minDistSq=99999999;var ret=null;for(var i=0;i<options.length;i++){var dx=options[i].x-x;var dy=options[i].y-y;var distSq=dx*dx+dy*dy;if(distSq<20*20&&distSq<minDistSq){minDistSq=distSq;ret=options[i];}}
if(ret==null){var t=line.ClosestRelativePoint(x,y,false);var p=line._GetRelativePoint(t);var dx=p.x-x;var dy=p.y-y;var distSq=dx*dx+dy*dy;if(distSq<20*20){var after=0;for(var i=0;i<cp.length;i++){if(cp[i].t<t)
after=i;else
break;}
var slope=findSplineSlope(p.x,p.y,cp[after],{x:cp[after].x+cp[after].nx,y:cp[after].y+cp[after].ny},{x:cp[after+1].x-cp[after+1].nx,y:cp[after+1].y-cp[after+1].ny},cp[after+1]);ret={Action:'AddControlPoint',x:p.x,y:p.y,nx:slope.x,ny:slope.y,After:after,Color:'rgb(255,0,0)'};}}
return ret;}
function Render(){g_Client.Log.Log('el','Render');scale=g_Client.Viewport.Scale;var Size=g_Client.Viewport.SelectedPage.GetPropertyValue('Size');Layer.move(0,0,Size.w*scale,Size.h*scale);var c=Layer.getContext();c.scale(scale,scale);c.fillStyle='rgba(255,255,170,0.5)';c.fillRect(0,0,Size.w,Size.h);var width=line.GetPropertyValue('LineWidth');var points=line.GetPropertyValue('Points');c.strokeStyle='rgb(0,0,0)';c.lineWidth=width+2;c.beginPath();c.moveTo(points[0].x,points[0].y);for(var i=1;i<points.length;i++)
c.lineTo(points[i].x,points[i].y);c.stroke();var cp=line._GetControlPoints();c.fillStyle='rgb(255,255,255)';c.strokeStyle='rgb(128,0,0)';c.lineWidth=2;for(var i=0;i<cp.length;i++){c.beginPath();c.moveTo(cp[i].x+cp[i].nx/2,cp[i].y+cp[i].ny/2);c.lineTo(cp[i].x-cp[i].nx/2,cp[i].y-cp[i].ny/2);c.stroke();if(i>0&&i<cp.length-1){c.beginPath();c.arc(cp[i].x,cp[i].y,5,0,Math.PI*2,false);c.closePath();c.stroke();c.fill();}
c.beginPath();c.arc(cp[i].x+cp[i].nx/2,cp[i].y+cp[i].ny/2,5,0,Math.PI*2,false);c.closePath();c.stroke();c.fill();c.beginPath();c.arc(cp[i].x-cp[i].nx/2,cp[i].y-cp[i].ny/2,5,0,Math.PI*2,false);c.closePath();c.stroke();c.fill();}
if(MouseHit){c.fillStyle=MouseHit.Color;c.strokeStyle='rgb(0,0,0)';c.lineWidth=2;c.beginPath();c.arc(MouseHit.x,MouseHit.y,5,0,Math.PI*2,false);c.closePath();c.stroke();c.fill();}}
var Invalidated=true;var Tick=function(){if(Invalidated||scale!=g_Client.Viewport.Scale){Invalidated=false;Render();}}
renderInterval=setInterval(Tick,20);function MouseDown(x,y){DragHit=HitTest(x,y);if(DragHit&&DragHit.Action=='AddControlPoint'){var cp=line.GetPropertyValue('ControlPoints');if(cp.middle==null)
cp.middle=[];cp.middle.splice(DragHit.After,0,{x:DragHit.x,y:DragHit.y,nx:DragHit.nx,ny:DragHit.ny});line.SetPropertyValue('ControlPoints',cp);Invalidated=true;DragHit=HitTest(x,y);}}
function DoubleClick(x,y){DragHit=null;var hit=HitTest(x,y);if(hit&&(hit.Action=='MoveTangent'||hit.Action=='MoveControlPoint')){var cp=line.GetPropertyValue('ControlPoints');var Calculated=line._GetControlPoints();if(hit.Index==0)
delete cp.first;else if(hit.Index==Calculated.length-1)
delete cp.last;else
cp.middle.splice(hit.Index-1,1);line.SetPropertyValue('ControlPoints',cp);Invalidated=true;}}
function MouseMove(x,y){MouseHit=HitTest(x,y);if(DragHit&&DragHit.Action=='MoveTangent'){var cp=line.GetPropertyValue('ControlPoints');var Calculated=line._GetControlPoints();if(DragHit.Index==0){if(cp.first==null)
cp.first=Calculated[0];var p=cp.first;}
else if(DragHit.Index==Calculated.length-1){if(cp.last==null)
cp.last=Calculated[Calculated.length-1];var p=cp.last;}
else
var p=cp.middle[DragHit.Index-1];p.nx=(x-p.x)/DragHit.Factor;p.ny=(y-p.y)/DragHit.Factor;line.SetPropertyValue('ControlPoints',cp);}
else if(DragHit&&DragHit.Action=='MoveControlPoint'){var cp=line.GetPropertyValue('ControlPoints');var Calculated=line._GetControlPoints();var p=cp.middle[DragHit.Index-1];p.x=x;p.y=y;line.SetPropertyValue('ControlPoints',cp);}
Invalidated=true;if(!is_safari)
Tick();g_Client.Log.Log('el','MouseMove/invalidated');}
function MouseUp(x,y){DragHit=null;}
this._SetupEditLinePoints(line,page,MouseDown,MouseMove,MouseUp,DoubleClick);}


var LucidThumbnail=function(){$('body').append('<div id="thumbnaildiv"><div id="viewportrect"></div></div>');var c=document.createElement('canvas');c.id='thumbnail';$('#thumbnaildiv').append(c);this.Div=$('#thumbnaildiv');this.Canvas=InitCanvas($('#thumbnail'));this.ViewportRect=$('#viewportrect');this.Div.css({overflow:'hidden',border:'1px solid #aaaaaa'});this.ViewportRect.css({opacity:0.1,background:'#000000',position:'absolute','z-index':1000});this.IsMouseDown=false;var me=this;this.Canvas.Bind('mousedown',function(e){me.IsMouseDown=true;me.MoveViewportViaThumbnail(e);});this.Canvas.Bind('mouseout',function(e){var x=e.pageX;var y=e.pageY;var offset=$(me.Canvas).offset();var w=me.Canvas.offsetWidth;var h=me.Canvas.offsetHeight;if(x>=offset.left&&x<=offset.left+w&&y>=offset.top&&y<=offset.top+h)
return;if(me.IsMouseDown){me.IsMouseDown=false;me.MoveViewportViaThumbnail(e);}});this.Canvas.Bind('mouseup',function(e){if(me.IsMouseDown){me.IsMouseDown=false;me.MoveViewportViaThumbnail(e);}});this.Canvas.Bind('mousemove',function(e){if(me.IsMouseDown)
me.MoveViewportViaThumbnail(e);});for(var i=0;i<this.Canvas.BindedEvents.length;i++)
this._PassthroughEvent(this.ViewportRect,this.Canvas,this.Canvas.BindedEvents[i]);this.Dirty=false;this._Tick=function(){if(me.Dirty){me.Dirty=false;var before=new Date();me.Render();var after=new Date();g_Client.Log.Log('Render',(after.getTime()-before.getTime())+'ms: Overall thumbnail render');}};setInterval(this._Tick,50);var me=this;g_Client.Document.HookActions(function(a){me.Invalidate();});g_Client.Viewport.HookSelectPage(function(){me.Invalidate();});}
LucidThumbnail.prototype._PassthroughEvent=function(Div,canvas,event){Div.bind(event,function(e){$(canvas).trigger(e);});}
LucidThumbnail.prototype.Invalidate=function(){this.Dirty=true;}
LucidThumbnail.prototype.MoveViewportViaThumbnail=function(e){if(g_Client.Viewport==null||g_Client.Viewport.SelectedPage==null)
return;var PageSize=g_Client.Viewport.SelectedPage.GetPropertyValue('Size');var offset=$(this.Canvas).offset();var scale=PageSize.w/$(this.Canvas).width();var x=(e.pageX-offset.left)*scale;var y=(e.pageY-offset.top)*scale;g_Client.Viewport.Div.scrollLeft=x*g_Client.Viewport.Scale-g_Client.Viewport.Div.offsetWidth/2;g_Client.Viewport.Div.scrollTop=y*g_Client.Viewport.Scale-g_Client.Viewport.Div.offsetHeight/2;}
LucidThumbnail.prototype.MoveViewportRect=function(){if(g_Client.Viewport==null||g_Client.Viewport.SelectedPage==null)
return;var div=g_Client.Viewport.Div;var maincanvas=g_Client.Viewport.Canvas.container;var PageSize=g_Client.Viewport.SelectedPage.GetPropertyValue('Size');var w=180;var h=Math.round(w*PageSize.h/PageSize.w);if(w!=$(this.Canvas).attr('width')||h!=$(this.Canvas).attr('height')){$(this.Canvas).attr('width',w).attr('height',h);$(this.Div).css({'width':w+'px','height':h+'px'});g_Client.LayoutDirty=true;g_Client.Log.Log('Render','g_Client.LayoutDirty=true (Thumbnail.Render)'+[w,h,$(this.Canvas).attr('width'),$(this.Canvas).attr('height')]);}
var scale=w/PageSize.w;try{var coffset=$(maincanvas).offset();var doffset=$(div).offset();var scrollLeft=doffset.left-coffset.left;var scrollTop=doffset.top-coffset.top;this.ViewportRect.css({left:(scrollLeft*scale/g_Client.Viewport.Scale)+'px',top:(scrollTop*scale/g_Client.Viewport.Scale)+'px',width:(div.clientWidth*scale/g_Client.Viewport.Scale)+'px',height:(div.clientHeight*scale/g_Client.Viewport.Scale)+'px'});}
catch(err){document.title=err;}}
LucidThumbnail.prototype.Render=function(){if(g_Client.Viewport==null||g_Client.Viewport.SelectedPage==null)
return;g_Client.Log.Log('Render','Thumbnail.Render');var PageSize=g_Client.Viewport.SelectedPage.GetPropertyValue('Size');var w=180;var h=Math.round(w*PageSize.h/PageSize.w);if(w!=$(this.Canvas).attr('width')||h!=$(this.Canvas).attr('height')){$(this.Canvas).attr('width',w).attr('height',h);$(this.Div).css({'width':w+'px','height':h+'px'});g_Client.LayoutDirty=true;g_Client.Log.Log('Render','g_Client.LayoutDirty=true (Thumbnail.Render)'+[w,h,$(this.Canvas).attr('width'),$(this.Canvas).attr('height')]);}
var scale=w/PageSize.w;var c=this.Canvas.getContext('2d');c.clearRect(0,0,w,h);c.fillStyle="rgb(255,255,255)";c.fillRect(0,0,w,h);var blocks=g_Client.Viewport.SelectedPage.GetOrderedBlocks();for(var i=0;i<blocks.length;i++){if(blocks[i].IsContainer)
blocks[i].RenderThumbnail(this.Canvas,scale);}
var lines=g_Client.Viewport.SelectedPage.GetOrderedLines();for(var i=0;i<lines.length;i++)
lines[i].RenderThumbnail(this.Canvas,scale);for(var i=0;i<blocks.length;i++){if(!blocks[i].IsContainer)
blocks[i].RenderThumbnail(this.Canvas,scale);}}


var LucidPageList=function(){var me=this;this.AllowDragDrop=true;this.AllowRename=true;this.AllowContextMenu=true;this.AllowNewPage=true;g_Client.Document.HookActions(function(a){if(a.Action=='SetProperty'){var item=g_Client.Document._FindObject(a.id);if(item!=null&&item.IsPage)
me.MarkupDirty=true;}
else if(a.Action=='CreatePage'||a.Action=='RemovePage'){me.MarkupDirty=true;}});g_Client._RegisterMarkupItem(this,function(){if(this.Div==null){$('body').append("<div id='pagesdiv'><ul id='pages'><li id='pages_NewPage'><a><img src='/img/icons/add.png'/></a></li></ul><div style='clear:both;'></div></div>");this.Div=$('#pagesdiv');this.UL=$('#pages');$('#pages_NewPage').click(function(){if(!g_Client.CanEdit())return;jqPrompt('Please enter a title for this new page.','New Page',function(NewTitle){var a={Action:'CreatePage',Properties:{Title:NewTitle,Order:g_Client.Document.MaxPageProperty('Order')+1}};fd.RunAction(a);g_Client.Viewport.SelectPage(g_Client.Document.Pages[a.id]);});});}
if(!g_Client.CanEdit()||!me.AllowNewPage)
$('#pages_NewPage').css('display','none');else
$('#pages_NewPage').css('display','block');var Pages=g_Client.Document.GetOrderedPages();while(this.UL.find('li').size()>1)
this.UL.find('li').eq(0).remove();while(this.UL.find('li').size()<Pages.length+1)
this.UL.prepend('<li><a></a></li>');var fd=g_Client.Document;this.Div.find('li').each(function(i){if(i>=Pages.length)
return;var li=this;if(me.AllowDragDrop){$(this).find('a').draggable({distance:10,containment:'#pagesdiv',zIndex:5000,start:function(){me.DraggingItem=li;},stop:function(){var y=[];me.Div.find('a').each(function(i){if(i>=Pages.length)return;if(this.parentNode==me.DraggingItem)return;if(arrayIndexOf(y,$(this).offset().top)==-1)
y.push($(this).offset().top);});var mindist=null;var DragY=$(me.DraggingItem).find('a').offset().top;var FinalDragY=null;for(var i=0;i<y.length;i++){var dist=Math.abs(y[i]-DragY);if(mindist==null||dist<mindist){mindist=dist;FinalDragY=y[i];}}
var DragId=$(me.DraggingItem).attr('PageId');var SortPages=g_Client.Document.GetOrderedPages();SortPages.sort(function(a,b){var AOffset=0;if(a.id==DragId)AOffset=-1;if(b.id==DragId)AOffset=1;a=me.Div.find('li[PageId='+a.id+'] a').offset();b=me.Div.find('li[PageId='+b.id+'] a').offset();if(a.top==DragY)a.top=FinalDragY;if(b.top==DragY)b.top=FinalDragY;g_Client.Log.Log('Render',[b.top,b.left,a.top,a.left]);return(a.top*10000+a.left+AOffset)-(b.top*10000+b.left);});g_Client.Document.StartUndoBatch();for(var i=0;i<SortPages.length;i++){g_Client.Document.RunAction({Action:'SetProperty',id:SortPages[i].id,Property:'Order',Value:i});}
g_Client.Document.EndUndoBatch();}});}
$(this).attr('PageId',Pages[i].id);var PromptRename=function(){if(!g_Client.CanEdit())return;if(!me.AllowRename)return;jqPrompt('Please enter a new title for this page.',Pages[i].GetPropertyValue('Title'),function(NewTitle){fd.RunAction({Action:'SetProperty',id:Pages[i].id,Property:'Title',Value:NewTitle});});}
$(this).find('a').html(Pages[i].GetPropertyValue('Title'));$(this).click(function(){g_Client.Viewport.SelectPage(Pages[i]);}).dblclick(PromptRename);if(me.AllowContextMenu)
g_Client.PageListContextMenu.AttachContextMenu(this);if(Pages[i]==g_Client.Viewport.SelectedPage)
$(this).addClass('selected');else
$(this).removeClass('selected');});this.Div.find('li a').addClass('ui-widget ui-state-default ui-corner-bottom').css({borderTop:'0'}).filter('.selected a').addClass('ui-state-active').removeClass('ui-state-default');g_Client.LayoutDirty=true;g_Client.Log.Log('Render','g_Client.LayoutDirty=true (PageList.UpdateMarkup)');});}
LucidPageList.prototype.SetAllowDragDrop=function(allow){if(this.AllowDragDrop!=allow){this.MarkupDirty=true;this.AllowDragDrop=allow;}}
LucidPageList.prototype.SetAllowNewPage=function(allow){if(this.AllowNewPage!=allow){this.MarkupDirty=true;this.AllowNewPage=allow;}}
LucidPageList.prototype.SetAllowContextMenu=function(allow){if(this.AllowContextMenu!=allow){this.MarkupDirty=true;this.AllowContextMenu=allow;}}
LucidPageList.prototype.SetAllowRename=function(allow){this.AllowRename=allow;}


var LucidTabControl=function(){this.Panels={};this.SelectedPanel=null;g_Client._RegisterMarkupItem(this,function(){if(this.Div==null){$('body').append("<div id='panelcontrol' style='float:left;'><ul></ul></div>");this.Div=$('#panelcontrol');this.UL=$('#panelcontrol ul');}
this.Div.html(this._GetMarkup());this._SetEvents();this.Div.find('a').addClass('ui-widget ui-state-default ui-corner-top').css({borderBottom:'0'}).prepend('<span class="ui-icon ui-icon-triangle-1-e"></span>').filter('.selected').addClass('ui-state-active').removeClass('ui-state-default').find('.ui-icon').removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');});}
LucidTabControl.prototype.GetTargetWidth=function(){var ret=0;if(this.Div!=null){this.Div.find('a').each(function(){ret+=jqWidth(this);});}
if(is_firefox&&is_mac)
ret+=2;return ret;}
LucidTabControl.prototype.AddPanel=function(Name,Width,HTML,OnShow,OnHide,Before){var NewPanels={};function SetNewPanel(){NewPanels[Name]={Name:Name,Width:Width,HTML:HTML,MenuId:'menu_'+Name.replace(/[^a-zA-Z0-9]/g,''),PanelId:'panel_'+Name.replace(/[^a-zA-Z0-9]/g,''),OnShow:OnShow,OnHide:OnHide};}
for(var key in this.Panels){if(key==Before)
SetNewPanel();NewPanels[key]=this.Panels[key];}
if(NewPanels[Name]==null)
SetNewPanel();this.Panels=NewPanels;$('body').append("<div class='panel' id='"+this.Panels[Name].PanelId+"' style='display:none;width:"+Width+"px;'>"+HTML+"</div>");this.MarkupDirty=true;}
LucidTabControl.prototype.RemovePanel=function(Name){delete this.Panels[Name];this.MarkupDirty=true;}
LucidTabControl.prototype.ShowPanel=function(Name){if(this.SelectedPanel!=null&&Name!=this.SelectedPanel.Name){if(this.SelectedPanel.OnHide!=null)
this.SelectedPanel.OnHide();}
if(Name==null)
this.SelectedPanel=null;else{this.SelectedPanel=this.Panels[Name];if(this.SelectedPanel!=null&&this.SelectedPanel.OnShow!=null)
this.SelectedPanel.OnShow();}
g_Client.LayoutDirty=true;this.MarkupDirty=true;g_Client.Log.Log('Render','g_Client.LayoutDirty=true (TabControl.ShowPanel)');}
LucidTabControl.prototype.TogglePanel=function(Name){if(Name==null)
this.ShowPanel(null);else{if(this.SelectedPanel==null)
this.ShowPanel(Name);else if(this.SelectedPanel.Name==Name)
this.ShowPanel(null);else
this.ShowPanel(Name);}}
LucidTabControl.prototype._GetMarkup=function(){var ret='';for(var key in this.Panels){var selected='';if(this.Panels[key]==this.SelectedPanel)
selected='class="selected"';ret+='<li><a '+selected+' id="'+this.Panels[key].MenuId+'">'+key+'</a></li>';}
return ret;}
LucidTabControl.prototype._SetEvents=function(){for(var key in this.Panels){(function(key){$('#'+this.Panels[key].MenuId).click(function(){g_Client.TabControl.TogglePanel(key);});}).call(this,key);}}


var LucidImageManager=function(){this.Images={};this.OnLoad={};}
LucidImageManager.prototype._PreprocessURL=function(url){if(url.search('/img/')==0)
return ImageDomain+url;return url;}
LucidImageManager.prototype.OnImageLoad=function(url,onload){url=this._PreprocessURL(url);if(this.IsImageLoaded(url)){onload(url);}
else{if(this.OnLoad[url]==null)
this.OnLoad[url]=[];this.OnLoad[url].push(onload);}}
LucidImageManager.prototype.IsImageRequested=function(url){url=this._PreprocessURL(url);return this.Images[url]!=null;}
LucidImageManager.prototype.IsImageLoaded=function(url){url=this._PreprocessURL(url);return this.Images[url]!=null&&this.Images[url].IsLoaded;}
LucidImageManager.prototype.GetImage=function(url,onload){url=this._PreprocessURL(url);if(!this.Images[url]){this.Images[url]={URL:url,Image:new Image(),OnLoad:[],IsLoaded:false};var img=this.Images[url];var me=this;$(img.Image).bind('load',function(){if(!img.IsLoaded){img.IsLoaded=true;for(var i=0;i<img.OnLoad.length;i++)
img.OnLoad[i](url);if(me.OnLoad[url]!=null){for(var i=0;i<me.OnLoad[url].length;i++)
me.OnLoad[url][i](url);}}});img.Image.src=url;}
if(onload!=null){if(this.Images[url].IsLoaded){setTimeoutFunction(function(){onload(url);},1);}
else
this.Images[url].OnLoad.push(onload);}
return this.Images[url].Image;}


var LucidDocument=function(){SetupPropertyStore(this);this.RegisterProperty('Title','',null,function(old,NewTitle){$('#title span:first').html(NewTitle);});this.RegisterProperty('DefaultBlockLineColor','#000000');this.RegisterProperty('DefaultBlockFillColor','#ffffff');this.RegisterProperty('DefaultBlockLineWidth',2);this.RegisterProperty('RoundCorners',0);this.RegisterProperty('Gradient',0);this.RegisterProperty('DefaultLineShape','elbow');this.RegisterProperty('DefaultLineLineColor','#000000');this.RegisterProperty('DefaultLineLineWidth',2);this.RegisterProperty('DefaultLineStrokeStyle','solid');this.RegisterProperty('DefaultFont','times');this.RegisterProperty('PageTemplate',[]);this.RegisterProperty('RealTimeCollaboration',0);this.Pages={};this.ActionHistory=[];this.DocumentId=null;this.LoadedActionHistory=[];this.UndoHistory=[];this.RedoHistory=[];this.UndoBatchLevel=0;this.UndoBatch=[];this.ConnectionId=0;this.NextItemId=0;this.NumObjects=0;this.ActionHooks=[];this.PostActionHooks=[];this.UIActionHooks=[];this.SelectionChangeHooks=[];this.NextActionHooks=[];this.IsPublished=false;this.PublicSegments=null;this.ViewingHistory=false;this.HistoryVersion=null;this.ReversedHistory=[];this.SaveHistory=[];this.AllPlugins=[];this.AddPropertyControl('Collaboration','RealTimeCollaboration',{Label:'Changes',Type:'Select',Options:{0:'Share On Save',1:'Share Real-Time'},Value:function(){return this.GetPropertyValue('RealTimeCollaboration');},OnChange:function(val){if(this.DocumentId==null||parseInt(val)==0)
$.jGrowl('This change (toggling real-time collaboration) will take effect when you save this '+Configure.document_text+'.');this.RunAction({Action:'SetProperty',id:null,Property:'RealTimeCollaboration',Value:parseInt(val)});}});this.AddPropertyControl('Template For New Pages','PageTemplate',{Label:'Template',Type:'Buttons',Buttons:{'Set To Current Page':function(){if(g_Client.Viewport.SelectedPage==null)return;var Page=g_Client.Viewport.SelectedPage;var Actions=[];for(var i=0;i<g_Client.Document.ActionHistory.length;i++){var a=g_Client.Document.ActionHistory[i];if(a.Action=='CreateBlock'||a.Action=='CreateLine'){if(a.Page==Page.id)
Actions.push(CopyObject(a));}
if(a.Action=='RemoveBlock'||a.Action=='RemoveLine'||a.Action=='SetProperty'){var OldPageId=g_Client.Document.PageIdFromHistoricalItemId(a.id);if(OldPageId==Page.id||a.id==Page.id)
Actions.push(CopyObject(a));}}
g_Client.Document.RunAction({Action:'SetProperty',id:null,Property:'PageTemplate',Value:Actions});},'Clear Template':function(){g_Client.Document.RunAction({Action:'SetProperty',id:null,Property:'PageTemplate',Value:[]});}}});this.AddPropertyControl('Default Font','Font',{Label:'Font',Type:'SelectButton',Options:{'times':'<span style="font-family:times;font-size:18px;">Times</span>','helvetica':'<span style="font-family:helvetica;font-size:18px;">Helvetica</span>'},Property:'DefaultFont',OnChange:function(val){g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'DefaultFont',Value:val});jqAlert('Would you like to update everything in this document to use this default font?','Change Font',{Yes:function(){function UpdateIndividualFont(){g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'Font',Value:val});}
g_Client.Document.StartUndoBatch();g_Client.Document.EachPage(function(){this.EachBlock(UpdateIndividualFont);this.EachLine(UpdateIndividualFont);});g_Client.Document.EndUndoBatch();},No:function(){}});}});this.AddPropertyControl('Default Style For New Blocks','LineColor',{Label:'Line Color',Type:'Color',Property:'DefaultBlockLineColor'});this.AddPropertyControl('Default Style For New Blocks','FillColor',{Label:'Background',Type:'Color',Property:'DefaultBlockFillColor'});this.AddPropertyControl('Default Style For New Blocks','LineWidth',{Label:'Line Width',Type:'SelectButton',Options:{1:'<img src="/img/editor/width1.png"/>',2:'<img src="/img/editor/width2.png"/>',4:'<img src="/img/editor/width4.png"/>',8:'<img src="/img/editor/width8.png"/>'},Property:'DefaultBlockLineWidth',Numeric:true});this.AddPropertyControl('Default Style For New Lines','LineColor',{Label:'Line Color',Type:'Color',Property:'DefaultLineLineColor'});this.AddPropertyControl('Default Style For New Lines','LineWidth',{Label:'Line Width',Type:'SelectButton',Options:{1:'<img src="/img/editor/width1.png"/>',2:'<img src="/img/editor/width2.png"/>',4:'<img src="/img/editor/width4.png"/>',8:'<img src="/img/editor/width8.png"/>'},Property:'DefaultLineLineWidth',Numeric:true});this.AddPropertyControl('Default Style For New Lines','LineStyle',{Label:'Line Style',Type:'SelectButton',Options:{solid:'<img src="/img/editor/solid.png"/>',dashed:'<img src="/img/editor/dashed.png"/>',dotted:'<img src="/img/editor/dotted.png"/>'},Property:'DefaultLineStrokeStyle'});this.AddPropertyControl('Default Style For New Lines','DefaultLineShape',{Label:'Line Shape',Type:'SelectButton',Options:{curve:'<img src="/img/editor/curve.png"/>',elbow:'<img src="/img/editor/elbow.png"/>',diagonal:'<img src="/img/editor/diagonal.png"/>'},Property:'DefaultLineShape'});}
LucidDocument.prototype.ClearPublishedSegments=function(){this.EachPage(function(){this.ClearPublishedSegments();});}
LucidDocument.prototype.MakeUnsaved=function(){if(this.ViewingHistory)
this.ExitHistoryView();this.DocumentId=null;this.LoadedActionHistory=[];this.SaveHistory=[];}
LucidDocument.prototype.AddSaveHistory=function(user,date,count,noupdate){var last=this.SaveHistory.length==0?{UserName:'',Date:'2000-01-01 00:00:00',Start:0,Count:0,Summary:null}:this.SaveHistory[this.SaveHistory.length-1];if(this.SaveHistory.length==0||user!=last.UserName||mysqlDateDiffSeconds(last.Date,date)>60*10){this.SaveHistory.push({UserName:user,Date:date,Start:last.Start+last.Count,Count:count,Summary:null});}
else{last.Date=date;last.Count+=count;last.Summary=null;}
if(noupdate==null||noupdate==false)
g_Client.HistoryTab.UpdateSaveHistory();}
LucidDocument.prototype.GetSaveHistorySummary=function(h){var doc=this;if(h.Summary==null){h.Summary={};var AddSummaryInfo=function(id,action,itemid){if(!h.Summary[id]){h.Summary[id]={id:id,Title:id=='Document'?'Document':doc._PageTitleBeforeAction(id,h.Start+h.Count),Actions:{},Items:{}};}
h.Summary[id].Actions[action]=true;if(itemid!=null)
h.Summary[id].Items[itemid]=true;}
var RemoveSummaryInfo=function(id,action){if(h.Summary[id].Actions[action]!=null)
delete h.Summary[id].Actions[action];}
for(var i=h.Start;i<h.Start+h.Count;i++){var a=this.ActionHistory[i];switch(a.Action){case'CreatePage':AddSummaryInfo(a.id,'create');RemoveSummaryInfo(a.id,'delete');break;case'RemovePage':AddSummaryInfo(a.id,'delete');break;case'CreateBlock':case'RemoveBlock':case'RemoveLine':case'CreateLine':AddSummaryInfo(this.PageIdFromHistoricalItemId(a.id),'edit',a.id);break;case'SetProperty':var PageId=this.PageIdFromHistoricalItemId(a.id);if(PageId!=null)
AddSummaryInfo(PageId,'edit',a.id);else
AddSummaryInfo('Document','edit');break;}}}
return h.Summary;}
LucidDocument.prototype.IsPDFPublished=function(){return this.PublishedPDFId()!=null;}
LucidDocument.prototype.PublishedPDFId=function(){if(this.PublicSegments==null)return null;for(var key in this.PublicSegments){if(this.PublicSegments[key].format=='pdf'&&this.PublicSegments[key].page==null)
return this.PublicSegments[key].id;}}
LucidDocument.prototype.IsModified=function(){return this.ActionHistory.length>this.LoadedActionHistory.length;}
LucidDocument.prototype.MarkAllActionsCommitted=function(RevisionSaved){if(g_Client.User!=null){var now=new Date();this.AddSaveHistory(g_Client.User.first_name+' '+g_Client.User.last_name,now.format("yyyy-mm-dd HH:MM:ss"),RevisionSaved-this.LoadedActionHistory.length);}
g_Client.Log.Log('update','**** MarkCommitted up til '+RevisionSaved+' ****');g_Client.Log.Log('maac',""+RevisionSaved);for(var i=this.LoadedActionHistory.length;i<RevisionSaved;i++)
this.LoadedActionHistory.push(CopyObject(this.ActionHistory[i]));}
LucidDocument.prototype.HasSetTitle=function(){var first=true;for(var i=0;i<this.ActionHistory.length;i++){var a=this.ActionHistory[i];if(a.Action=='SetProperty'&&a.id==null&&a.Property=='Title'){if(first)
first=false;else
return true;}}
return false;}
LucidDocument.prototype.SerializeChanges=function(IncludeSaved){var ToSerialize=[];for(var i=IncludeSaved?0:this.LoadedActionHistory.length;i<this.ActionHistory.length;i++){if(this.ActionHistory[i].Action=='LoadPlugin'){var a=CopyObject(this.ActionHistory[i]);a.Code='';ToSerialize.push(a);}
else{ToSerialize.push(this.ActionHistory[i]);}}
return JSON.stringify(ToSerialize);}
LucidDocument.prototype.Deserialize=function(ActionHistory,DocumentId,ConnectionId,SaveHistory,Callback){var StartTime=new Date();this.DocumentId=DocumentId;this.ConnectionId=ConnectionId;for(var i=0;i<SaveHistory.length;i++)
this.AddSaveHistory(SaveHistory[i].UserName,SaveHistory[i].Date,SaveHistory[i].Count,true);this.ActionHistory=[];this.ForceAllowActions=true;this.IsDeserializing=true;var ah=eval(ActionHistory);var me=this;var i=0;g_Client.LockUI('<span id="loadprogress">Loading: 0%</span>');var DeserializeInterval=setInterval(function(){var end=Math.min(ah.length,i+50);for(;i<end;i++)
me.RunAction(ah[i],true);$('#loadprogress').html('Loading: '+Math.round(i*100/ah.length)+'%');if(i==ah.length){g_Client.UnlockUI();clearInterval(DeserializeInterval);me.ForceAllowActions=false;me.LoadedActionHistory=ah;me.UndoHistory=[];g_Client.HistoryTab.UpdateSaveHistory();var EndTime=new Date();var Delta=EndTime.getTime()-StartTime.getTime();g_Client.Log.Log('load',JSON.stringify(Delta));if(Delta>30000)
g_Client.LogAction('loadTimeOver30Seconds');else if(Delta>15000)
g_Client.LogAction('loadTimeOver15Seconds');else if(Delta>10000)
g_Client.LogAction('loadTimeOver10Seconds');else if(Delta>5000)
g_Client.LogAction('loadTimeOver5Seconds');if($.cookie('nospeedcheck')==null){var CookieCheckbox="<p><input type='checkbox' id='nospeedcheckcookie'/> Don't tell me again.</p>";if(Delta>5000&&is_ie){jqAlert("<p>It took around "+Math.round(Delta/1000)+" seconds to load this "+Configure.document_text+" in IE.  You should consider using <b>Google Chrome</b>, which would load this "+Configure.document_text+" around <b>5 times faster</b>.</p>"+CookieCheckbox);}
if(Delta>5000&&is_firefox&&is_win){jqAlert("<p>It took around "+Math.round(Delta/1000)+" seconds to load this "+Configure.document_text+" in Firefox.  You should consider using <b>Google Chrome</b>, which would load this "+Configure.document_text+" around <b>2 times faster</b>.</p>"+CookieCheckbox);}
$('#nospeedcheckcookie').click(function(){if(this.checked)
$.cookie('nospeedcheck','true');else
$.cookie('nospeedcheck',null);});}
me.IsDeserializing=false;if(Callback)
Callback();}},1);}
LucidDocument.prototype.LockUpdates=function(){this.UpdatesLocked=true;this.PendingUpdates=[];}
LucidDocument.prototype.UnlockUpdates=function(){if(this.UpdatesLocked){this.UpdatesLocked=false;for(var i=0;i<this.PendingUpdates.length;i++)
this.Update(this.PendingUpdates[i][0],this.PendingUpdates[i][1],this.PendingUpdates[i][2],this.PendingUpdates[i][3]);}}
LucidDocument.prototype.Update=function(ActionHistory,SaveHistory,TotalActionHistoryLength,SavedActionHistoryLength){if(this.UpdatesLocked){this.PendingUpdates.push([ActionHistory,SaveHistory,TotalActionHistoryLength,SavedActionHistoryLength]);return null;}
if(this.ViewingHistory){var v=this.HistoryVersion;this.ExitHistoryView();var ret=this.Update(ActionHistory,SaveHistory,TotalActionHistoryLength,SavedActionHistoryLength);this.ViewRevision(v);return ret;}
g_Client.Log.Log('update',JSON.stringify({ActionHistory_length:JSON.parse(ActionHistory).length,SaveHistory_length:SaveHistory.length,TotalActionHistoryLength:TotalActionHistoryLength,SavedActionHistoryLength:SavedActionHistoryLength,this_ActionHistory_length:this.ActionHistory.length,this_LoadedActionHistory_length:this.LoadedActionHistory.length}));for(var i=this.LoadedActionHistory.length;i<SavedActionHistoryLength;i++)
this.LoadedActionHistory.push(CopyObject(this.ActionHistory[i]));var RemoteChanges=JSON.parse(ActionHistory);if(TotalActionHistoryLength!=null){while(TotalActionHistoryLength-this.LoadedActionHistory.length<RemoteChanges.length){if(SaveHistory.length==0)
return[];g_Client.Log.Log('update',JSON.stringify({a:'Removing some remote changes',RemovedRemoteChanges:SaveHistory[0].Count,NewRemoteChangeLength:RemoteChanges.length-SaveHistory[0].Count}));RemoteChanges.splice(0,SaveHistory[0].Count);SaveHistory.splice(0,1);}}
g_Client.Log.Log('update',JSON.stringify({TotalActionHistoryLength:TotalActionHistoryLength,this_LoadedActionHistory_length:this.LoadedActionHistory.length,RemoteChanges_length:RemoteChanges.length}));if(TotalActionHistoryLength!=this.LoadedActionHistory.length+RemoteChanges.length){}
var LocalChanges=[];for(var i=this.LoadedActionHistory.length;i<this.ActionHistory.length;i++)
LocalChanges.push(CopyObject(this.ActionHistory[i]));g_Client.Log.Log('update',JSON.stringify({LocalChanges_length:LocalChanges.length}));var UndoHistory=CopyObject(this.UndoHistory);var RedoHistory=CopyObject(this.RedoHistory);var Conflicts=[];var doc=this;var RemoteModifiedPage=function(id){for(var i=0;i<RemoteChanges.length;i++){if(RemoteChanges[i].Action=='CreateBlock'||RemoteChanges[i].Action=='RemoveBlock'||RemoteChanges[i].Action=='SetProperty'||RemoteChanges[i].Action=='CreateLine'||RemoteChanges[i].Action=='RemoveLine'){var Page=doc._FindObjectPage(RemoteChanges[i].id);if(Page.id==id)
return true;}
if(RemoteChanges[i].Action=='SetProperty'){if(RemoteChanges[i].id==id)
return true;}}
return false;}
var RemoteModifiedProperty=function(id,p){for(var i=0;i<RemoteChanges.length;i++){if(RemoteChanges[i].Action=='SetProperty'&&RemoteChanges[i].Property==p&&RemoteChanges[i].id==id)
return RemoteChanges[i];}
return false;}
var AlreadyPromptedPages=[];var PromptRestorePage=function(id){for(var i=0;i<AlreadyPromptedPages.length;i++){if(AlreadyPromptedPages[i]==id)
return false;}
var RemovePageChange=null;for(var r=0;r<RemoteChanges.length;r++){if(RemoteChanges[r].Action=='RemovePage'&&RemoteChanges[r].id==id){RemovePageChange=RemoteChanges[r];break;}}
if(confirm("You made changes to the page "+RemovePageChange.GetPropertyValue('Title')+".  Another user has removed this page from the "+Configure.document_text+".  Would you like to restore it?")){doc.RunAction(doc._GetReverseAction(RemovePageChange),true);return true;}
AlreadyPromptedPages.push(id);return false;}
var GetItemPageId=function(id){for(var i=0;i<doc.ActionHistory.length;i++){if(doc.ActionHistory[i].Action=='CreateBlock'||doc.ActionHistory[i].Action=='CreateLine'){if(doc.ActionHistory[i].id==id)
return doc.ActionHistory[i].Page;}}
for(var i=0;i<LocalChanges.length;i++){if(LocalChanges[i].Action=='CreateBlock'||LocalChanges[i].Action=='CreateLine'){if(LocalChanges[i].id==id)
return LocalChanges[i].Page;}}}
var IsPageId=function(id){for(var i=0;i<doc.ActionHistory.length;i++){if(doc.ActionHistory[i].Action=='CreatePage'){if(doc.ActionHistory[i].id==id)
return true;}}
return false;}
this.ForceAllowActions=true;for(var i=LocalChanges.length-1;i>=0;i--)
this._RunAction(this._GetReverseAction(LocalChanges[i]));this.ActionHistory=CopyObject(this.LoadedActionHistory);for(var i=0;i<RemoteChanges.length;i++){if(!this.RunAction(RemoteChanges[i],true)){g_Client.Log.Log('update','Failed running remote change: '+JSON.stringify(RemoteChanges[i]));}}
this.LoadedActionHistory=CopyObject(this.ActionHistory);for(var i=0;i<LocalChanges.length;i++){if(LocalChanges[i].Action=='CreatePage'){this.RunAction(LocalChanges[i],true);}
else if(LocalChanges[i].Action=='LoadPlugin'){this.RunAction(LocalChanges[i],true);}
else if(LocalChanges[i].Action=='SetProperty'){if(LocalChanges[i].id==null){this.RunAction(LocalChanges[i],true);}
else if(IsPageId(LocalChanges[i].id)){if(this.Pages[LocalChanges[i].id]==null){if(PromptRestorePage(LocalChanges[i].id))
this.RunAction(LocalChanges[i],true);}
else{this.RunAction(LocalChanges[i],true);}}
else{if(this._FindObject(LocalChanges[i].id)==null){var PageId=GetItemPageId(LocalChanges[i].id);if(this.Pages[PageId]==null){if(PromptRestorePage(PageId)){if(this._FindObject(LocalChanges[i].id)==null){}
else
this.RunAction(LocalChanges[i],true);}}
else{}}
else{var OtherChange=RemoteModifiedProperty(LocalChanges[i].id,LocalChanges[i].Property);if(OtherChange!=false){Conflicts.push({Action:CopyObject(LocalChanges[i]),ConflictAction:CopyObject(OtherChange),Type:'DoubleSetProperty'});this.RunAction(LocalChanges[i],true);}
else{this.RunAction(LocalChanges[i],true);}}}}
else if(LocalChanges[i].Action=='RemovePage'){var page=this.Pages[LocalChanges[i].id];if(page==null){}
else if(RemoteModifiedPage(LocalChanges[i].id)){if(confirm('Another user has modified the page '+page.GetPropertyValue('Title')+'.  You had deleted this page.  Would you still like to delete this page?'))
this.RunAction(LocalChanges[i],true);}
else{this.RunAction(LocalChanges[i],true);}}
else if(LocalChanges[i].Action=='CreateBlock'){if(this.Pages[LocalChanges[i].Page]==null){if(PromptRestorePage(LocalChanges[i].Page))
this.RunAction(LocalChanges[i],true);}
else{this.RunAction(LocalChanges[i],true);}}
else if(LocalChanges[i].Action=='RemoveBlock'){if(this._FindObjectPage(LocalChanges[i].id)!=null){if(this._FindObject(LocalChanges[i].id)!=null)
this.RunAction(LocalChanges[i],true);}}
else if(LocalChanges[i].Action=='RemoveLine'){if(this._FindObjectPage(LocalChanges[i].id)!=null){if(this._FindObject(LocalChanges[i].id)!=null){this.RunAction(LocalChanges[i],true);}
else{}}
else{}}
else if(LocalChanges[i].Action=='CreateLine'){if(this.Pages[LocalChanges[i].Page]==null){if(PromptRestorePage(LocalChanges[i].Page)){this.RunAction(LocalChanges[i],true);}}
else{this.RunAction(LocalChanges[i],true);}}
else if(LocalChanges[i].Action=='NoOp'){}
else{alert('Error!  Unknown action type '+LocalChanges[i].Action);}}
this.UndoHistory=UndoHistory;this.RedoHistory=RedoHistory;this.ForceAllowActions=false;for(var i=0;i<SaveHistory.length;i++)
this.AddSaveHistory(SaveHistory[i].UserName,SaveHistory[i].Date,SaveHistory[i].Count,true);g_Client.HistoryTab.UpdateSaveHistory();g_Client.Log.Log('update',JSON.stringify({this_ActionHistory_length:this.ActionHistory.length,this_LoadedActionHistory_length:this.LoadedActionHistory.length}));g_Client.Log.Log('update','---------------------------------');if(this.LoadedActionHistory.length!=TotalActionHistoryLength){}
return Conflicts;}
LucidDocument.prototype.PDFPageFilters=[];LucidDocument.prototype.FilterPDFPages=function(f){this.PDFPageFilters.push(f);}
LucidDocument.prototype.GetPDFData=function(page){var me=this;var ret={};this.EachOrderedPage(function(){if(page==null){for(var i=0;i<me.PDFPageFilters.length;i++){if(!me.PDFPageFilters[i](this))
return;}}
if(page==null||page==this)
ret[this.id]=this.GetPDFData();});return ret;}
LucidDocument.prototype.AllowMoreObjects=function(){if(!this.IsDeserializing&&g_Client.Level.document_objects>0){if(this.NumObjects>=g_Client.Level.document_objects>0){return false;}}
return true;}
LucidDocument.prototype.RunAction=function(a,IsNotUI){if(g_Client.CanEdit()||this.ForceAllowActions){if(!this.AllowMoreObjects()){if(a.Action=='CreatePage'||a.Action=='CreateBlock'||a.Action=='CreateLine'){if($('#cannotaddmore').size()==0)
jqAlert('<span id="cannotaddmore">You</span> cannot add more objects to this document.  Please consider upgrading.');return false;}}
var ret=this._RunAction(a);if(!ret){if(a.IsUndo||a.IsRedo){return false;}
else if(!this.DisplayedError){g_Client.LogAction('error');this.DisplayedError=true;a={Action:'NoOp'};}}
this.ActionHistory.push(a);this.StartUndoBatch();if(!a.IsUndo&&!a.IsRedo){this.UndoBatch.push(a);}
if(!IsNotUI){try{for(var i=0;i<this.UIActionHooks.length;i++){this.UIActionHooks[i](a);}}
catch(e){}}
this.EndUndoBatch();return ret;}
return false;}
LucidDocument.prototype.StartUndoBatch=function(){this.UndoBatchLevel++;}
LucidDocument.prototype.EndUndoBatch=function(){this.UndoBatchLevel--;this.UndoBatchLevel=Math.max(0,this.UndoBatchLevel);if(this.UndoBatchLevel==0&&this.UndoBatch.length>0){this.UndoHistory.push(this.UndoBatch);this.RedoHistory=[];this.UndoBatch=[];}}
LucidDocument.prototype.CanUndo=function(){return this.UndoHistory.length>0;}
LucidDocument.prototype.CanRedo=function(){return this.RedoHistory.length>0;}
LucidDocument.prototype.Undo=function(){if(this.UndoHistory.length==0)
return;var OldBatch=this.UndoHistory[this.UndoHistory.length-1];var NewBatch=[];for(var i=OldBatch.length-1;i>=0;i--){var a=this._GetReverseAction(OldBatch[i]);if(a!=null){a.IsUndo=true;delete a.IsRedo;NewBatch.push(a);this.RunAction(a,true);}}
this.UndoHistory.splice(this.UndoHistory.length-1,1);this.RedoHistory.splice(0,0,NewBatch);}
LucidDocument.prototype.Redo=function(){if(this.RedoHistory.length==0)
return;var OldBatch=this.RedoHistory[0];var NewBatch=[];for(var i=OldBatch.length-1;i>=0;i--){var a=this._GetReverseAction(OldBatch[i]);if(a!=null){a.IsRedo=true;delete a.IsUndo;NewBatch.push(a);this.RunAction(a,true);}}
this.RedoHistory.splice(0,1);this.UndoHistory.push(NewBatch);}
LucidDocument.prototype.ClearUndoHistory=function(){this.UndoHistory=[];this.RedoHistory=[];}
LucidDocument.prototype.HookActions=function(f){this.ActionHooks.push(f);}
LucidDocument.prototype.HookPostActions=function(f){this.PostActionHooks.push(f);}
LucidDocument.prototype.OnNextAction=function(f){this.NextActionHooks.push(f);}
LucidDocument.prototype.HookUIActions=function(f){this.UIActionHooks.push(f);}
LucidDocument.prototype.HookSelectionChange=function(f){this.SelectionChangeHooks.push(f);}
LucidDocument.prototype.EachPage=function(f){for(var key in this.Pages){if(f.call(this.Pages[key])=='stop')
return;}}
LucidDocument.prototype.EachOrderedPage=function(f){var p=this.GetOrderedPages();for(var i=0;i<p.length;i++){if(f.call(p[i])=='stop')
return;}}
LucidDocument.prototype.GetOrderedPages=function(Property){if(Property==null)Property='Order';var ret=[];this.EachPage(function(){ret.push(this);});ret.sort(function(a,b){return a.GetPropertyValue(Property)-b.GetPropertyValue(Property);});return ret;}
LucidDocument.prototype.MaxPageProperty=function(Property,ret){this.EachPage(function(){if(this.GetPropertyValue(Property)>ret||ret==null)
ret=this.GetPropertyValue(Property);});return ret;}
LucidDocument.prototype.ViewRevision=function(idx){if(this.ViewingHistory){var OldVersion=this.HistoryVersion;this.HistoryVersion=idx;if(this.HistoryVersion<OldVersion){for(var i=this.ActionHistory.length-1;i>=idx;i--){var a=this.ActionHistory[i];this.ActionHistory.splice(i,1);this.ReversedHistory.push(a);this._RunAction(this._GetReverseAction(a));}}
else if(this.HistoryVersion>OldVersion){var CountToRun=this.HistoryVersion-OldVersion;for(var i=0;i<CountToRun;i++){var h=this.ReversedHistory[this.ReversedHistory.length-1-i];this._RunAction(h);this.ActionHistory.push(h);}
this.ReversedHistory.splice(this.ReversedHistory.length-CountToRun,CountToRun);}}
else{g_Client.Viewport.InvalidateBackground();this.ViewingHistory=true;this.HistoryVersion=idx;this.ReversedHistory=[];for(var i=this.ActionHistory.length-1;i>=idx;i--){var a=this.ActionHistory[i];this.ActionHistory.splice(i,1);this.ReversedHistory.push(a);this._RunAction(this._GetReverseAction(a));}}}
LucidDocument.prototype.ExitHistoryView=function(){if(!this.ViewingHistory)
return;for(var i=this.ReversedHistory.length-1;i>=0;i--){this._RunAction(this.ReversedHistory[i]);this.ActionHistory.push(this.ReversedHistory[i]);}
this.ViewingHistory=false;g_Client.Viewport.InvalidateBackground();}
LucidDocument.prototype.RevertToHistoryVersion=function(){if(!this.ViewingHistory)
return;var Version=this.HistoryVersion;this.ExitHistoryView();this.StartUndoBatch();for(var i=this.ActionHistory.length-1;i>=Version;i--)
this.RunAction(this._GetReverseAction(this.ActionHistory[i]));this.EndUndoBatch();}
LucidDocument.prototype._GetReverseAction=function(a){var ret=CopyObject(a);switch(a.Action){case'CreatePage':ret.Action='RemovePage';break;case'RemovePage':ret.Action='CreatePage';ret.Recreate=true;break;case'CreateBlock':ret.Action='RemoveBlock';break;case'RemoveBlock':ret.Action='CreateBlock';break;case'CreateLine':ret.Action='RemoveLine';break;case'RemoveLine':ret.Action='CreateLine';break;case'SetProperty':ret.Value=a.OldValue;break;case'NoOp':break;default:return null;}
return ret;}
LucidDocument.prototype._RunAction=function(a){if(a==null)
return false;g_Client.Log.Log('a',JSON.stringify(a));for(var i=0;i<this.ActionHooks.length;i++){try{this.ActionHooks[i](a);}
catch(e){}}
for(var i=0;i<this.NextActionHooks.length;i++){try{this.NextActionHooks[i](a);}
catch(e){}}
this.NextActionHooks=[];switch(a.Action){case'LoadPlugin':eval(a.Code);this.AllPlugins.push(a.URL);break;case'CreatePage':if(a.id==null)
a.id=this._GetUniqueItemId();var page=new LucidPage(a.id,ObjectSize(this.Pages));page.HookSelectionChange(function(p){for(var i=0;i<g_Client.Document.SelectionChangeHooks.length;i++)
g_Client.Document.SelectionChangeHooks[i](p);});this.Pages[a.id]=page;var Template=this.GetPropertyValue('PageTemplate');var IdMap={};for(var i=0;i<Template.length;i++){if(Template[i].Properties&&Template[i].Properties.Endpoint1&&Template[i].Properties.Endpoint1.Block)
Template[i].Properties.Endpoint1.Block=IdMap[Template[i].Properties.Endpoint1.Block];if(Template[i].Properties&&Template[i].Properties.Endpoint2&&Template[i].Properties.Endpoint2.Block)
Template[i].Properties.Endpoint2.Block=IdMap[Template[i].Properties.Endpoint2.Block];if(Template[i].NewEndpoint&&Template[i].NewEndpoint.Block)
Template[i].NewEndpoint.Block=IdMap[Template[i].NewEndpoint.Block];if(Template[i].OldEndpoint&&Template[i].OldEndpoint.Block)
Template[i].OldEndpoint.Block=IdMap[Template[i].OldEndpoint.Block];if(Template[i].Value&&Template[i].Value.Block)
Template[i].Value.Block=IdMap[Template[i].Value.Block];if(Template[i].OldValue&&Template[i].OldValue.Block)
Template[i].OldValue.Block=IdMap[Template[i].OldValue.Block];if(Template[i].Action=='CreateBlock'||Template[i].Action=='CreateLine'){var id=Template[i].id;Template[i].id=null;Template[i].Page=a.id;this._RunAction(Template[i]);IdMap[id]=Template[i].id;}
if(Template[i].Action=='RemoveBlock'||Template[i].Action=='RemoveLine'||Template[i].Action=='SetProperty'){if(IdMap[Template[i].id]!=null)
Template[i].id=IdMap[Template[i].id];else
Template[i].id=a.id;this._RunAction(Template[i]);}}
if(a.Properties!=null){for(var Name in a.Properties)
page.SetPropertyValue(Name,a.Properties[Name]);}
if(a.Recreate){for(var i=0;i<this.ActionHistory.length;i++){if(this.ActionHistory[i].Action=='CreateBlock'||this.ActionHistory[i].Action=='CreateLine'){if(this.ActionHistory[i].Page==a.id)
this._RunAction(this.ActionHistory[i]);}
if(this.ActionHistory[i].Action=='RemoveBlock'||this.ActionHistory[i].Action=='RemoveLine'||this.ActionHistory[i].Action=='SetProperty'){var OldPageId=this.PageIdFromHistoricalItemId(this.ActionHistory[i].id);if(OldPageId==a.id||this.ActionHistory[i].id==a.id)
this._RunAction(this.ActionHistory[i]);}}}
break;case'RemovePage':var page=this.Pages[a.id];if(page==null)return false;if(ObjectSize(this.Pages)==1)
return false;this.NumObjects-=ObjectSize(page.Blocks)+ObjectSize(page.Lines);a.Properties=page.GetAllProperties();delete this.Pages[a.id];break;case'CreateBlock':if(a.id==null)
a.id=this._GetUniqueItemId();var page=this.Pages[a.Page];if(page==null)return false;var Class=eval(a.Class);var block=new Class(a.id);page.Blocks[a.id]=block;if(a.Properties!=null){for(var Name in a.Properties)
block.SetPropertyValue(Name,a.Properties[Name]);}
this.NumObjects++;break;case'RemoveBlock':var block=this._FindObject(a.id);if(block==null)return false;a.Properties=block.GetAllProperties();a.Class=block.Class;a.Page=this._FindObjectPage(a.id);if(a.Page==null)return false;a.Page=a.Page.id;this._RemoveBlock(a.id);this.NumObjects--;break;case'CreateLine':if(a.id==null)
a.id=this._GetUniqueItemId();var page=this.Pages[a.Page];if(page==null)return false;var line=new LucidLine(a.id);if(a.Properties!=null){for(var Name in a.Properties){if(Name=='Endpoint1'||Name=='Endpoint2'||Name=='Shape')
line.SetPropertyValue(Name,a.Properties[Name]);}
for(var Name in a.Properties){if(Name!='Endpoint1'&&Name!='Endpoint2'&&Name!='Shape')
line.SetPropertyValue(Name,a.Properties[Name]);}}
page.Lines[a.id]=line;this.NumObjects++;break;case'RemoveLine':var line=this._FindObject(a.id);if(line==null)return false;LucidLine.InvalidateJumps(line);a.Properties=line.GetAllProperties();a.Page=this._FindObjectPage(a.id);if(a.Page==null)return false;a.Page=a.Page.id;this._RemoveLine(a.id);this.NumObjects--;break;case'SetProperty':var item=this._FindObject(a.id);if(item==null)return false;a.OldValue=item.GetPropertyValue(a.Property);if(!item.SetPropertyValue(a.Property,a.Value))
return false;break;case'NoOp':break;default:return false;}
try{for(var i=0;i<this.PostActionHooks.length;i++){this.PostActionHooks[i](a);}}
catch(e){}
return true;}
LucidDocument.prototype._FindObjectPage=function(id){for(var pid in this.Pages){var ret=this.Pages[pid]._FindObject(id);if(ret!=null)
return this.Pages[pid];}
return null;}
LucidDocument.prototype._FindObject=function(id){if(id==null)
return this;if(this.Pages[id]!=null)
return this.Pages[id];for(var pid in this.Pages){var ret=this.Pages[pid]._FindObject(id);if(ret!=null)
return ret;}
return null;}
LucidDocument.prototype._RemoveBlock=function(id){if(id==null)
return;for(var pid in this.Pages)
this.Pages[pid]._RemoveBlock(id);}
LucidDocument.prototype._RemoveLine=function(id){if(id==null)
return;for(var pid in this.Pages)
this.Pages[pid]._RemoveLine(id);}
LucidDocument.prototype._IsIdUnique=function(id){for(var i=0;i<this.ActionHistory.length;i++){if(this.ActionHistory[i].id==id)
return false;}
return true;}
LucidDocument.prototype._GetUniqueItemId=function(){var id=this.ConnectionId+"_"+this.NextItemId;this.NextItemId++;if(this._IsIdUnique(id))
return id;else
return this._GetUniqueItemId();}
LucidDocument.prototype._PageTitleBeforeAction=function(id,idx){for(var i=idx-1;i>=0;i--){if(this.ActionHistory[i].Action=='CreatePage'){if(this.ActionHistory[i].id==id)
return this.ActionHistory[i].Properties.Title;}
if(this.ActionHistory[i].Action=='SetProperty'&&this.ActionHistory[i].Property=='Title'){if(this.ActionHistory[i].id==id)
return this.ActionHistory[i].Value;}}
return null;}
LucidDocument.prototype.PageIdFromHistoricalItemIdCache={};LucidDocument.prototype.PageIdFromHistoricalItemId=function(id){if(this.PageIdFromHistoricalItemIdCache[id])
return this.PageIdFromHistoricalItemIdCache[id];if(this.Pages[id]!=null){this.PageIdFromHistoricalItemIdCache[id]=id;return id;}
var pid=this._FindObjectPage(id);if(pid!=null){this.PageIdFromHistoricalItemIdCache[id]=pid.id;return pid.id;}
for(var i=0;i<this.ActionHistory.length;i++){if(this.ActionHistory[i].Action=='CreateBlock'||this.ActionHistory[i].Action=='CreateLine'){if(this.ActionHistory[i].id==id){this.PageIdFromHistoricalItemIdCache[id]=this.ActionHistory[i].Page;return this.ActionHistory[i].Page;}}
if(this.ActionHistory[i].Action=='CreatePage'){if(this.ActionHistory[i].id==id){this.PageIdFromHistoricalItemIdCache[id]=id;return id;}}}
return null;}


var LucidPage=function(id,order){SetupPropertyStore(this);this.RegisterProperty('Title','');this.RegisterProperty('Order',order);this.RegisterProperty('Size',{w:8.5*160,h:11*160});this.RegisterProperty('DPI',160);this.RegisterProperty('GridSpacing',20);this.RegisterProperty('Margin',.5);this.Blocks={};this.Lines={};this.id=id;this.IsPage=true;this.SelectionChangeHooks=[];var ClosestPageSize=function(w,h){for(var key in LucidPage.PageSizes){var Size=eval(key);if(Math.abs(Size.w-w)<0.1&&Math.abs(Size.h-h)<0.1)
return key;if(Math.abs(Size.w-h)<0.1&&Math.abs(Size.h-w)<0.1)
return key;}
for(var key in LucidPage.PageSizes)
return key;}
var me=this;this.AddPropertyControl('Page Size','PageSize',{Label:'Page Size',Type:'SelectButton',Width:71,Height:90,Options:LucidPage.PageSizeOptions(),Value:function(){var Size=this.GetPropertyValue('Size');var DPI=this.GetPropertyValue('DPI');return ClosestPageSize(Size.w/DPI,Size.h/DPI);},OnChange:function(val){var Size=eval(val);var DPI=this.GetPropertyValue('DPI');g_Client.LogAction('pageSize'+Size.w+'x'+Size.h);var OldSize=this.GetPropertyValue('Size');if(OldSize.w>OldSize.h)
Size={w:Size.h,h:Size.w};Size.w*=DPI;Size.h*=DPI;g_Client.Document.StartUndoBatch();g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'Size',Value:{w:Size.w,h:Size.h}});me.MoveItemsIntoPageSize(Size);g_Client.Document.EndUndoBatch();}});this.AddPropertyControl('Orientation','Orientation',{Label:'Orientation',Type:'SelectButton',Width:71,Height:80,Options:{'Portrait':'Portrait<br/><div style="width:38px;height:50px;border:1px solid black;background:white;margin:0px auto;"></div>','Landscape':'Landscape<br/><div style="width:50px;height:38px;border:1px solid black;background:white;margin:6px auto;"></div>'},Value:function(){var Size=this.GetPropertyValue('Size');return Size.h>Size.w?'Portrait':'Landscape';},OnChange:function(val){var Size=this.GetPropertyValue('Size');if(val=='Portrait')
Size={w:Math.min(Size.w,Size.h),h:Math.max(Size.w,Size.h)};else
Size={w:Math.max(Size.w,Size.h),h:Math.min(Size.w,Size.h)};g_Client.Document.StartUndoBatch();g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'Size',Value:Size});me.MoveItemsIntoPageSize(Size);g_Client.Document.EndUndoBatch();}});this.AddPropertyControl('Layout','Margin',{Label:'Margins',Type:'Select',Options:{0:'None',.25:'1/4"',.5:'1/2"',1:'1"',1.5:'1 1/2"',2:'2"'},Property:'Margin',Numeric:true});this.AddPropertyControl('Layout','Content Size',{Label:'Content Size',Type:'Select',Options:function(){var ret={320:'Very Small',240:'Small',160:'Normal',120:'Large',80:'Very Large'};if(ret[me.GetPropertyValue('DPI')]==null)
ret[me.GetPropertyValue('DPI')]='Custom';return ret;},Value:function(){return this.GetPropertyValue('DPI');},OnChange:function(val){var Size=this.GetPropertyValue('Size');var OldDPI=this.GetPropertyValue('DPI');Size.w*=val/OldDPI;Size.h*=val/OldDPI;g_Client.Document.StartUndoBatch();g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'Size',Value:Size});g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'DPI',Value:val});me.MoveItemsIntoPageSize(Size);g_Client.Document.EndUndoBatch();g_Client.LogAction('changeContentSize');}});this.RegisterProperty('FillColor','#ffffff');this.AddPropertyControl('Colors','FillColor',{Label:'Background',Type:'Color',Property:'FillColor'});this.PublishedSegments=[];}
LucidPage.PageSizes={};LucidPage.prototype.ClearPublishedSegments=function(){this.PublishedSegments=[];g_Client.Viewport.Invalidate();}
LucidPage.prototype.AddPublishedSegment=function(x,y,w,h){this.PublishedSegments.push({x:x,y:y,w:w,h:h});g_Client.Viewport.Invalidate();}
LucidPage.prototype.IncomingLines=function(b){var ret=[];this.EachLine(function(){if(this.GetPropertyValue('Endpoint2',true).Block==b.id)
ret.push(this);});return ret;}
LucidPage.prototype.EverythingDownstream=function(b){var ret=[];var check=[b];var page=this;var checked={};while(check.length>0){var block=check[0];check.splice(0,1);if(checked[block.id])
continue;checked[block.id]=true;ret.push(block);$.map(this.OutgoingLines(block),function(line){ret.push(line);var ep2=line.GetPropertyValue('Endpoint2');if(ep2.Block!=null){var other=page.Blocks[ep2.Block];if(other!=null)
check.push(other);}});}
return ret;}
LucidPage.prototype.OutgoingLines=function(b){var ret=[];this.EachLine(function(){if(this.GetPropertyValue('Endpoint1',true).Block==b.id)
ret.push(this);});return ret;}
LucidPage.prototype.BlocksOverlappingBoundingBox=function(test){var ret=[];this.EachBlock(function(){var bb=this.GetPropertyValue('BoundingBox');if(bb.x>test.x+test.w)
return;if(bb.y>test.y+test.h)
return;if(bb.x+bb.w<test.x)
return;if(bb.y+bb.h<test.y)
return;ret.push(this);});return ret;}
LucidPage.prototype.ContentBoundingBox=function(){var MinX=null;var MinY=null;var MaxX=null;var MaxY=null;this.EachBlock(function(){var bb=this.GetPropertyValue('BoundingBox');MinX=MinX==null?bb.x:Math.min(MinX,bb.x);MinY=MinY==null?bb.y:Math.min(MinY,bb.y);MaxX=MaxX==null?bb.x+bb.w:Math.max(MaxX,bb.x+bb.w);MaxY=MaxY==null?bb.y+bb.h:Math.max(MaxY,bb.y+bb.h);});this.EachLine(function(){function OnePoint(ep){MinX=MinX==null?ep.x:Math.min(MinX,ep.x);MinY=MinY==null?ep.y:Math.min(MinY,ep.y);MaxX=MaxX==null?ep.x:Math.max(MaxX,ep.x);MaxY=MaxY==null?ep.y:Math.max(MaxY,ep.y);}
var p=this.GetPropertyValue('Points',true);for(var i=0;i<p.length;i++)
OnePoint(p[i]);});return{x:MinX,y:MinY,w:MaxX-MinX,h:MaxY-MinY};}
LucidPage.prototype.ExpandPage=function(threshold,margin){var bb=this.ContentBoundingBox();if(bb.w==0||bb.h==0)
return{x:0,y:0};var Size=this.GetPropertyValue('Size');if(bb.x>threshold&&bb.y>threshold&&bb.x+bb.w<Size.w-threshold&&bb.y+bb.h<Size.h-threshold)
return{x:0,y:0};if(bb.w+margin*2==Size.w&&bb.h+margin*2==Size.h)
return{x:0,y:0};g_Client.Document.StartUndoBatch();g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'Size',Value:{w:bb.w+margin*2,h:bb.h+margin*2}});var Offset={x:(bb.w+margin*2)/2-(bb.x+bb.w/2),y:(bb.h+margin*2)/2-(bb.y+bb.h/2)};var me=this;if(Offset.x!=0||Offset.y!=0){this.EachLine(function(){function OneEndpoint(name){var ep=this.GetPropertyValue(name,true);g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:name,Value:{x:ep.x+me.SnapToGrid(Offset.x),y:ep.y+me.SnapToGrid(Offset.y)}});}
OneEndpoint.call(this,'Endpoint1');OneEndpoint.call(this,'Endpoint2');});this.EachBlock(function(){var bb=this.GetPropertyValue('BoundingBox');g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'BoundingBox',Value:{x:bb.x+me.SnapToGrid(Offset.x),y:bb.y+me.SnapToGrid(Offset.y),w:bb.w,h:bb.h}});});}
g_Client.Document.EndUndoBatch();return Offset;}
LucidPage.prototype.FitContent=function(){var me=this;var ContentBB=this.ContentBoundingBox();var MinX=ContentBB.x;var MinY=ContentBB.y;var MaxX=ContentBB.x+ContentBB.w;var MaxY=ContentBB.y+ContentBB.h;var Size=this.GetPropertyValue('Size');var DPI=this.GetPropertyValue('DPI');var Margin=this.GetPropertyValue('Margin');Size.w-=Margin*DPI*2;Size.h-=Margin*DPI*2;Size.w/=DPI;Size.h/=DPI;DPI=Math.round(Math.max((MaxX-MinX)/Size.w,(MaxY-MinY)/Size.h));g_Client.Document.StartUndoBatch();g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'DPI',Value:DPI});g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'Size',Value:{w:(Size.w+Margin*2)*DPI,h:(Size.h+Margin*2)*DPI}});this.EachLine(function(){function OneEndpoint(name){var ep=this.GetPropertyValue(name,true);g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:name,Value:{x:ep.x+me.SnapToGrid(Margin*DPI-MinX),y:ep.y+me.SnapToGrid(Margin*DPI-MinY)}});}
OneEndpoint.call(this,'Endpoint1');OneEndpoint.call(this,'Endpoint2');});this.EachBlock(function(){var bb=this.GetPropertyValue('BoundingBox');g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'BoundingBox',Value:{x:bb.x+me.SnapToGrid(Margin*DPI-MinX),y:bb.y+me.SnapToGrid(Margin*DPI-MinY),w:bb.w,h:bb.h}});});g_Client.Document.EndUndoBatch();}
LucidPage.prototype.MoveItemsIntoPageSize=function(Size){var me=this;if(Size==null)
Size=this.GetPropertyValue('Size');this.EachBlock(function(){var bb=this.GetPropertyValue('BoundingBox');var Offset={x:0,y:0};if(bb.x<0)
Offset.x=-bb.x;if(bb.y<0)
Offset.y=-bb.y;if(bb.x+bb.w>Size.w)
Offset.x=Size.w-(bb.x+bb.w);if(bb.y+bb.h>Size.h)
Offset.y=Size.h-(bb.y+bb.h);if(Offset.x!=0||Offset.y!=0){g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'BoundingBox',Value:{x:bb.x+Offset.x,y:bb.y+Offset.y,w:bb.w,h:bb.h}});}});this.EachLine(function(){function OneEndpoint(name){var ep=this.GetPropertyValue(name,true);var Offset={x:0,y:0};if(ep.x<0)
Offset.x=-ep.x;if(ep.y<0)
Offset.y=-ep.y;if(ep.x>Size.w)
Offset.x=Size.w-ep.x;if(ep.y>Size.h)
Offset.y=Size.h-ep.y;if(Offset.x!=0||Offset.y!=0){g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:name,Value:{x:ep.x+Offset.x,y:ep.y+Offset.y}});}}
OneEndpoint.call(this,'Endpoint1');OneEndpoint.call(this,'Endpoint2');});}
LucidPage.AddPageSize=function(Name,w,h){var exampleWidth=50*w/h;var example='<div style="margin:0 auto;width:'+exampleWidth+'px;height:50px;background:white;border:1px solid black;"></div>';LucidPage.PageSizes["({w:"+w+",h:"+h+"})"]=Name+"<br/>"+example+"<span style='font-size:10px;'>"+w+"<span style='font-size:6px'> x </span>"+h+"\"</span>";}
LucidPage.AddPageSize('Letter',8.5,11);LucidPage.AddPageSize('Legal',8.5,14);LucidPage.AddPageSize('Executive',7.25,10.5);LucidPage.AddPageSize('A3',11.69,16.54);LucidPage.AddPageSize('A4',8.27,11.69);LucidPage.AddPageSize('A5',5.83,8.27);LucidPage.AddPageSize('Tabloid',11,17);LucidPage.AddPageSize('Folio',8.5,13);LucidPage.AddPageSize('Statement',5.5,8.5);LucidPage.PageSizeOptions=function(){var ret=[];var row={};for(var key in LucidPage.PageSizes){if(ObjectSize(row)==3){ret.push(row);row={};}
row[key]=LucidPage.PageSizes[key];}
if(ObjectSize(row)>0)
ret.push(row);return ret;}
LucidPage.prototype.GetPDFData=function(){var s=this.GetPropertyValue('Size');c=new RGBColor(this.GetPropertyValue('FillColor'));var ret={GridSpacing:this.GetPropertyValue('GridSpacing'),Width:s.w,Height:s.h,DPI:this.GetPropertyValue('DPI'),Gradient:g_Client.Document.GetPropertyValue('Gradient'),FillColor:{r:c.r,g:c.g,b:c.b,a:c.a},Blocks:[],Lines:[],Containers:[]};var blocks=this.GetOrderedBlocks();for(var i=0;i<blocks.length;i++){if(blocks[i].IsContainer)
ret.Containers.push(blocks[i].GetPDFData());else
ret.Blocks.push(blocks[i].GetPDFData());}
var lines=this.GetOrderedLines();LucidLine._PreRender(lines);for(var i=0;i<lines.length;i++)
ret.Lines.push(lines[i].GetPDFData());return ret;}
LucidPage.prototype.SnapToGrid=function(x,subdivide){if(x==null)
return null;if(typeof(x)=='object'){var ret=CopyObject(x);for(var key in ret)
ret[key]=this.SnapToGrid(ret[key]);return ret;}
else{var Spacing=this.GetPropertyValue('GridSpacing');if(subdivide!=null)Spacing/=subdivide;return Math.round(x/Spacing)*Spacing;}}
LucidPage.prototype.EachBlock=function(f){for(var key in this.Blocks){if(f.call(this.Blocks[key])=='stop')
return;}}
LucidPage.prototype.EachLine=function(f){for(var key in this.Lines){if(f.call(this.Lines[key])=='stop')
return;}}
LucidPage.prototype.EachItem=function(f){for(var key in this.Blocks){if(f.call(this.Blocks[key])=='stop')
return;}
for(var key in this.Lines){if(f.call(this.Lines[key])=='stop')
return;}}
LucidPage.prototype.EachOrderedItem=function(f){var b=this.GetOrderedBlocks();for(var i=b.length-1;i>=0;i--){if(f.call(b[i])=='stop')
return;}
var l=this.GetOrderedLines();for(var i=l.length-1;i>=0;i--){if(f.call(l[i])=='stop')
return;}}
LucidPage.prototype.EachSelectedItem=function(f){for(var key in this.Blocks){if(this.Blocks[key].Selected){if(f.call(this.Blocks[key])=='stop')
return;}}
for(var key in this.Lines){if(this.Lines[key].Selected){if(f.call(this.Lines[key])=='stop')
return;}}}
LucidPage.prototype.GetOrderedBlocks=function(Property){if(Property==null)Property='ZOrder';var ret=[];this.EachBlock(function(){ret.push(this);});ret.sort(function(a,b){return a.GetPropertyValue(Property)-b.GetPropertyValue(Property);});return ret;}
LucidPage.prototype.GetOrderedLines=function(Property){if(Property==null)Property='ZOrder';var ret=[];this.EachLine(function(){ret.push(this);});ret.sort(function(a,b){return a.GetPropertyValue(Property)-b.GetPropertyValue(Property);});return ret;}
LucidPage.prototype.MaxProperty=function(Property,ret){this.EachItem(function(){if(this.GetPropertyValue(Property)>ret||ret==null)
ret=this.GetPropertyValue(Property);});return ret;}
LucidPage.prototype.MinProperty=function(Property,ret){this.EachItem(function(){if(this.GetPropertyValue(Property)<ret||ret==null)
ret=this.GetPropertyValue(Property);});return ret;}
LucidPage.prototype.MaxSelectedProperty=function(Property,ret){this.EachItem(function(){if(this.Selected){if(this.GetPropertyValue(Property)>ret||ret==null)
ret=this.GetPropertyValue(Property);}});return ret;}
LucidPage.prototype.MinSelectedProperty=function(Property,ret){this.EachItem(function(){if(this.Selected){if(this.GetPropertyValue(Property)<ret||ret==null)
ret=this.GetPropertyValue(Property);}});return ret;}
LucidPage.prototype.HitTest=function(x,y,Skip,alt){var ret=null;this.EachOrderedItem(function(){if(this==Skip)
return;if(this.Selected){var Hit=this.HitTest(x,y,alt);if(Hit!=null){ret=Hit;return'stop';}}});if(ret!=null)
return ret;this.EachOrderedItem(function(){if(this==Skip)
return;var Hit=this.HitTest(x,y,alt);if(Hit!=null){ret=Hit;return'stop';}});return ret;}
LucidPage.prototype.HookSelectionChange=function(f){this.SelectionChangeHooks.push(f);}
LucidPage.prototype.UnselectAll=function(){this.EachItem(function(){this.Selected=false;});g_Client.Viewport.Invalidate();for(var i=0;i<this.SelectionChangeHooks.length;i++)
this.SelectionChangeHooks[i](this);}
LucidPage.prototype.GetSelection=function(){var ret=[];this.EachItem(function(){if(this.Selected)
ret.push(this);});return ret;}
LucidPage.prototype.SelectItem=function(i){i.Selected=true;g_Client.Viewport.Invalidate();for(var i=0;i<this.SelectionChangeHooks.length;i++)
this.SelectionChangeHooks[i](this);}
LucidPage.prototype.UnselectItem=function(i){i.Selected=false;g_Client.Viewport.Invalidate();for(var i=0;i<this.SelectionChangeHooks.length;i++)
this.SelectionChangeHooks[i](this);}
LucidPage.prototype._FindObject=function(id){if(this.Blocks[id]!=null)
return this.Blocks[id];if(this.Lines[id]!=null)
return this.Lines[id];return null;}
LucidPage.prototype._RemoveBlock=function(id){if(this.Blocks[id]!=null)
delete this.Blocks[id];}
LucidPage.prototype._RemoveLine=function(id){if(this.Lines[id]!=null)
delete this.Lines[id];}


function SetupPropertyStore(o){o.Properties={};o.PropertyControls={};o.SetPropertyHooks=[];o.RegisterProperty=function(Name,Value,PreSave,PostSave){o.Properties[Name]={Name:Name,Value:null,PreSave:[],PostSave:[],Object:typeof(Value)=='object'};o.HookPropertyPreSave(Name,PreSave);o.HookPropertyPostSave(Name,PostSave);o.SetPropertyValue(Name,Value);}
o.HookPropertyPreSave=function(Name,f){if(f!=null)
o.Properties[Name].PreSave.push(f);}
o.HookPropertyPostSave=function(Name,f){if(f!=null){if(Name==null)
o.SetPropertyHooks.push(f);else
o.Properties[Name].PostSave.push(f);}}
o.GetPropertyValue=function(Name,NoCopy){var p=this.Properties[Name];if(p==null)
return null;if(p.Object&&!NoCopy)
return CopyObject(p.Value);else
return p.Value;}
o.SetPropertyValue=function(Name,Value,NoCopy){var p=this.Properties[Name];if(p==null)
return false;for(var i=0;i<p.PreSave.length;i++)
Value=p.PreSave[i].call(p,Value);var OldValue=p.Value;if(p.Object&&!NoCopy)
p.Value=CopyObject(Value);else
p.Value=Value;for(var i=0;i<p.PostSave.length;i++)
p.PostSave[i].call(p,OldValue,Value);for(var i=0;i<o.SetPropertyHooks.length;i++)
o.SetPropertyHooks[i].call(p,OldValue,Value);return true;}
o.GetAllProperties=function(){var ret={};for(var Name in this.Properties)
ret[Name]=this.GetPropertyValue(Name);return ret;}
o.AddPropertyControl=function(Category,Key,Settings){if(this.PropertyControls[Category]==null)
this.PropertyControls[Category]={};Settings.me=this;if(Settings.Value==null&&Settings.Property!=null){Settings.Value=function(){return this.GetPropertyValue(Settings.Property);};}
if(Settings.OnChange==null&&Settings.Property!=null){Settings.OnChange=function(val){g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:Settings.Property,Value:Settings.Numeric?parseFloat(val):val});}}
this.PropertyControls[Category][Key]=Settings;}}
function IntersectPropertyControls(base,p){var CreateMergedValueFunction=function(a,b){return function(){var av=a.Value.call(a.me);var bv=b.Value.call(b.me);if(av==bv)
return av;return null;}}
var CreateMergedOnChangeFunction=function(a,b){return function(val){g_Client.Document.StartUndoBatch();a.OnChange.call(a.me,val);b.OnChange.call(b.me,val);g_Client.Document.EndUndoBatch();}}
var ret={};for(var Category in base){if(p[Category]==null)
continue;for(var key in base[Category]){if(p[Category][key]==null)
continue;if(ret[Category]==null)
ret[Category]={};var c={};for(var ckey in base[Category][key]){if(ckey=='Value')
c[ckey]=CreateMergedValueFunction(base[Category][key],p[Category][key]);else if(ckey=='OnChange')
c[ckey]=CreateMergedOnChangeFunction(base[Category][key],p[Category][key]);else
c[ckey]=base[Category][key][ckey];}
ret[Category][key]=c;}}
return ret;}
function UnionPropertyControls(base,p){var CreateMergedValueFunction=function(a,b){return function(){var av=a.Value.call(a.me);var bv=b.Value.call(b.me);if(av==bv)
return av;return null;}}
var CreateMergedOnChangeFunction=function(a,b){return function(val){g_Client.Document.StartUndoBatch();a.OnChange.call(a.me,val);b.OnChange.call(b.me,val);g_Client.Document.EndUndoBatch();}}
var ret={};for(var Category in base){ret[Category]={};for(var key in base[Category]){var c={};for(var ckey in base[Category][key])
c[ckey]=base[Category][key][ckey];ret[Category][key]=c;}}
for(var Category in p){if(ret[Category]==null)
ret[Category]={};for(var key in p[Category]){if(ret[Category][key]==null){var c={};for(var ckey in p[Category][key])
c[ckey]=p[Category][key][ckey];ret[Category][key]=c;}
else{ret[Category][key].Value=CreateMergedValueFunction(base[Category][key],p[Category][key]);ret[Category][key].OnChange=CreateMergedOnChangeFunction(base[Category][key],p[Category][key]);}}}
return ret;}
function GetPropertyControlsMarkup(p,prefix){var ret=new StringBuilder();for(var Category in p){ret.append('<li>'+Category+'<ul>');for(var key in p[Category]){var c=p[Category][key];var id='PropertyControl_'+prefix+'_'+Category.replace(/[^a-zA-Z0-9]/g,'')+'_'+key.replace(/[^a-zA-Z0-9]/g,'');var style='';if(c.Value)
var val=c.Value.call(c.me);if(c.Type=='Text'){ret.append('<li><label>').append(c.Label).append('</label>');if(val==null){val='';style='background:#ffff99';}
ret.append('<input id="').append(id).append('" style="').append(style).append('" type="text" value="').append(val).append('"/>');ret.append('</li>');}
if(c.Type=='Select'){ret.append('<li><label>').append(c.Label).append('</label>');if(val==null)
style='background:#ffff99';ret.append('<select id="').append(id).append('" style="').append(style).append('">');if(val==null)
ret.append('<option value=""></option>');var op=c.Options;if(typeof op=='function')
op=op();for(var skey in op){var selected='';if(skey==val)
selected='selected="selected"';ret.append('<option ').append(selected).append(' value="').append(skey).append('">').append(op[skey]).append('</option>');}
ret.append('</select>');ret.append('</li>');}
if(c.Type=='SelectButton'){ret.append('<div id="').append(id).append('" class="fg-buttonset fg-buttonset-single" style="margin-bottom:6px;clear:both;width:240px;">');var op=c.Options;if(typeof op=='function')
op=op();function oneRow(op,classAll,classLeft,classRight){var idx=0;for(var skey in op){var classes=classAll;if(skey==val)
classes+=' ui-state-active';if(idx==0)
classes+=' '+classLeft;if(idx==ObjectSize(op)-1)
classes+=' '+classRight;idx++;var style='';if(c.Width!=null)
style+='width:'+c.Width+'px;';if(c.Height!=null)
style+='height:'+c.Height+'px;';ret.append('<div style="').append(style).append('" value="').append(skey).append('" class="').append(classes).append(' fg-button ui-state-default ui-priority-primary">').append(op[skey]).append('</div>');}}
if(IsArray(op)){for(var i=0;i<op.length;i++){var classLeft=[];var classRight=[];if(i==0){classLeft.push('ui-corner-tl');classRight.push('ui-corner-tr');}
if(i==op.length-1){classLeft.push('ui-corner-bl');classRight.push('ui-corner-br');}
oneRow(op[i],i==0?'':'ui-no-top-border',classLeft.join(' '),classRight.join(' '));ret.append('<br/>');}}
else
oneRow(op,'','ui-corner-left','ui-corner-right');ret.append('</div>');}
if(c.Type=='Color'){ret.append('<li><label>').append(c.Label).append('</label>');if(val==null){val='';style='background:#ffff99';}
ret.append('<input id="').append(id).append('" style="').append(style).append('" type="text" value="').append(val).append('"/>');ret.append('</li>');}
if(c.Type=='Buttons'){ret.append('<li><label>').append(c.Label).append('</label>');var idx=0;for(var key in c.Buttons){if(idx>0)
ret.append('<br/><label>&nbsp;</label>');ret.append('<input id="').append(id).append('_'+key.replace(/[^a-zA-Z0-9]/g,'')).append('" type="button" value="'+key+'"/>');idx++;}
ret.append('</li>');}}
ret.append('</ul></li>');}
return ret.toString();}
function SetPropertyControlsEvents(p,prefix){var SetOneEvent=function(item,id){if(item.Type=='Buttons'){for(var key in item.Buttons){(function(key){$('#'+id+'_'+key.replace(/[^a-zA-Z0-9]/g,'')).click(function(){item.Buttons[key]();});})(key);}}
else if(item.Type=='SelectButton'){$('#'+id).find('div.fg-button').click(function(){item.OnChange.call(item.me,$(this).attr('value'));});}
else{$('#'+id).change(function(){var val='';if(item.Type=='Text'||item.Type=='Select'||item.Type=='Color')
val=$('#'+id).val();item.OnChange.call(item.me,val);});if(item.Type=='Color'){$('#'+id).colorPicker();}}}
for(var Category in p){for(var key in p[Category]){var id='PropertyControl_'+prefix+'_'+Category.replace(/[^a-zA-Z0-9]/g,'')+'_'+key.replace(/[^a-zA-Z0-9]/g,'');SetOneEvent(p[Category][key],id);}}}


var LucidBlock=function(){}
LucidBlock.NextBlockClasses={};LucidBlock.CreateNextBlockGroup=function(all){for(var i=0;i<all.length;i++){if(LucidBlock.NextBlockClasses[all[i]]==null)
LucidBlock.NextBlockClasses[all[i]]=[];for(var j=0;j<all.length;j++)
LucidBlock.NextBlockClasses[all[i]].push(all[j]);}}
LucidBlock.prototype._InitBlock=function(id){this.id=id;this.IsBlock=true;this.Selected=false;this.TextCursor='text';this.TextAreas=[];SetupPropertyStore(this);var block=this;this.RegisterProperty('BoundingBox',{x:0,y:0,w:160,h:120},null,function(o,v){try{var Offset=null;if(o!=null){Offset={x:v.x-o.x,y:v.y-o.y,w:v.w-o.w,h:v.h-o.h};}
var page=g_Client.Document._FindObjectPage(id);if(page==null)
return;page.EachLine(function(){var ep1=this.GetPropertyValue('Endpoint1',true);var ep2=this.GetPropertyValue('Endpoint2',true);if(ep1.Block==id){this.SetPropertyValue('Endpoint1',{x:block.RelativeX(ep1.LinkX,Offset),y:block.RelativeY(ep1.LinkY,Offset)},true);}
if(ep2.Block==id){this.SetPropertyValue('Endpoint2',{x:block.RelativeX(ep2.LinkX,Offset),y:block.RelativeY(ep2.LinkY,Offset)},true);}});}
catch(e){}});this.RegisterProperty('LineColor','#000000');this.RegisterProperty('FillColor','#ffffff');this.RegisterProperty('LineWidth',2);this.RegisterProperty('ZOrder',0);this.RegisterProperty('TextAlign','center');this.RegisterProperty('Font','times');this.AddPropertyControl('Colors','LineColor',{Label:'Line Color',Type:'Color',Property:'LineColor'});this.AddPropertyControl('Colors','FillColor',{Label:'Background',Type:'Color',Property:'FillColor'});this.AddPropertyControl('Style','Font',{Label:'Font',Type:'SelectButton',Options:{'times':'<span style="font-family:times;font-size:18px;">Times</span>','helvetica':'<span style="font-family:helvetica;font-size:18px;">Helvetica</span>'},Property:'Font'});this.AddPropertyControl('Style','TextAlign',{Label:'Text Align',Type:'SelectButton',Options:{'left':'<img src="/img/editor/left.png"/>','center':'<img src="/img/editor/center.png"/>','right':'<img src="/img/editor/right.png"/>'},Property:'TextAlign'});this.AddPropertyControl('Style','LineWidth',{Label:'Line Width',Type:'SelectButton',Options:{1:'<img src="/img/editor/width1.png"/>',2:'<img src="/img/editor/width2.png"/>',4:'<img src="/img/editor/width4.png"/>',8:'<img src="/img/editor/width8.png"/>'},Property:'LineWidth',Numeric:true});var b=this;var AddBoundingBoxPart=function(Key,Part){b.AddPropertyControl('Block Location',Key,{Label:Key,Type:'Text',Value:function(){return this.GetPropertyValue('BoundingBox')[Part];},OnChange:function(val){var bb=this.GetPropertyValue('BoundingBox');bb[Part]=g_Client.Viewport.SelectedPage.SnapToGrid(parseFloat(val));g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'BoundingBox',Value:bb});}});}
AddBoundingBoxPart('X','x');AddBoundingBoxPart('Y','y');AddBoundingBoxPart('Width','w');AddBoundingBoxPart('Height','h');this.LayerPadding=function(bb){return 8;}
this.Dirty=false;this.HookPropertyPostSave(null,function(o,v){if(this.Name!='BoundingBox')
b.Dirty=true;});}
LucidBlock.prototype._AddTextArea=function(PropertyName,Default,fBB,WantReturn,ReadOnly){this.RegisterProperty(PropertyName,Default,function(v){return InlineEditor.Finalize('testtext',v,1);});var ta={Name:PropertyName,BoundingBox:fBB,DivId:'textarea_'+this.id+'_'+PropertyName.replace(/[^a-zA-Z0-9]/g,''),WantReturn:WantReturn,Index:this.TextAreas.length,ReadOnly:ReadOnly,Dirty:false};this.TextAreas.push(ta);this.HookPropertyPostSave(PropertyName,function(OldValue,Value){if(Value!=OldValue)
ta.Dirty=true;});}
LucidBlock.prototype.AfterEditText=function(){}
LucidBlock.prototype._EditText=function(a){if(a.ReadOnly)
return;var TextDiv=$('#'+a.DivId);if(TextDiv.size()==0){var b=this;setTimeoutFunction(function(){b._EditText(a);},50);return;}
if(TextDiv.attr('IsEditing'))
return;if(is_ie)
g_Client.Viewport.Canvas.container.get(0).insertAdjacentElement('afterEnd',this.Layer.container.get(0));else
g_Client.Viewport.Canvas.container.append(this.Layer.container);if(is_chrome||is_safari)
g_Client.Viewport.Canvas.container.css({overflow:'visible'});var b=this;InlineEditor.Create(a.DivId,g_Client.Viewport.Scale,function(val){g_Client.Viewport.Invalidate();g_Client.Document.StartUndoBatch();if(val!=b.GetPropertyValue(a.Name)){g_Client.Document.RunAction({Action:'SetProperty',id:b.id,Property:a.Name,Value:val});}
b.AfterEditText();g_Client.Document.EndUndoBatch();},a.WantReturn);if(this.TextAreas.length>1){function OnKeyDown(e){if(TextDiv.attr('IsEditing')){if(e.which==9||e.keyCode==9){TextDiv.blur();if(e.shiftKey)
var NewIndex=(a.Index+1)%b.TextAreas.length;else
var NewIndex=(a.Index+b.TextAreas.length-1)%b.TextAreas.length;b._EditText(b.TextAreas[NewIndex]);return false;}
TextDiv.one('keydown',OnKeyDown);}}
TextDiv.one('keydown',OnKeyDown);}
return TextDiv;}
LucidBlock.prototype.ClosestLinkPoint=function(x,y){var bb=this.GetPropertyValue('BoundingBox');x=(x-bb.x)/bb.w;y=(y-bb.y)/bb.h;var minDistSq=100000000;var ret=null;for(var i=0;i<this.LinkPoints.length;i++){var distSq=(x-this.LinkPoints[i].x)*(x-this.LinkPoints[i].x)+(y-this.LinkPoints[i].y)*(y-this.LinkPoints[i].y);if(distSq<minDistSq){ret=this.LinkPoints[i];minDistSq=distSq;}}
return ret;}
LucidBlock.prototype.EachAttachedLine=function(f){var block=this;var page=g_Client.Document._FindObjectPage(this.id);if(page==null)
return;page.EachLine(function(){var ep1=this.GetPropertyValue('Endpoint1',true);var ep2=this.GetPropertyValue('Endpoint2',true);if(ep1.Block==block.id||ep2.Block==block.id)
return f.call(this,ep1.Block==block.id,ep2.Block==block.id);});}
LucidBlock.prototype.GetPDFData=function(){var t=[];for(var i=0;i<this.TextAreas.length;i++){t.push({BoundingBox:this.TextAreas[i].BoundingBox(this.GetBoundingBox()),Text:this.GetPropertyValue(this.TextAreas[i].Name),Align:this.GetPropertyValue('TextAlign'),Font:this.GetPropertyValue('Font'),Link:this.GetTextLink(this.TextAreas[i])});}
return{id:this.id,Text:t,RenderData:this.GetPDFRenderData()};}
LucidBlock.prototype.GetTextLink=function(t){return null;}
LucidBlock.prototype.GetRenderData=function(Offset,Type){var ret=this._GetRenderData(Offset,Type);if(Type!='sample')
ret=RoundRenderData(ret,g_Client.Document.GetPropertyValue('RoundCorners'));return ret;}
LucidBlock.prototype.GetPDFRenderData=function(){var RenderData=this.GetRenderData(null,'pdf');var c;for(var i=0;i<RenderData.length;i++){if(RenderData[i].FillColor){g_Client.Log.Log('color','checking color '+RenderData[i].FillColor);c=new RGBColor(RenderData[i].FillColor);RenderData[i].FillColor={r:c.r,g:c.g,b:c.b,a:c.a};}
if(RenderData[i].StrokeColor){c=new RGBColor(RenderData[i].StrokeColor);RenderData[i].StrokeColor={r:c.r,g:c.g,b:c.b,a:c.a};}
if(RenderData[i].Image){RenderData[i].Image=RenderData[i].Image.src;}};RenderData.splice(0,0,{BoundingBox:this.GetPropertyValue('BoundingBox')});return RenderData;}
LucidBlock.prototype.LineDrawn=function(id,count,allowUI){}
LucidBlock.prototype.OnCreate=function(){if(this.TextAreas.length>0)
this._EditText(this.TextAreas[0]);}
LucidBlock.prototype.GetBoundingBox=function(){return this.GetPropertyValue('BoundingBox');}
LucidBlock.prototype.GetOffsetBoundingBox=function(Offset){var bb=this.GetPropertyValue('BoundingBox');if(Offset!=null){bb.x+=Offset.x;bb.y+=Offset.y;bb.w+=Offset.w;bb.h+=Offset.h;}
return bb;}
LucidBlock.prototype.RenderSample=function(canvas,scale){var c=canvas.getContext('2d');if(scale)
c.scale(scale,scale);var RenderData=this.GetRenderData(null,'sample');for(var i=0;i<RenderData.length;i++){if(RenderData[i].Image!=null){try{c.drawImage(RenderData[i].Image,RenderData[i].BoundingBox.x,RenderData[i].BoundingBox.y,RenderData[i].BoundingBox.w,RenderData[i].BoundingBox.h);}catch(err){c.fillStyle='#aaaaaa';c.fillRect(RenderData[i].BoundingBox.x,RenderData[i].BoundingBox.y,RenderData[i].BoundingBox.w,RenderData[i].BoundingBox.h);}}
else{if(RenderData[i].FillColor){var col=new RGBColor(RenderData[i].FillColor);if(col.r==255&&col.g==255&&col.b==255){col.r=240;col.g=240;col.b=240;}
c.fillStyle=col.toHex();c.beginPath();c.StrokeChunk(RenderData[i].Actions,1);c.fill();}
c.strokeStyle=RenderData[i].StrokeColor?RenderData[i].StrokeColor:"rgb(0,0,0)";c.lineWidth=RenderData[i].StrokeColor?RenderData[i].LineWidth:.5;c.beginPath();c.StrokeChunk(RenderData[i].Actions,1);c.stroke();}}}
LucidBlock.prototype.PreRender=function(canvas,IsToolHelper,Offset,ShowLinkPoints){}
LucidBlock.prototype.Render=function(canvas,IsToolHelper,Offset,ShowLinkPoints){var bb=this.GetOffsetBoundingBox(Offset);var scale=g_Client.Viewport.Scale;if(this.Layer==null){this.Layer=new SuperCanvasLayer(Math.round(bb.x*scale),Math.round(bb.y*scale),Math.round(bb.w*scale),Math.round(bb.h*scale),Math.round(scale*this.LayerPadding(bb)));this.Layer.BlockId=this.id;canvas.removeLayerByAttribute('BlockId',this.id);}
else
this.Layer.move(Math.round(bb.x*scale),Math.round(bb.y*scale),Math.round(bb.w*scale),Math.round(bb.h*scale),Math.round(scale*this.LayerPadding(bb)));this.Layer.ZOrder=this.GetPropertyValue('ZOrder');var UniqueDrawData=JSON.stringify([bb.w,bb.h,this.Selected,ShowLinkPoints,scale,g_Client.Document.GetPropertyValue('Gradient'),g_Client.Document.GetPropertyValue('RoundCorners')]);var ReRender=canvas.addLayer(this.Layer)||this.Dirty||this.OldUniqueDrawData!=UniqueDrawData;if(ReRender){this.OldUniqueDrawData=UniqueDrawData;this.Dirty=false;var RenderData=this.GetRenderData(Offset,IsToolHelper?'toolhelper':'screen');var c=this.Layer.getContext();c.scale(scale,scale);c.translate(-bb.x,-bb.y);if(this.Selected){for(var i=0;i<RenderData.length;i++){if(RenderData[i].StrokeColor){c.strokeStyle='rgba(136,51,51,.5)';c.lineWidth=RenderData[i].LineWidth+8;c.beginPath();c.StrokeChunk(RenderData[i].Actions);c.stroke();}}}
for(var i=0;i<RenderData.length;i++){if(RenderData[i].Image!=null){if(!g_Client.ImageManager.IsImageLoaded(RenderData[i].Image.src))
this.OldUniqueDrawData=null;try{c.drawImage(RenderData[i].Image,RenderData[i].BoundingBox.x,RenderData[i].BoundingBox.y,RenderData[i].BoundingBox.w,RenderData[i].BoundingBox.h);}catch(e){c.fillStyle='#aaaaaa';c.fillRect(RenderData[i].BoundingBox.x,RenderData[i].BoundingBox.y,RenderData[i].BoundingBox.w,RenderData[i].BoundingBox.h);this.OldUniqueDrawData=null;}}
else{if(RenderData[i].FillColor){var GradientFactor=g_Client.Document.GetPropertyValue('Gradient');if(GradientFactor>0){var col=new RGBColor(RenderData[i].FillColor);var col2=col.Lighten(GradientFactor);var g=c.createLinearGradient(bb.x,bb.y,bb.x+bb.w,bb.y+bb.h);g.addColorStop(0,col2.toHex());g.addColorStop(1,col.toHex());c.fillStyle=g;}
else
c.fillStyle=RenderData[i].FillColor;c.beginPath();c.StrokeChunk(RenderData[i].Actions);c.fill();}
if(RenderData[i].StrokeColor){c.strokeStyle=RenderData[i].StrokeColor;c.lineWidth=RenderData[i].LineWidth;c.beginPath();c.StrokeChunk(RenderData[i].Actions);c.stroke();}}}
if(this.Selected||ShowLinkPoints)
this._DrawLinkPoints(c,Offset);if(this.Selected)
this._DrawStretchCorners(c,bb);}
if(!IsToolHelper){for(var i=0;i<this.TextAreas.length;i++){if(ReRender||this.TextAreas[i].Dirty){this._PlaceText(this.TextAreas[i],bb);this.TextAreas[i].Dirty=false;}}}}
LucidBlock.prototype.RenderThumbnail=function(canvas,scale){var c=canvas.getContext('2d');var RenderData=this.GetRenderData(null,'thumb');for(var i=0;i<RenderData.length;i++){if(RenderData[i].Image!=null){try{c.drawImage(RenderData[i].Image,RenderData[i].BoundingBox.x*scale,RenderData[i].BoundingBox.y*scale,RenderData[i].BoundingBox.w*scale,RenderData[i].BoundingBox.h*scale);}catch(err){c.fillStyle='#aaaaaa';c.fillRect(RenderData[i].BoundingBox.x*scale,RenderData[i].BoundingBox.y*scale,RenderData[i].BoundingBox.w*scale,RenderData[i].BoundingBox.h*scale);}}
else{if(RenderData[i].FillColor){c.fillStyle=RenderData[i].FillColor;c.beginPath();c.StrokeChunk(RenderData[i].Actions,scale);c.fill();}
if(RenderData[i].StrokeColor){c.strokeStyle=RenderData[i].StrokeColor;c.lineWidth=.5;c.beginPath();c.StrokeChunk(RenderData[i].Actions,scale);c.stroke();}}}}
LucidBlock.prototype.HitTestBoundingBox=function(){return this.GetPropertyValue('BoundingBox');}
LucidBlock.prototype.HitTestTools=function(x,y,alt){var bb=this.GetPropertyValue('BoundingBox');if(x<bb.x-20||x>bb.x+bb.w+20||y<bb.y-20||y>bb.y+bb.h+20)
return null;if(!alt){if(this._NearPoint(x,y,bb.x,bb.y,10))
return{Item:this,Action:'nw'};if(this._NearPoint(x,y,bb.x+bb.w,bb.y,10))
return{Item:this,Action:'ne'};if(this._NearPoint(x,y,bb.x+bb.w,bb.y+bb.h,10))
return{Item:this,Action:'se'};if(this._NearPoint(x,y,bb.x,bb.y+bb.h,10))
return{Item:this,Action:'sw'};for(var i=0;i<this.LinkPoints.length;i++){if(this._NearPoint(x,y,this.RelativeX(this.LinkPoints[i].x),this.RelativeY(this.LinkPoints[i].y),10)){return{Item:this,Action:'linkpoint',x:this.LinkPoints[i].x,y:this.LinkPoints[i].y};}}
var me=this;var canvasOffset=g_Client.Viewport.Canvas.container.offset();x*=g_Client.Viewport.Scale;y*=g_Client.Viewport.Scale;for(var i=0;i<this.TextAreas.length;i++){var div=this.TextAreas[i].TextDiv;if(div){var offset=div.offset();offset.left-=canvasOffset.left;offset.top-=canvasOffset.top;if(x>=offset.left&&x<=offset.left+div.get(0).offsetWidth&&y>=offset.top&&y<=offset.top+div.get(0).offsetHeight){return{Item:this,Action:'text',Cursor:this.TextCursor,Click:(function(a){return function(){if(!a.ReadOnly)
me._TextClicked(a);};})(this.TextAreas[i])};}}}
x/=g_Client.Viewport.Scale;y/=g_Client.Viewport.Scale;}
return null;}
LucidBlock.prototype.HitTest=function(x,y,alt){var ret=this.HitTestTools(x,y,alt);if(ret==null){bb=this.HitTestBoundingBox();if(x>=bb.x&&x<=bb.x+bb.w&&y>=bb.y&&y<=bb.y+bb.h){return{Item:this,Action:'move'};}}
return ret;}
LucidBlock.prototype.RectTest=function(x,y,x2,y2){var bb=this.HitTestBoundingBox();return!(bb.x>x2||bb.y>y2||bb.x+bb.w<x||bb.y+bb.h<y);}
LucidBlock.prototype.LinkPointNormal=function(lp){if(lp.x==.5&&lp.y<.5)return{x:0,y:-1};if(lp.x==.5&&lp.y>.5)return{x:0,y:1};if(lp.y==.5&&lp.x<.5)return{x:-1,y:0};if(lp.y==.5&&lp.x>.5)return{x:1,y:0};var p1={x:this.RelativeX(.5),y:this.RelativeY(.5)};var p2={x:this.RelativeX(lp.x),y:this.RelativeY(lp.y)};var d={x:p2.x-p1.x,y:p2.y-p1.y};var l=Math.sqrt(d.x*d.x+d.y*d.y);return{x:d.x/l,y:d.y/l};}
LucidBlock.prototype.RelativeX=function(x,Offset){var bb=this.GetPropertyValue('BoundingBox',true);if(Offset!=null)
return(bb.x+Offset.x)+(bb.w+Offset.w)*x;else
return bb.x+(bb.w)*x;}
LucidBlock.prototype.RelativeY=function(y,Offset){var bb=this.GetPropertyValue('BoundingBox',true);if(Offset!=null)
return(bb.y+Offset.y)+(bb.h+Offset.h)*y;else
return bb.y+(bb.h)*y;}
LucidBlock.prototype._NearPoint=function(x,y,px,py,d){return(x>=px-d&&x<=px+d&&y>=py-d&&y<=py+d);}
LucidBlock.prototype._TextClicked=function(a){if(!g_Client.CanEdit())return;this._EditText(a);}
LucidBlock.prototype._TextDivCreated=function(a){}
LucidBlock.prototype._PlaceText=function(a,blockBB){var TextDiv=a.TextDiv;if(TextDiv==null){a.TextDiv=this.Layer.addDiv();TextDiv=a.TextDiv;TextDiv.attr('id',a.DivId);TextDiv.attr('ItemId',this.id);TextDiv.addClass('overlay');TextDiv.css({cursor:'auto',padding:'1px',display:'block','min-height':'1em'});this._TextDivCreated(a);}
var bb=a.BoundingBox(blockBB);bb.x-=blockBB.x;bb.y-=blockBB.y;bb.w=Math.max(bb.w,1);bb.h=Math.max(bb.h,1);var text=this.GetPropertyValue(a.Name);var align=this.GetPropertyValue('TextAlign');var font=this.GetPropertyValue('Font');var data=JSON.stringify([bb,g_Client.Viewport.Scale,text,align,font]);if(TextDiv.attr('textdata')!=data){TextDiv.attr('textdata',data);TextDiv.move(bb.x*g_Client.Viewport.Scale,bb.y*g_Client.Viewport.Scale,bb.w*g_Client.Viewport.Scale);TextDiv.css({'text-align':align,'font-family':font});InlineEditor.Finalize(a.DivId,text,g_Client.Viewport.Scale,true);var height=TextDiv.get(0).offsetHeight;TextDiv.move(null,bb.y*g_Client.Viewport.Scale+(bb.h*g_Client.Viewport.Scale-height)/2);}}
LucidBlock.prototype._DrawStretchCorners=function(c,bb){c.strokeStyle='#883333';c.lineWidth=2;c.fillStyle='rgb(255,255,192)';c.beginPath();c.moveTo(bb.x-5,bb.y+5);c.lineTo(bb.x-5,bb.y-5);c.lineTo(bb.x+5,bb.y-5);c.closePath();c.fill();c.stroke();c.beginPath();c.moveTo(bb.x+bb.w+5,bb.y+5);c.lineTo(bb.x+bb.w+5,bb.y-5);c.lineTo(bb.x+bb.w-5,bb.y-5);c.closePath();c.fill();c.stroke();c.beginPath();c.moveTo(bb.x-5,bb.y+bb.h-5);c.lineTo(bb.x-5,bb.y+bb.h+5);c.lineTo(bb.x+5,bb.y+bb.h+5);c.closePath();c.fill();c.stroke();c.beginPath();c.moveTo(bb.x+bb.w+5,bb.y+bb.h-5);c.lineTo(bb.x+bb.w+5,bb.y+bb.h+5);c.lineTo(bb.x+bb.w-5,bb.y+bb.h+5);c.closePath();c.fill();c.stroke();}
LucidBlock.prototype._DrawLinkPoints=function(c,Offset){c.strokeStyle='#883333';c.lineWidth=2;c.fillStyle='rgb(255,255,192)';for(var i=0;i<this.LinkPoints.length;i++){c.beginPath();c.ellipse(this.RelativeX(this.LinkPoints[i].x,Offset)-3,this.RelativeY(this.LinkPoints[i].y,Offset)-3,6,6);c.fill();c.stroke();}}


var LucidLine=function(id){this.id=id;this.IsLine=true;this.PointCache={};this.TextDivs={};SetupPropertyStore(this);this.RegisterProperty('LineColor','#000000');this.RegisterProperty('LineWidth',2);this.RegisterProperty('ZOrder',0);this.RegisterProperty('StrokeStyle','solid');this.RegisterProperty('Font','times');var me=this;this.RegisterProperty('ControlPoints',{},null,function(old,val){if(me.GetPropertyValue('Shape')=='curve'){var ep1=me.GetPropertyValue('Endpoint1');var ep2=me.GetPropertyValue('Endpoint2');if(ep1!=null&&ep2!=null){me.SetPropertyValue('Points',me._GetPoints(ep1,ep2));}}});this.RegisterProperty('Points',[{x:0,y:0},{x:100,y:0}],function(v){if(v==null){var ep1=me.GetPropertyValue('Endpoint1',true);var ep2=me.GetPropertyValue('Endpoint2',true);if(ep1!=null&&ep2!=null)
v=me._GetPoints(ep1,ep2);}
me._CachePoints(ep1,ep2,me.GetPropertyValue('Shape'),v);return v;});this.RegisterProperty('TextAreas',{IsFullPropSettings:true},function(v){if(v.IsFullPropSettings){for(var key in this.Value){if(v[key]==null)
v[key]=null;}
return v;}
var ret=this.Value==null?{}:CopyObject(this.Value);for(var key in v){if(ret[key]==null||v[key]==null)
ret[key]=v[key];else{for(var akey in v[key]){if(akey=='Value'){ret[key][akey]=InlineEditor.Finalize('testtext',v[key][akey],1);if($.trim($(ret[key][akey]).text())==''){ret[key]=null;break;}}
else
ret[key][akey]=v[key][akey];}}}
return ret;});var BeforeUpdateEndpoint=function(v){var ret=this.Value==null?{}:CopyObject(this.Value);for(var key in v)
ret[key]=v[key];if(ret.Block!=null){var b=g_Client.Document._FindObject(ret.Block);if(b!=null){ret.x=b.RelativeX(ret.LinkX);ret.y=b.RelativeY(ret.LinkY);}}
return ret;}
var AfterUpdateEndpoint=function(old,v){if(old==null||(v.x&&v.x!=old.x)||(v.y&&v.y!=old.y)||(v.Block!=old.Block)){var ep1=me.GetPropertyValue('Endpoint1',true);var ep2=me.GetPropertyValue('Endpoint2',true);if(ep1!=null&&ep2!=null){var cache=me._GetCachedPoints(ep1,ep2,me.GetPropertyValue('Shape'));if(cache==null)
cache=me._GetPoints(ep1,ep2);me.SetPropertyValue('Points',cache,true);}}}
this.RegisterProperty('Endpoint1',{x:0,y:0,Style:'None',Block:null,LinkX:null,LinkY:null},BeforeUpdateEndpoint,AfterUpdateEndpoint);this.RegisterProperty('Endpoint2',{x:100,y:0,Style:'Arrow',Block:null,LinkX:null,LinkY:null},BeforeUpdateEndpoint,AfterUpdateEndpoint);this.RegisterProperty('Shape','elbow',null,function(v){var ep1=me.GetPropertyValue('Endpoint1',true);var ep2=me.GetPropertyValue('Endpoint2',true);if(ep1!=null&&ep2!=null){var cache=me._GetCachedPoints(ep1,ep2,v);if(cache==null)
cache=me._GetPoints(ep1,ep2);me.SetPropertyValue('Points',cache,true);}});this.AddPropertyControl('Colors','LineColor',{Label:'Line Color',Type:'Color',Property:'LineColor'});this.AddPropertyControl('Style','Font',{Label:'Font',Type:'SelectButton',Options:{'times':'<span style="font-family:times;font-size:18px;">Times</span>','helvetica':'<span style="font-family:helvetica;font-size:18px;">Helvetica</span>'},Property:'Font'});this.AddPropertyControl('Style','LineWidth',{Label:'Line Width',Type:'SelectButton',Options:{1:'<img src="/img/editor/width1.png"/>',2:'<img src="/img/editor/width2.png"/>',4:'<img src="/img/editor/width4.png"/>',8:'<img src="/img/editor/width8.png"/>'},Property:'LineWidth',Numeric:true});this.AddPropertyControl('Style','LineStyle',{Label:'Line Style',Type:'SelectButton',Options:{solid:'<img src="/img/editor/solid.png"/>',dashed:'<img src="/img/editor/dashed.png"/>',dotted:'<img src="/img/editor/dotted.png"/>'},Property:'StrokeStyle'});var AddEndpointStyleControl=function(i){me.AddPropertyControl('Style','Endpoint'+i,{Label:'Endpoint '+i,Type:'SelectButton',Options:function(){var ret={};for(var key in LucidLine.EndpointStyles)
ret[key]="<img src='"+LucidLine.EndpointStyleImages[key][2-i]+"'/>";return ret;},Value:function(){return this.GetPropertyValue('Endpoint'+i).Style;},OnChange:function(val){g_Client.Document.RunAction({Action:'SetProperty',id:this.id,Property:'Endpoint'+i,Value:{Style:val}});}});}
AddEndpointStyleControl(1);AddEndpointStyleControl(2);this.AddPropertyControl('Style','LineShape',{Label:'Line Shape',Type:'SelectButton',Options:{curve:'<img src="/img/editor/curve.png"/>',elbow:'<img src="/img/editor/elbow.png"/>',diagonal:'<img src="/img/editor/diagonal.png"/>'},Property:'Shape'});this.Dirty=false;this.HookPropertyPostSave(null,function(o,v){me.Dirty=true;});this.BoundingBox=this.GetBoundingBox();this.HookPropertyPostSave('Points',function(o,v){me.BoundingBox=me.GetBoundingBox();LucidLine.InvalidateJumps(me);});this.HookPropertyPostSave('ZOrder',function(o,v){LucidLine.InvalidateJumps(me);});}
LucidLine.prototype._CachePoints=function(ep1,ep2,s,p){var key=JSON.stringify([ep1,ep2,s]);this.PointCache[key]=p;}
LucidLine.prototype._GetCachedPoints=function(ep1,ep2,s){var key=JSON.stringify([ep1,ep2,s]);return this.PointCache[key];}
LucidLine.prototype._GetRelativePoint=function(t){var p=this.GetPropertyValue('Points',true);var TotalLength=this._GetTotalLength();t*=TotalLength;if(t<0)
t=0;if(t>TotalLength)
t=TotalLength;for(var i=0;i<p.length-1;i++){var x=p[i+1].x-p[i].x;var y=p[i+1].y-p[i].y;var l=Math.max(0.001,Math.sqrt(x*x+y*y));if(t<l){return{x:p[i].x+x/l*t,y:p[i].y+y/l*t,nx:x/l,ny:y/l}}
t-=l;}
t+=l;return{x:p[i-1].x+x/l*t,y:p[i-1].y+y/l*t,nx:x/l,ny:y/l}}
LucidLine.prototype.ClosestRelativePoint=function(x,y,SnapToCenter){var p=this.GetPropertyValue('Points',true);var TotalLength=this._GetTotalLength();var MinDist=1000000;var t=0;var ret=0;for(var i=0;i<p.length-1;i++){var dx=p[i+1].x-p[i].x;var dy=p[i+1].y-p[i].y;var l=Math.max(0.001,Math.sqrt(dx*dx+dy*dy));var hit=ClosestPointOnLineSegment(x,y,p[i].x,p[i].y,p[i+1].x,p[i+1].y);if(hit.d<MinDist){ret=t+hit.t*l;MinDist=hit.d;}
t+=l;}
ret/=TotalLength;if(SnapToCenter&&ret>=0.45&&ret<=0.55)
ret=0.5;return ret;}
LucidLine.prototype._GetTotalLength=function(){var p=this.GetPropertyValue('Points',true);var TotalLength=0;for(var i=0;i<p.length-1;i++){var x=p[i].x-p[i+1].x;var y=p[i].y-p[i+1].y;TotalLength+=Math.sqrt(x*x+y*y);}
return Math.max(1,TotalLength);}
LucidLine.prototype.GetPDFData=function(){var ta=this.GetPropertyValue('TextAreas');var t=[];for(var key in ta){if(key=='IsFullPropSettings'||ta[key]==null)continue;var a=ta[key];var p=this._GetRelativePoint(a.Location);t.push({BoundingBox:{x:p.x,y:p.y,w:1,h:1},Text:a.Value,Font:this.GetPropertyValue('Font')});}
return{id:this.id,Text:t,RenderData:this.GetPDFRenderData()};}
LucidLine.prototype.GetPDFRenderData=function(){var RenderData=this._GetRenderData();var c;for(var i=0;i<RenderData.length;i++){if(RenderData[i].FillColor){c=new RGBColor(RenderData[i].FillColor);RenderData[i].FillColor={r:c.r,g:c.g,b:c.b};}
if(RenderData[i].StrokeColor){c=new RGBColor(RenderData[i].StrokeColor);RenderData[i].StrokeColor={r:c.r,g:c.g,b:c.b};}}
return RenderData;}
LucidLine.EndpointStyles={None:function(p,n,StrokeStyle,LineWidth,FillStyle,TouchesBlock){if(!TouchesBlock)
return[];var ret={StrokeColor:StrokeStyle,LineWidth:LineWidth,NoRounding:true,Actions:[]};ret.Actions.push({Action:'move',x:p.x,y:p.y});ret.Actions.push({Action:'line',x:p.x+n.x*3,y:p.y+n.y*3});return[ret];},Arrow:function(p,n,StrokeStyle,LineWidth,FillStyle,TouchesBlock){var ret={StrokeColor:StrokeStyle,LineWidth:LineWidth,FillColor:FillStyle,NoRounding:true,Actions:[]};var t=Math.atan2(n.y,n.x);ret.Actions.push({Action:'move',x:p.x,y:p.y});ret.Actions.push({Action:'line',x:p.x+Math.cos(t+3.14159*.9)*15,y:p.y+Math.sin(t+3.14159*.9)*15});ret.Actions.push({Action:'line',x:p.x+Math.cos(t-3.14159*.9)*15,y:p.y+Math.sin(t-3.14159*.9)*15});ret.Actions.push({Action:'close'});return[ret];},'Hollow Arrow':function(p,n,StrokeStyle,LineWidth,FillStyle,TouchesBlock){var ret=LucidLine.EndpointStyles.Arrow(p,n,StrokeStyle,LineWidth,FillStyle);ret[0].FillColor='rgb(255,255,255)';return ret;},'Open Arrow':function(p,n,StrokeStyle,LineWidth,FillStyle,TouchesBlock){var ret={StrokeColor:StrokeStyle,LineWidth:LineWidth,NoRounding:true,Actions:[]};var t=Math.atan2(n.y,n.x);ret.Actions.push({Action:'move',x:p.x+Math.cos(t+3.14159*.9)*20,y:p.y+Math.sin(t+3.14159*.9)*20});ret.Actions.push({Action:'line',x:p.x,y:p.y});ret.Actions.push({Action:'line',x:p.x+Math.cos(t-3.14159*.9)*20,y:p.y+Math.sin(t-3.14159*.9)*20});return[ret];}};LucidLine.EndpointStyleImages={None:['/img/editor/none.png','/img/editor/none_left.png'],Arrow:['/img/editor/arrow.png','/img/editor/arrow_left.png'],'Hollow Arrow':['/img/editor/hollow.png','/img/editor/hollow_left.png'],'Open Arrow':['/img/editor/open.png','/img/editor/open_left.png']};LucidLine.prototype.GetBoundingBox=function(){var minx=null;var miny=null;var maxx=null;var maxy=null;var minu=null;var minv=null;var maxu=null;var maxv=null;var p=this.GetPropertyValue('Points');for(var i=0;i<p.length;i++){if(minx==null||p[i].x<minx)minx=p[i].x;if(maxx==null||p[i].x>maxx)maxx=p[i].x;if(miny==null||p[i].y<miny)miny=p[i].y;if(maxy==null||p[i].y>maxy)maxy=p[i].y;var u=p[i].x*0.707106781-p[i].y*0.707106781;var v=p[i].y*0.707106781+p[i].x*0.707106781;if(minu==null||u<minu)minu=u;if(maxu==null||u>maxu)maxu=u;if(minv==null||v<minv)minv=v;if(maxv==null||v>maxv)maxv=v;}
return{x:minx,y:miny,w:maxx-minx,h:maxy-miny,rx:minu,ry:minv,rw:maxu-minu,rh:maxv-minv};}
LucidLine.prototype.InBoundingBox=function(x,y){var bb=this.BoundingBox;if(x<bb.x||x>bb.x+bb.w||y<bb.y||y>bb.y+bb.h)
return false;var u=x*0.707106781-y*0.707106781;var v=y*0.707106781+x*0.707106781;if(u<bb.rx||u>bb.rx+bb.rw||v<bb.ry||v>bb.ry+bb.rh)
return false;return true;}
LucidLine.prototype.BoxInBoundingBox=function(p1,p2){var bb=this.BoundingBox;if(p1.x<p2.x){var x1=p1.x;var x2=p2.x;}
else{var x1=p2.x;var x2=p1.x;}
if(x2<bb.x||x1>bb.x+bb.w)
return false;if(p1.y<p2.y){var y1=p1.y;var y2=p2.y;}
else{var y1=p2.y;var y2=p1.y;}
if(y2<bb.y||y1>bb.y+bb.h)
return false;var p1x=p1.x*0.707106781;var p1y=p1.y*0.707106781;var p2x=p2.x*0.707106781;var p2y=p2.y*0.707106781;var up1=p1x-p1y;var vp1=p1y+p1x;var up2=p2x-p2y;var vp2=p2y+p2x;if(up1<up2){var u1=up1;var u2=up2;}
else{var u1=up2;var u2=up1;}
if(u2<bb.rx||u1>bb.rx+bb.rw)
return false;if(vp1<vp2){var v1=vp1;var v2=vp2;}
else{var v1=vp2;var v2=vp1;}
if(v2<bb.ry||v1>bb.ry+bb.rh)
return false;return true;}
LucidLine.prototype.NearBoundingBox=function(x,y,tolerance){var bb=this.BoundingBox;if(x<bb.x-tolerance||x>bb.x+bb.w+tolerance||y<bb.y-tolerance||y>bb.y+bb.h+tolerance)
return false;var u=x*0.707106781-y*0.707106781;var v=y*0.707106781+x*0.707106781;if(u<bb.rx-tolerance||u>bb.rx+bb.rw+tolerance||v<bb.ry-tolerance||v>bb.ry+bb.rh+tolerance)
return false;return true;}
LucidLine.prototype.NearPoint=function(x,y,px,py,d){return(x>=px-d&&x<=px+d&&y>=py-d&&y<=py+d);}
LucidLine.prototype.HitTest=function(x,y,alt){if(!this.NearBoundingBox(x,y,20))
return null;var me=this;var canvasOffset=g_Client.Viewport.Canvas.container.offset();x*=g_Client.Viewport.Scale;y*=g_Client.Viewport.Scale;for(var i in this.TextDivs){var div=this.TextDivs[i];var offset=div.offset();offset.left-=canvasOffset.left;offset.top-=canvasOffset.top;if(x>=offset.left&&x<=offset.left+div.get(0).offsetWidth&&y>=offset.top&&y<=offset.top+div.get(0).offsetHeight){return{Item:this,Cursor:'text',Action:'text',Div:div,Key:i,Click:(function(id){return function(){me._TextClicked(id,me.GetPropertyValue('TextAreas')[id]);};})(i)};}}
x/=g_Client.Viewport.Scale;y/=g_Client.Viewport.Scale;var ep1=this.GetPropertyValue('Endpoint1');var ep2=this.GetPropertyValue('Endpoint2');if(this.NearPoint(x,y,ep1.x,ep1.y,25)){return{Item:this,Action:'dragline',Property:'Endpoint1',Value:ep1};}
else if(this.NearPoint(x,y,ep2.x,ep2.y,25)){return{Item:this,Action:'dragline',Property:'Endpoint2',Value:ep2};}
var OtherAction=(ep1.Block==null||g_Client.Document._FindObject(ep1.Block)==null)&&(ep2.Block==null||g_Client.Document._FindObject(ep2.Block)==null)?'move':'none';var p=this.GetPropertyValue('Points');for(var i=0;i<p.length-1;i++){if(DistanceFromLineSegment(x,y,p[i].x,p[i].y,p[i+1].x,p[i+1].y)<10){if(i>0&&i<p.length-2){var n1=this._EndpointNormal(ep1);var n2=this._EndpointNormal(ep2);if(p[i].x==p[i+1].x){var max=Math.max(p[i-1].x,p[i].x,p[i+2].x);var min=Math.min(p[i-1].x,p[i].x,p[i+2].x);if(p[i].x==min&&p[i-1].x>min&&p[i+2].x>min)
min=0;if(p[i].x==max&&p[i-1].x<max&&p[i+2].x<max)
max=10000;if(max!=min)
return{Item:this,Action:'slidex',p1:ep1,p2:ep2,n1:n1,n2:n2,Points:p,Index:i,Min:min,Max:max};}
else if(p[i].y==p[i+1].y){var max=Math.max(p[i-1].y,p[i].y,p[i+2].y);var min=Math.min(p[i-1].y,p[i].y,p[i+2].y);if(p[i].y==min&&p[i-1].y>min&&p[i+2].y>min)
min=0;if(p[i].y==max&&p[i-1].y<max&&p[i+2].y<max)
max=10000;if(max!=min)
return{Item:this,Action:'slidey',p1:ep1,p2:ep2,n1:n1,n2:n2,Points:p,Index:i,Min:min,Max:max};}}
return{Item:this,Action:OtherAction};}}
return null;}
LucidLine.prototype.RectTest=function(x,y,x2,y2){var bb=this.BoundingBox;if(x2<bb.x||y2<bb.y||x>bb.x+bb.w||y>bb.y+bb.h)
return false;var pts=this.GetPropertyValue('Points');for(var i=1;i<pts.length;i++){if(LineIntersectsRectangle(pts[i-1].x,pts[i-1].y,pts[i].x,pts[i].y,x,y,x2,y2))
return true;}
return false;}
LucidLine.prototype.Render=function(canvas){var bb=this.BoundingBox;var scale=g_Client.Viewport.Scale;if(this.Layer==null){this.Layer=new SuperCanvasLayer(Math.round(bb.x*scale),Math.round(bb.y*scale),Math.round(bb.w*scale),Math.round(bb.h*scale),Math.round(scale*12));this.Layer.LineId=this.id;canvas.removeLayerByAttribute('LineId',this.id);}
else
this.Layer.move(Math.round(bb.x*scale),Math.round(bb.y*scale),Math.round(bb.w*scale),Math.round(bb.h*scale),Math.round(scale*12));this.Layer.ZOrder=this.GetPropertyValue('ZOrder');var RenderAffectors=JSON.stringify([scale,this.Selected,g_Client.Document.GetPropertyValue('RoundCorners')]);var ReRender=canvas.addLayer(this.Layer)||this.Dirty||RenderAffectors!=this.OldRenderAffectors;if(ReRender){this.Dirty=false;this.OldRenderAffectors=RenderAffectors;var RenderData=this._GetRenderData();var c=this.Layer.getContext();c.scale(scale,scale);c.translate(-bb.x,-bb.y);if(this.Selected){for(var i=0;i<RenderData.length;i++){if(RenderData[i].StrokeColor){c.strokeStyle='rgba(136,51,51,.5)';c.lineWidth=RenderData[i].LineWidth+8;c.beginPath();c.StrokeChunk(RenderData[i].Actions);c.stroke();}}}
for(var i=0;i<RenderData.length;i++){if(RenderData[i].Image!=null){try{c.drawImage(RenderData[i].Image,RenderData[i].BoundingBox.x,RenderData[i].BoundingBox.y,RenderData[i].BoundingBox.w,RenderData[i].BoundingBox.h);}catch(err){c.fillStyle='#aaaaaa';c.fillRect(RenderData[i].BoundingBox.x,RenderData[i].BoundingBox.y,RenderData[i].BoundingBox.w,RenderData[i].BoundingBox.h);}}
else{if(RenderData[i].FillColor){c.fillStyle=RenderData[i].FillColor;c.beginPath();c.StrokeChunk(RenderData[i].Actions);c.fill();}
if(RenderData[i].StrokeColor){c.strokeStyle=RenderData[i].StrokeColor;c.lineWidth=RenderData[i].LineWidth;c.beginPath();c.StrokeChunk(RenderData[i].Actions);c.stroke();}}}
var TextAreas=this.GetPropertyValue('TextAreas');for(var key in TextAreas){if(key!='IsFullPropSettings'){this._PlaceText(canvas,key,TextAreas[key],bb);}}}}
LucidLine.prototype.RenderThumbnail=function(canvas,scale){var c=canvas.getContext('2d');c.strokeStyle=this.GetPropertyValue('LineColor');c.lineWidth=.5;var p=this.GetPropertyValue('Points');c.beginPath();for(var i=0;i<p.length;i++){if(i==0)
c.moveTo(p[i].x*scale,p[i].y*scale);else
c.lineTo(p[i].x*scale,p[i].y*scale);}
c.stroke();}
LucidLine.prototype._TextDivId=function(key){return'linetext_'+this.id+'_'+key.replace(/[^a-zA-Z0-9]/g,'');}
LucidLine.prototype._PlaceText=function(canvas,key,a,bb){if(a==null){$('#'+this._TextDivId(key)).remove();delete this.TextDivs[key];return;}
var TextDiv=this.TextDivs[key];if(TextDiv==null){this.TextDivs[key]=this.Layer.addDiv();TextDiv=this.TextDivs[key];TextDiv.attr('id',this._TextDivId(key));TextDiv.attr('ItemId',this.id);TextDiv.addClass('overlay');TextDiv.addClass('line');TextDiv.css({position:'absolute',padding:'1px','text-align':'center',display:'block','white-space':'nowrap',cursor:'auto'});g_Client.ContextMenu.AttachContextMenu(TextDiv.get(0));}
var pos=this._GetRelativePoint(a.Location);pos.x-=bb.x;pos.y-=bb.y;var font=this.GetPropertyValue('Font');var data=JSON.stringify([a.Value,g_Client.Viewport.Scale,pos,a.Side,font]);if(TextDiv.attr('textdata')!=data){TextDiv.attr('textdata',data);var page=g_Client.Document._FindObjectPage(this.id);if(page==null)
var BackColor='#ffffff';else
var BackColor=page.GetPropertyValue('FillColor');TextDiv.css({background:BackColor,'font-family':font});var data2=JSON.stringify([a.Value,g_Client.Viewport.Scale]);if(TextDiv.attr('textdata2')!=data2){TextDiv.css({top:'-1000px',left:'-1000px'});TextDiv.attr('textdata2',data2);InlineEditor.Finalize(TextDiv.get(0).id,a.Value,g_Client.Viewport.Scale,true);TextDiv.attr('lastOffsetWidth',TextDiv.get(0).offsetWidth);TextDiv.attr('lastOffsetHeight',TextDiv.get(0).offsetHeight);}
var height=TextDiv.attr('lastOffsetHeight');var width=TextDiv.attr('lastOffsetWidth');if(a.Side==1){var angle=Math.atan2(pos.ny,pos.nx);var nx=Math.round(Math.cos(angle+Math.PI/2),3);var ny=Math.round(Math.sin(angle+Math.PI/2),3);}
else if(a.Side==-1){var angle=Math.atan2(pos.ny,pos.nx);var nx=Math.round(Math.cos(angle-Math.PI/2),3);var ny=Math.round(Math.sin(angle-Math.PI/2),3);}
if(a.Side==0||a.Side==null||(nx!=0&&ny!=0)){TextDiv.move(pos.x*g_Client.Viewport.Scale-width/2,pos.y*g_Client.Viewport.Scale-height/2);}
else if(nx==1){TextDiv.move((pos.x+3)*g_Client.Viewport.Scale,pos.y*g_Client.Viewport.Scale-height/2);}
else if(nx==-1){TextDiv.move((pos.x-3)*g_Client.Viewport.Scale-width,pos.y*g_Client.Viewport.Scale-height/2);}
else if(ny==1){TextDiv.move(pos.x*g_Client.Viewport.Scale-width/2,(pos.y+3)*g_Client.Viewport.Scale);}
else if(ny==-1){TextDiv.move(pos.x*g_Client.Viewport.Scale-width/2,(pos.y-3)*g_Client.Viewport.Scale-height);}}}
LucidLine.prototype._TextClicked=function(key,a){if(!g_Client.CanEdit())return;this._EditText(key);}
LucidLine.prototype._EditText=function(key){var a=this.GetPropertyValue('TextAreas')[key];var TextDiv=$('#'+this._TextDivId(key));if(TextDiv.size()==0){var b=this;setTimeoutFunction(function(){b._EditText(key);},50);return;}
if(TextDiv.attr('IsEditing'))
return;if(is_ie)
g_Client.Viewport.Canvas.container.get(0).insertAdjacentElement('afterEnd',this.Layer.container.get(0));else
g_Client.Viewport.Canvas.container.append(this.Layer.container);if(is_chrome||is_safari)
g_Client.Viewport.Canvas.container.css({overflow:'visible'});var b=this;InlineEditor.Create(this._TextDivId(key),g_Client.Viewport.Scale,function(val){g_Client.Viewport.Invalidate();if(val!=a.Value){var data={};data[key]={Value:val};g_Client.Document.RunAction({Action:'SetProperty',id:b.id,Property:'TextAreas',Value:data});}},a.WantReturn);}
LucidLine.RemoveExcessPoints=function(ret){for(var i=1;i<ret.length-1;i++){var dist=DistanceFromLineSegment(ret[i].x,ret[i].y,ret[i-1].x,ret[i-1].y,ret[i+1].x,ret[i+1].y);if(dist<0.1){ret.splice(i,1);i--;}}
return ret;}
LucidLine.prototype._EndpointNub=function(ep){var n=this._EndpointNormal(ep);if(n==null)
return{x:ep.x,y:ep.y};return{x:ep.x+n.x*20,y:ep.y+n.y*20};}
LucidLine.prototype._EndpointNormal=function(ep){if(ep.Block==null)
return null;if(this.GetPropertyValue('Shape')=='elbow'){if(ep.LinkX==0)
return{x:-1,y:0};else if(ep.LinkX==1)
return{x:1,y:0};else if(ep.LinkY==0)
return{x:0,y:-1};else if(ep.LinkY==1)
return{x:0,y:1};}
var ret={x:ep.LinkX-.5,y:ep.LinkY-.5};var l=Math.sqrt(ret.x*ret.x+ret.y*ret.y);if(l==0)
return null;ret.x/=l;ret.y/=l;return ret;}
function ReflectPointOverLine(p,p1,p2){var l={x:p2.x-p1.x,y:p2.y-p1.y};var v={x:p.x-p1.x,y:p.y-p1.y};var c=2*(v.x*l.x+v.y*l.y)/(l.x*l.x+l.y*l.y);return{x:c*l.x-v.x+p1.x,y:c*l.y-v.y+p1.y};}
LucidLine.prototype._GetControlPoints=function(ep1,ep2){var cp=this.GetPropertyValue('ControlPoints');if(ep1==null)ep1=this.GetPropertyValue('Endpoint1');if(ep2==null)ep2=this.GetPropertyValue('Endpoint2');if(cp.middle==null)
cp.middle=[];if(cp.first==null||cp.last==null){var p1={x:ep1.x,y:ep1.y};var p2={x:ep2.x,y:ep2.y};var n1=this._EndpointNormal(ep1);var n2=this._EndpointNormal(ep2);var ControlScale=.4;if(cp.middle.length==0){var l=Math.sqrt((p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y));if(l==0)l=1;if(n1==null)
n1={x:(p2.x-p1.x)/l,y:(p2.y-p1.y)/l};if(n2==null)
n2={x:(p1.x-p2.x)/l,y:(p1.y-p2.y)/l};if(ep1.Block&&ep1.Block==ep2.Block)
ControlScale=1;if(n1.x==-n2.x&&n1.y==-n2.y){var m=2*(n1.x*n1.x-2*n1.x*n2.x+n1.y*n1.y-2*n1.y*n2.y+n2.x*n2.x+n2.y*n2.y);var b=2*n1.x*(p1.x-p2.x)+2*n1.y*(p1.y-p2.y)-2*n2.x*(p1.x-p2.x)-2*n2.y*(p1.y-p2.y);if(m!=0){var t=-b/m;if(t>0){ControlScale=t/l;}}}
var l1=l;var l2=l;}
else{var m1=cp.middle[0];var m2=cp.middle[cp.middle.length-1];var l1=Math.sqrt((m1.x-p1.x)*(m1.x-p1.x)+(m1.y-p1.y)*(m1.y-p1.y));if(l1==0)l1=1;var l2=Math.sqrt((m2.x-p2.x)*(m2.x-p2.x)+(m2.y-p2.y)*(m2.y-p2.y));if(l2==0)l2=1;if(n1==null)
n1={x:(m1.x-p1.x)/l1,y:(m1.y-p1.y)/l1};if(n2==null)
n2={x:(m2.x-p2.x)/l2,y:(m2.y-p2.y)/l2};}
if(cp.first==null){cp.first={nx:n1.x*l1*ControlScale,ny:n1.y*l1*ControlScale};}
if(cp.last==null){cp.last={nx:-n2.x*l2*ControlScale,ny:-n2.y*l2*ControlScale};}}
cp.first.x=ep1.x;cp.first.y=ep1.y;cp.last.x=ep2.x;cp.last.y=ep2.y;var ret=CopyObject(cp.middle);ret.splice(0,0,CopyObject(cp.first));ret.push(CopyObject(cp.last));g_Client.Log.Log('cp',JSON.stringify(ret));return ret;}
LucidLine.prototype._GetPoints=function(ep1,ep2){var p1={x:ep1.x,y:ep1.y};var p2={x:ep2.x,y:ep2.y};var n1=this._EndpointNormal(ep1);var n2=this._EndpointNormal(ep2);if(this.GetPropertyValue('Shape')=='diagonal'){return[{x:p1.x,y:p1.y},{x:p2.x,y:p2.y}];}
if(this.GetPropertyValue('Shape')=='curve'){var cp=this._GetControlPoints(ep1,ep2);return calculateSplinePoints(cp,function(l){return Math.max(25,l/20);});}
if(n1!=null&&n2!=null){var intersect=RaysIntersection(p1,n1,p2,n2);if(intersect!=false)
return[p1,intersect,p2];var intersect=RaysIntersection(p1,{x:-n1.x,y:-n1.y},p2,{x:-n2.x,y:-n2.y});if(intersect!=false){var third=RaysIntersection({x:p1.x+n1.x*20,y:p1.y+n1.y*20},n2,{x:p2.x+n2.x*20,y:p2.y+n2.y*20},n1);return[p1,{x:p1.x+n1.x*20,y:p1.y+n1.y*20},third,{x:p2.x+n2.x*20,y:p2.y+n2.y*20},p2];}
if(n1.x==-n2.x&&n1.y==-n2.y){var m=2*(n1.x*n1.x-2*n1.x*n2.x+n1.y*n1.y-2*n1.y*n2.y+n2.x*n2.x+n2.y*n2.y);var b=2*n1.x*(p1.x-p2.x)+2*n1.y*(p1.y-p2.y)-2*n2.x*(p1.x-p2.x)-2*n2.y*(p1.y-p2.y);if(m!=0){var t=-b/m;if(t>0){return[p1,{x:p1.x+n1.x*t,y:p1.y+n1.y*t},{x:p2.x+n2.x*t,y:p2.y+n2.y*t},p2];}}}
if(n1.x==n2.x&&n1.y==n2.y){var d1=DistanceFromLineSegment(p1.x,p1.y,p2.x,p2.y,p2.x+n2.x*100000,p2.y+n2.y*100000);var d2=DistanceFromLineSegment(p2.x,p2.y,p1.x,p1.y,p1.x+n1.x*100000,p1.y+n1.y*100000);var mid1,mid2;if(d1<d2){mid1={x:p1.x+n1.x*20,y:p1.y+n1.y*20};mid2=ProjectPointOntoRay(mid1,p2,n2);}
else{mid2={x:p2.x+n2.x*20,y:p2.y+n2.y*20};mid1=ProjectPointOntoRay(mid2,p1,n1);}
return[p1,mid1,mid2,p2];}}
var ret=[{x:p1.x,y:p1.y}];if(ep1.Block!=null){ret.push(this._EndpointNub(ep1));p1=ret[ret.length-1];}
if(ep2.Block!=null){p2=this._EndpointNub(ep2);}
var xdiff=Math.abs(p1.x-p2.x);var ydiff=Math.abs(p1.y-p2.y);if(xdiff<ydiff){ret.push({x:p1.x,y:(p1.y+p2.y)/2});ret.push({x:p2.x,y:(p1.y+p2.y)/2});}
else{ret.push({x:(p1.x+p2.x)/2,y:p1.y});ret.push({x:(p1.x+p2.x)/2,y:p2.y});}
if(ep2.Block!=null){ret.push(p2);p2={x:ep2.x,y:ep2.y};}
ret.push({x:p2.x,y:p2.y});return ret;}
LucidLine.prototype._GetRenderData=function(){var StrokeStyle=this.GetPropertyValue('LineColor');var FillStyle=this.GetPropertyValue('LineColor');var LineWidth=this.GetPropertyValue('LineWidth');var page=g_Client.Document._FindObjectPage(this.id);if(page==null)
var BackColor='#ffffff';else
var BackColor=page.GetPropertyValue('FillColor');var ep1=this.GetPropertyValue('Endpoint1');var ep2=this.GetPropertyValue('Endpoint2');var p=this.GetPropertyValue('Points');var ret=[];var LineShadow={StrokeColor:BackColor,LineWidth:LineWidth*2};var LineItself={StrokeColor:StrokeStyle,LineWidth:LineWidth,Actions:[{Action:'move',x:p[0].x,y:p[0].y}]};g_Client.Log.Log('LineRender','Starting new line...');var t=0;var UnresolvedT=0;var EndJumpPoint=null;for(var i=0;i<p.length-1;i++){var n={x:p[i+1].x-p[i].x,y:p[i+1].y-p[i].y};var dist=Math.sqrt(n.x*n.x+n.y*n.y);var check=LucidLine._DrawSegment(p[i],p[i+1],ep1,ep2,LineItself.Actions,this.GetPropertyValue('StrokeStyle'),this.GetPropertyValue('LineWidth'),t,i,this.id);t+=dist;if(check>t){UnresolvedT=check-t;g_Client.Log.Log('LineRender','[check,t]='+[check,t]);EndJumpPoint={x:p[i+1].x+n.x/dist*UnresolvedT,y:p[i+1].y+n.y/dist*UnresolvedT};}}
for(var i=0;i<LineItself.Actions.length-1;i++){if(LineItself.Actions[i].Action=='move'&&LineItself.Actions[i+1].Action=='move'){LineItself.Actions.splice(i,1);i--;}}
LineShadow.Actions=CopyObject(LineItself.Actions);for(var i=0;i<LineShadow.Actions.length;i++){if(LineShadow.Actions[i].Action=='line')
LineShadow.Actions[i].Action='move';}
ret.push(LineShadow);ret.push(LineItself);var TotalLength=this._GetTotalLength();if(LucidLine.EndpointStyles[ep1.Style]!=null){var fn=LucidLine.EndpointStyles[ep1.Style];var p2=this._GetRelativePoint(15/TotalLength);var n={x:p[0].x-p2.x,y:p[0].y-p2.y};var l=Math.max(1,Math.sqrt(n.x*n.x+n.y*n.y));n.x/=l;n.y/=l;var all=fn(p[0],n,StrokeStyle,LineWidth,FillStyle,ep1.Block!=null);for(var i=0;i<all.length;i++)
ret.push(all[i]);}
if(LucidLine.EndpointStyles[ep2.Style]!=null){var fn=LucidLine.EndpointStyles[ep2.Style];var p2=this._GetRelativePoint((TotalLength-15)/TotalLength);var n={x:p[p.length-1].x-p2.x,y:p[p.length-1].y-p2.y};var l=Math.max(1,Math.sqrt(n.x*n.x+n.y*n.y));n.x/=l;n.y/=l;var all=fn(p[p.length-1],n,StrokeStyle,LineWidth,FillStyle,ep2.Block!=null);for(var i=0;i<all.length;i++)
ret.push(all[i]);}
return RoundRenderData(ret,g_Client.Document.GetPropertyValue('RoundCorners'));}
LucidLine._PreRender=function(Lines){LucidLine.FindAllJumps(Lines);}
LucidLine._DrawSegment=function(p1,p2,ep1,ep2,Actions,StrokeStyle,Width,t,PointIdx,LineId){var StartT=t;var jumps=[];for(var key in LucidLine.AllJumps[LineId]){if(LucidLine.AllJumps[LineId][key][PointIdx]!=null){for(var i=0;i<LucidLine.AllJumps[LineId][key][PointIdx].length;i++)
jumps.push(LucidLine.AllJumps[LineId][key][PointIdx][i]);}}
jumps.sort(function(a,b){var aDistSq=(a.x-p1.x)*(a.x-p1.x)+(a.y-p1.y)*(a.y-p1.y);var bDistSq=(b.x-p1.x)*(b.x-p1.x)+(b.y-p1.y)*(b.y-p1.y);return aDistSq-bDistSq;});var n={x:p2.x-p1.x,y:p2.y-p1.y};var dist=Math.sqrt(n.x*n.x+n.y*n.y);n.x/=dist;n.y/=dist;var angle2=Math.atan2(n.y,n.x);var angle1=angle2-Math.PI;if(p1.x>=p2.x)
angle1+=Math.PI*2;var LastPos=p1;for(var i=0;i<jumps.length;i++){if(i>0){if(Math.abs(jumps[i].x-jumps[i-1].x)<1&&Math.abs(jumps[i].y-jumps[i-1].y)<1)
continue;}
var Pos={x:jumps[i].x-n.x*5,y:jumps[i].y-n.y*5};LucidLine._DrawSegmentSegment(Actions,LastPos,Pos,StrokeStyle,Width,t);t+=Math.sqrt((Pos.x-LastPos.x)*(Pos.x-LastPos.x)+(Pos.y-LastPos.y)*(Pos.y-LastPos.y));Actions.push({Action:'move',x:Pos.x,y:Pos.y});Actions.push({Action:'curve',Control:EllipseArcControlPoints(jumps[i].x-5,jumps[i].y-5,10,10,angle1,angle2)});t+=10;LastPos={x:jumps[i].x+n.x*5,y:jumps[i].y+n.y*5};}
if(t-StartT<dist){LucidLine._DrawSegmentSegment(Actions,LastPos,p2,StrokeStyle,Width,t);t+=Math.sqrt((p2.x-LastPos.x)*(p2.x-LastPos.x)+(p2.y-LastPos.y)*(p2.y-LastPos.y));}
return t;}
LucidLine._DrawSegmentSegment=function(Actions,p1,p2,StrokeStyle,Width,StartT){var n={x:p2.x-p1.x,y:p2.y-p1.y};var dist=Math.sqrt(n.x*n.x+n.y*n.y);var EndT=StartT+dist;if(dist>0){n.x/=dist;n.y/=dist;}
else
return;if(StrokeStyle=='solid'){Actions.push({Action:'line',x:p2.x,y:p2.y});}
else if(StrokeStyle=='dashed'){var DashLength=Width*6;var SkipLength=Width*4;for(var t=0;t<StartT+dist;t+=DashLength+SkipLength){var BeginDash=t;var EndDash=t+DashLength;if(EndDash<StartT)continue;BeginDash=Math.max(BeginDash,StartT);EndDash=Math.min(EndDash,StartT+dist);Actions.push({Action:'move',x:p1.x+n.x*(BeginDash-StartT),y:p1.y+n.y*(BeginDash-StartT)});Actions.push({Action:'line',x:p1.x+n.x*(EndDash-StartT),y:p1.y+n.y*(EndDash-StartT)});}}
else if(StrokeStyle=='dotted'){var SkipLength=Width*4;var Radius=Width/2;for(var t=0;t<=StartT+dist;t+=SkipLength){if(t<StartT)continue;var x=p1.x+n.x*(t-StartT);var y=p1.y+n.y*(t-StartT);Actions.push({Action:'move',x:x+Radius,y:y});Actions.push({Action:'curve',Control:EllipseArcControlPoints(x-Radius,y-Radius,Radius*2,Radius*2,0,Math.PI*2)});}
Actions.push({Action:'move',x:p2.x,y:p2.y});}}


LucidLine.AllJumps={};LucidLine.InvalidateJumps=function(Line){Line.Dirty=true;delete LucidLine.AllJumps[Line.id];for(var LineId in LucidLine.AllJumps){if(!isEmpty(LucidLine.AllJumps[LineId][Line.id])){var l=g_Client.Document._FindObject(LineId);if(l!=null)
l.Dirty=true;}
delete LucidLine.AllJumps[LineId][Line.id];}}
LucidLine.FindAllJumps=function(Lines){var data={tests:0,loops:0};for(var i=0;i<Lines.length;i++){if(LucidLine.AllJumps[Lines[i].id]==null)
LucidLine.AllJumps[Lines[i].id]={};for(var j=i+1;j<Lines.length;j++){if(LucidLine.AllJumps[Lines[i].id][Lines[j].id])
continue;if(LucidLine.AllJumps[Lines[j].id]==null)
LucidLine.AllJumps[Lines[j].id]={};LucidLine.AllJumps[Lines[i].id][Lines[j].id]={};LucidLine.AllJumps[Lines[j].id][Lines[i].id]={};var b1=Lines[i].BoundingBox;var b2=Lines[j].BoundingBox;if(b1.x+b1.w<=b2.x||b1.y+b1.h<=b2.y||b1.x>=b2.x+b2.w||b1.y>=b2.y+b2.h)
continue;this._FindAllJumps(Lines[i],Lines[j],data);}}
g_Client.Log.Log('Render',JSON.stringify(data));}
LucidLine._FindAllJumps=function(Line1,Line2,data){var p1=Line1.GetPropertyValue('Points',true);var p2=Line2.GetPropertyValue('Points',true);var ep11=p1[0];var ep12=p1[p1.length-1];var ep21=p2[0];var ep22=p2[p2.length-1];function AddJump(point,intersection){if(LucidLine.AllJumps[Line2.id][Line1.id][point]==null)
LucidLine.AllJumps[Line2.id][Line1.id][point]=[];LucidLine.AllJumps[Line2.id][Line1.id][point].push(intersection);Line2.Dirty=true;}
var Skip2={};for(var j=0;j<p2.length-1;j++)
Skip2[j]=!Line1.BoxInBoundingBox(p2[j],p2[j+1]);for(var i=0;i<p1.length-1;i++){if(!Line2.BoxInBoundingBox(p1[i],p1[i+1]))
continue;for(var j=0;j<p2.length-1;j++){data.loops++;if(Skip2[j])
continue;var p11=p1[i];var p12=p1[i+1];var p21=p2[j];var p22=p2[j+1];data.tests++;var intersection=LinesIntersect(p11,p12,p21,p22);if(intersection!=true&&intersection!=false){if(Math.abs(intersection.x-p11.x)<0.1&&Math.abs(intersection.y-p11.y)<0.1)
continue;if(Math.abs(intersection.x-p12.x)<0.1&&Math.abs(intersection.y-p12.y)<0.1)
continue;if(Math.abs(intersection.x-p21.x)<0.1&&Math.abs(intersection.y-p21.y)<0.1)
continue;if(Math.abs(intersection.x-p22.x)<0.1&&Math.abs(intersection.y-p22.y)<0.1)
continue;AddJump(j,intersection);}}}}


var LucidLog=function(){this.Messages={};}
LucidLog.prototype.Log=function(Category,Message){if(this.Messages[Category]==null)
this.Messages[Category]=[];this.Messages[Category].push({Time:new Date(),Message:Message});if(this.Messages[Category].length>5000)
this.Messages[Category].splice(0,this.Messages[Category].length-100);}
LucidLog.prototype.ShowLog=function(Category){var html=new StringBuilder('<h1>'+Category+'</h1>');if(this.Messages[Category]!=null){for(var i=this.Messages[Category].length-1;i>=0;i--)
html.append(this.Messages[Category][i].Time.format('hh:MM:ss')+'.'+(this.Messages[Category][i].Time.getTime()%1000)+': '+htmlspecialchars(this.Messages[Category][i].Message)+'<hr/>');}
jqAlert(html.toString(),Category,null,800);}


var LucidPropertiesTab=function(){var me=this;g_Client.TabControl.AddPanel('Properties',300,"<div id='properties'></div>",function(){me.UpdateProperties();});this.UpdateCall=new ConsolidatedFunctionCall(function(){if(me.Dirty){me.Dirty=false;me._UpdateProperties();}},10);this.Dirty=true;g_Client.Document.HookActions(function(a){me.Dirty=true;});g_Client.Viewport.HookSelectPage(function(){me.Dirty=true;});g_Client.Document.HookSelectionChange(function(){me.Dirty=true;});}
LucidPropertiesTab.prototype.UpdateProperties=function(){this.UpdateCall.Queue();}
LucidPropertiesTab.prototype._UpdateProperties=function(){if(!g_Client.Viewport||!g_Client.Viewport.SelectedPage)
return;if($('#properties .ui-selectmenu').size()>0)
return;var idx=0;var html=new StringBuilder();if(g_Client.Viewport.SelectedPage.GetSelection().length>0){var c=null;g_Client.Viewport.SelectedPage.EachSelectedItem(function(){if(c==null)
c=this.PropertyControls;else
c=UnionPropertyControls(c,this.PropertyControls);});html.append('<div index="').append(idx++).append('"><a>Selected Items</a></div><div><ul>');html.append(GetPropertyControlsMarkup(c,'selection'));html.append('</ul></div>');}
html.append('<div index="').append(idx++).append('"><a>Page</a></div><div><ul>');html.append(GetPropertyControlsMarkup(g_Client.Viewport.SelectedPage.PropertyControls,'page'));html.append('</ul></div>');html.append('<div index="').append(idx++).append('"><a>').append(Configure.Document_text).append('</a></div><div><ul>');html.append(GetPropertyControlsMarkup(g_Client.Document.PropertyControls,'doc'));html.append('</div></ul>');$('#properties').accordion('destroy');$('#properties').html(html.toString());$('#properties').css({width:'274px'});var me=this;var options={active:0,autoHeight:false,alwaysOpen:true,change:function(event,ui){me.SelectedGroup=ui.newHeader.text();}};if(is_ie6)
options.animated=false;if(this.SelectedGroup!=null){$('#properties div').each(function(i){if($(this).text()==me.SelectedGroup)
options.active=parseInt($(this).attr('index'));});}
$('#properties').accordion(options);$("#properties .fg-button:not(.ui-state-disabled)").hover(function(){$(this).addClass("ui-state-hover");},function(){$(this).removeClass("ui-state-hover");}).mousedown(function(){$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");if($(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active')){$(this).removeClass("ui-state-active");}
else{$(this).addClass("ui-state-active");}}).mouseup(function(){if(!$(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button')){$(this).removeClass("ui-state-active");}});if(c!=null)SetPropertyControlsEvents(c,'selection');SetPropertyControlsEvents(g_Client.Viewport.SelectedPage.PropertyControls,'page');SetPropertyControlsEvents(g_Client.Document.PropertyControls,'doc');g_Client.Log.Log('Render','Updated properties');}


var LucidShareTab=function(){var me=this;g_Client.TabControl.AddPanel('Share',300,"<div id='addviewerdiv'>"
+"<h1>Invite By Email (One-Use Invitation)</h1><p>Enter the email address of an individual you'd like to collaborate with you on this document.  They will be able to accept this invitation using an existing account or register a new account to accept it.</p><input type='text' id='invite' value=''/><input type='button' id='submitinvite' value='Send Invite'/><hr/>"
+"<h1>Invite By Email (Multi-Use Invitation)</h1><p>Use this to send an invitation to a mailing list.  For example, if sales@yourdomain.com gets forwarded to your entire sales force, this will allow all of them to accept an invitation to collaborate on this document.</p><input type='text' id='invitemany' value=''/><input type='button' id='submitinvitemany' value='Send Invite'/><hr/>"
+"</div>"
+"<div id='viewersdiv'><h1>Users Sharing This "+Configure.Document_text+"</h1><div id='viewers'></div><hr/></div>"
+"<div id='chatlog'></div>"
+"<div id='chatinput'><input type='text' id='chattext'/><input type='button' id='submitchat' value='Chat'/></div>",function(){setTimeoutFunction(function(){me.Layout();},100);});$('#chattext').bind('keydown',function(e){if(e.which==13||e.keyCode==13)
$('#submitchat').triggerHandler('click');});$('#submitchat').click(function(){g_Client.SendChat($('#chattext').val());$('#chattext').val('');});$('#submitinvite,#submitinvitemany').click(function(){if(g_Client.Document.DocumentId==null){setTimeoutFunction(function(){jqAlert('You must save your '+Configure.document_text+' before sharing it with others.');},1);return;}
var input=$('#'+this.id.substr(6));var to=input.val();if(to.match(/.*@.*\..*/)==null){setTimeoutFunction(function(){jqAlert('Invalid email address.  Enter a valid email address (someone@somewhere.com) and click Send Invite.');},1);return;}
var multi=this.id=='submitinvitemany'?1:0;g_Client.GetUserRole(input.val(),'author',function(role){$.ajax({type:'POST',url:'/invitations/invite',data:'data[Invitation][document_id]='+encodeURIComponent(g_Client.Document.DocumentId)+'&data[Invitation][to]='+encodeURIComponent(to)+'&data[Invitation][role]='+encodeURIComponent(role)+'&data[Invitation][multi]='+encodeURIComponent(multi),success:function(msg){var d=JSON.parse(msg);if(d.Success){}
else if(d.Error==1){g_Client.InformFeatureRestriction();}
else{$.jGrowl('Could not send invitation.  If this error persists, please contact '+Configure.product+' support.');}},status:'Sending invitation to '+to});});input.val('');});$('#invite,#invitemany').keydown(function(e){if(e.which==27||e.keyCode==27){$(this).val('');}
if(e.which==13||e.keyCode==13){this.blur();$('#submit'+this.id).click();}});}
LucidShareTab.prototype.DealWithGetChatResult=function(d){if(d['messages'].length>0){$('#chatlog').append(Base64.decode(d['messages']));$('#chatlog').attr('scrollTop',100000000);if(g_Client.TabControl.SelectedPanel==null||g_Client.TabControl.SelectedPanel.Name!='Share'){$.jGrowl(Base64.decode(d['messages']),{life:5000,header:'<a href="javascript:g_Client.TabControl.ShowPanel(\'Share\');">Share (Chat)</a>'});}}
var v='';if(d['viewers']!=null&&d['viewers'].length!=null){for(var i=0;i<d['viewers'].length;i++){var u=d['viewers'][i].User;var vclass=d['viewers'][i].Connection.id==null?'viewer':'viewer online';var role=d['viewers'][i].DocumentsUser.role;v+="<div class='"+vclass+"'><a UserId='"+u.id+"' Role='"+role+"' href='javascript://' class='role'>"+this.PrettyRole(role)+"</a>"+u.first_name+' '+u.last_name+'<div style="clear:both;"></div></div>';}}
if(d['invitations']!=null&&d['invitations'].length!=null){for(var i=0;i<d['invitations'].length;i++){var inv=d['invitations'][i].Invitation;var vclass='viewer invited';v+="<div class='"+vclass+"'><a InvitationId='"+inv.id+"' Role='"+inv.role+"' href='javascript://' class='role'>"+this.PrettyRole(inv.role)+"</a>"+inv.to+'<div style="clear:both;"></div></div>';}}
$('#viewers').html(v);if(g_Client.Role=='owner'&&g_Client.User!=null){$('#viewers .role[UserId='+g_Client.User.id+']').removeAttr('href');$('#viewers .role[UserId][UserId!='+g_Client.User.id+']').click(function(){var UserId=$(this).attr('UserId');var Role=$(this).attr('Role');var Name=$(this).parent().text().replace($(this).text(),'');g_Client.GetUserRole(Name,Role,function(NewRole){if(NewRole==''){$.ajax({type:'POST',url:'/documentsUsers/delete',data:'data[DocumentsUser][document_id]='+encodeURIComponent(g_Client.Document.DocumentId)+'&data[DocumentsUser][user_id]='+encodeURIComponent(UserId),success:function(msg){var d=JSON.parse(msg);if(d.Success){}
else{$.jGrowl('Could not remove the collaborator.  If this error persists, please contact '+Configure.product+' support.');}},status:'Removing collaborator'});}
else{$.ajax({type:'POST',url:'/documentsUsers/add',data:'data[DocumentsUser][document_id]='+encodeURIComponent(g_Client.Document.DocumentId)+'&data[DocumentsUser][user_id]='+encodeURIComponent(UserId)+'&data[DocumentsUser][role]='+encodeURIComponent(NewRole),success:function(msg){var d=JSON.parse(msg);if(d.Success){}
else{$.jGrowl('Could not update the collaborator\'s role.  If this error persists, please contact '+Configure.product+' support.');}},status:'Updating collaborator role'});}},function(){},true);});$('#viewers .role[InvitationId]').click(function(){var InvitationId=$(this).attr('InvitationId');var Role=$(this).attr('Role');var Name=$(this).parent().text().replace($(this).text(),'');g_Client.GetUserRole(Name,Role,function(NewRole){if(NewRole==''){$.ajax({type:'POST',url:'/invitations/delete',data:'data[Invitation][id]='+encodeURIComponent(InvitationId),success:function(msg){var d=JSON.parse(msg);if(d.Success){}
else{$.jGrowl('Could not remove the invitation.  If this error persists, please contact '+Configure.product+' support.');}},status:'Canceling invitation'});}
else{$.ajax({type:'POST',url:'/invitations/edit',data:'data[Invitation][id]='+encodeURIComponent(InvitationId)+'&data[Invitation][role]='+encodeURIComponent(NewRole),success:function(msg){var d=JSON.parse(msg);if(d.Success){}
else{$.jGrowl('Could not update the collaborator\'s role.  If this error persists, please contact '+Configure.product+' support.');}},status:'Updating invitation role'});}},function(){},true,true);});}
else{$('#viewers .role').removeAttr('href');}
this.Layout();}
LucidShareTab.prototype.Layout=function(){for(var i=0;i<3;i++){var layout=[{DOM:'#addviewerdiv',Dock:'top'},{DOM:'#viewersdiv',Dock:'top'},{DOM:'#chatinput',Dock:'bottom'},{DOM:'#chatlog'}];if(g_Client.Role!='owner'){layout.splice(0,1);$('#addviewerdiv').css({display:'none'});}
else
$('#addviewerdiv').css({display:'block'});SetupLayout(layout,{x:4,y:0,w:272,h:g_Client.Viewport.Div.offsetHeight-4});}
$('#chatlog').css({'overflow-y':'auto'});$('#chattext').css({width:(265-jqWidth('#submitchat'))+'px'});}
LucidShareTab.prototype.PrettyRole=function(r){if(r=='owner')
return'Owner';else if(r=='author')
return'Author';else if(r=='viewer')
return'Viewer';else
return r;}


var LucidPublishTab=function(){var me=this;g_Client.TabControl.AddPanel('Publish',300,"<div style='padding:0 4px;'>"
+"<p>If you publish this "+Configure.document_text+" or any part of it, anyone will be able to view it if they have a link to it.</p>"
+"<p>These published links always point to the latest saved copy of your "+Configure.document_text+".</p><hr/>"
+"<h1>Publish "+Configure.Document_text+" As Web Page</h1><p id='publishnotice'></p><input id='publish' type='button' value=''/><hr/>"
+"<h1>Publish "+Configure.Document_text+" As PDF</h1><p id='publishpdfnotice'></p><input id='publishpdf' type='button' value=''/><hr/>"
+"<h1>Publish A Single Page</h1><p id='publishpagenotice'></p><input id='publishpage' type='button' value='Publish Current Page'/><hr/>"
+"<h1>Publish Part Of A Page</h1><p id='publishsegmentnotice'></p><input id='publishsegment' type='button' value='Publish Part Of Current Page'/><hr/>"
+"</div>",function(){g_Client.PublishTab._UpdateAll();});$('#publish').click(function(){if(g_Client.Document.DocumentId==null){jqAlert('You must save your '+Configure.document_text+' before publishing it.');return;}
$.ajax({type:"POST",url:"/documents/publish",data:'data[Document][id]='+encodeURIComponent(g_Client.Document.DocumentId)+'&data[Document][published]='+encodeURIComponent(g_Client.Document.IsPublished?0:1),success:function(msg){var d=JSON.parse(msg);if(d.Success){}
else{jqAlert(d.Error);}},status:'Saving published status'});});$('#publishpdf').click(function(){if(g_Client.Document.DocumentId==null){jqAlert('You must save your '+Configure.document_text+' before publishing it.');return;}
if(g_Client.Document.IsPDFPublished()){$.ajax({type:"POST",url:"/publicSegments/delete",data:'data[PublicSegment][id]='+encodeURIComponent(g_Client.Document.PublishedPDFId())
+'&data[PublicSegment][document_id]='+encodeURIComponent(g_Client.Document.DocumentId),success:function(msg){var d=JSON.parse(msg);if(d.Success){}
else{jqAlert(d.Error);}},status:'Saving PDF published status'});}
else{$.ajax({type:"POST",url:"/publicSegments/add",data:'data[PublicSegment][document_id]='+encodeURIComponent(g_Client.Document.DocumentId)
+'&data[PublicSegment][format]=pdf',success:function(msg){var d=JSON.parse(msg);if(d.Success){}
else{jqAlert(d.Error);}},status:'Saving PDF published status'});}});$('#publishpage').click(function(){if(g_Client.Document.DocumentId==null){jqAlert('You must save your '+Configure.document_text+' before publishing it.');return;}
g_Client.GetPublishFormat('pdf','',function(format,dpi){if(format=='pdf')
dpi='';else{if(dpi=='')
dpi=Math.round(g_Client.Viewport.SelectedPage.GetPropertyValue('DPI')*g_Client.Viewport.Scale);dpi='&data[PublicSegment][dpi]='+encodeURIComponent(dpi);}
$.ajax({type:"POST",url:"/publicSegments/add",data:'data[PublicSegment][document_id]='+encodeURIComponent(g_Client.Document.DocumentId)
+'&data[PublicSegment][page]='+encodeURIComponent(g_Client.Viewport.SelectedPage.id)
+'&data[PublicSegment][format]='+encodeURIComponent(format)
+dpi,success:function(msg){var d=JSON.parse(msg);if(d.Success){}
else{jqAlert(d.Error);}},status:'Publishing page'});},true);});$('#publishsegment').click(function(){if(g_Client.Document.DocumentId==null){jqAlert('You must save your '+Configure.document_text+' before publishing it.');return;}
g_Client.Viewport.SelectPageSegment('Select a portion of this page to publish',function(x,y,w,h){g_Client.GetPublishFormat('png','',function(format,dpi){if(dpi=='')
dpi=(g_Client.Viewport.SelectedPage.GetPropertyValue('DPI')*g_Client.Viewport.Scale);$.ajax({type:"POST",url:"/publicSegments/add",data:'data[PublicSegment][document_id]='+encodeURIComponent(g_Client.Document.DocumentId)
+'&data[PublicSegment][page]='+encodeURIComponent(g_Client.Viewport.SelectedPage.id)
+'&data[PublicSegment][format]='+encodeURIComponent(format)
+'&data[PublicSegment][dpi]='+encodeURIComponent(dpi)
+'&data[PublicSegment][x]='+encodeURIComponent(x)
+'&data[PublicSegment][y]='+encodeURIComponent(y)
+'&data[PublicSegment][w]='+encodeURIComponent(w)
+'&data[PublicSegment][h]='+encodeURIComponent(h),success:function(msg){var d=JSON.parse(msg);if(d.Success){}
else{jqAlert(d.Error);}},status:'Publishing page'});},false);});});}
LucidPublishTab.prototype._UpdateAll=function(){this.UpdatePublishDisplay();this.UpdatePublishPDFDisplay();this.UpdatePublishPageDisplay();}
LucidPublishTab.prototype.UpdatePublishDisplay=function(IsPublished){if(g_Client.Document.IsPublished){$('#publish').val('Remove Published Web Page');$('#publishnotice').html('This '+Configure.document_text+' is published <a href="/documents/view/'+g_Client.Document.DocumentId+'" target="_blank">here</a>.');}
else{$('#publish').val('Publish Web Page');$('#publishnotice').html('This '+Configure.document_text+' is not published.');}}
LucidPublishTab.prototype.UpdatePublishPDFDisplay=function(){if(g_Client.Document.IsPDFPublished()){$('#publishpdf').val('Remove Published PDF');$('#publishpdfnotice').html('This '+Configure.document_text+' is published <a href="/publicSegments/view/'+g_Client.Document.PublishedPDFId()+'" target="_blank">here</a>.');}
else{$('#publishpdf').val('Publish PDF');$('#publishpdfnotice').html('This '+Configure.document_text+' is not published.');}}
LucidPublishTab.prototype.UpdatePublishPageDisplay=function(){$('#publishpagenotice').html('');$('#publishsegmentnotice').html('');g_Client.Document.ClearPublishedSegments();var PublicSegments=g_Client.Document.PublicSegments;for(var key in PublicSegments){var seg=PublicSegments[key];if(seg.page==null)
continue;var filter='#publishpagenotice';if(seg.x!=null)
filter='#publishsegmentnotice';var page=g_Client.Document.Pages[seg.page];if(page==null)
continue;var format=seg.format.toUpperCase();if(format!='PDF'){if(seg.x!=null){if(g_Client.Document.Pages[seg.page]!=null)
g_Client.Document.Pages[seg.page].AddPublishedSegment(seg.x,seg.y,seg.w,seg.h);format+=', '+Math.round(seg.dpi*seg.w/page.GetPropertyValue('DPI'))+'x'+Math.round(seg.dpi*seg.h/page.GetPropertyValue('DPI'));}
else
format+=', '+seg.dpi+' DPI';}
var DeleteId='DeletePublishedPage_'+seg.id;(function(id){$(filter).append('<p><a class="action" id="'+DeleteId+'"><img src="/img/icons/delete.png"/></a><a href="/publicSegments/view/'+seg.id+'" target="_blank">'+page.GetPropertyValue('Title')+' ('+format+')</a></p>');$('#'+DeleteId).click(function(){jqAlert('Are you sure you wish to un-publish this portion of your '+Configure.document_text+'?  This will permanently break any outside links to this image.',null,{'Un-Publish':function(){$.ajax({type:"POST",url:"/publicSegments/delete",data:'data[PublicSegment][id]='+encodeURIComponent(id)
+'&data[PublicSegment][document_id]='+encodeURIComponent(g_Client.Document.DocumentId),success:function(msg){var d=JSON.parse(msg);if(d.Success){}
else{jqAlert(d.Error);}},status:'Publishing page'});},'Cancel':function(){}});});})(seg.id);}}


var LucidHistoryTab=function(){var me=this;g_Client.TabControl.AddPanel('History',300,"<div id='history'></div>",function(){g_Client.HistoryTab.UpdateSaveHistory();},function(){g_Client.Document.ExitHistoryView();});}
LucidHistoryTab.prototype.UpdateSaveHistory=function(){$('#history').accordion('destroy');$('#history').html('');$('#history').css({width:'274px'});for(var i=g_Client.Document.SaveHistory.length-1;i>=0;i--){var h=g_Client.Document.SaveHistory[i];var d=mysqlTimeStampToDate(h.Date);var changes=new StringBuilder();changes.append("<a class='historybutton newdoc'>Create new document from this revision</a><br/>");changes.append("<a class='historybutton revert'>Revert to this revision</a><hr/>");changes.append("<h1 style='padding-left:8px;'>Changes in this revision</h1>");var summary=g_Client.Document.GetSaveHistorySummary(h);for(var id in summary){changes.append("<div class='historypage'>");for(var action in summary[id].Actions){if(action=='create')
changes.append("<img class='historyaction' title='Page Created' src='/img/icons/add.png'/>");else if(action=='delete')
changes.append("<img class='historyaction' title='Page Deleted' src='/img/icons/delete.png'/>");else if(action=='edit')
changes.append("<img class='historyaction' title='Page Edited' src='/img/icons/page_white_edit.png'/>");}
if(summary[id].Actions['delete']==null&&id!='Document')
changes.append("<a id='showhistory_"+i+"_"+id+"' title='Show me what was changed' class='historypagetitle'>"+summary[id].Title+"</a>");else
changes.append("<span class='historypagetitle'>"+summary[id].Title+"</span>");changes.append("</div>");}
$('#history').append('<div><a id="showhistory_'+i+'_wholedoc">'+d.format('m/dd h:MM TT')+': '+h.UserName+'</a></div><div>'+changes+'</div>');}
var options={active:false,autoHeight:false,alwaysOpen:false};if(is_ie6)
options.animated=false;$('#history').accordion(options);$('#history a[id^=showhistory]').click(function(){var re=new RegExp(/^showhistory_(\d+)_(.+)$/);var m=re.exec(this.id);var h=g_Client.Document.SaveHistory[m[1]];var id=m[2];g_Client.Document.ViewRevision(h.Start+h.Count);if(g_Client.Document.Pages[id]==null)
id=g_Client.Document.GetOrderedPages()[0].id;g_Client.Viewport.SelectPage(g_Client.Document.Pages[id]);g_Client.Document.Pages[id].UnselectAll();for(var id in h.Summary){for(var ItemId in h.Summary[id].Items){var obj=g_Client.Document._FindObject(ItemId);if(obj)
g_Client.Viewport.SelectedPage.SelectItem(obj);}}
g_Client.LogAction('viewHistory');});$('#history .historybutton.revert').click(function(){jqAlert('<p>Are you sure you wish to revert to the version of this '+Configure.document_text+' you see displayed now?  You may undo this later.</p>',null,{'Revert To Earlier Version':function(){g_Client.Document.RevertToHistoryVersion();},Cancel:function(){}});});$('#history .historybutton.newdoc').click(function(){var Buttons={};Buttons['Create '+Configure.Document_text]=function(){g_Client.LockUI('Creating new document');var data='data[Document][pdfdata]='+encodeURIComponent(JSON.stringify(g_Client.Document.GetPDFData()))
+'&data[Document][title]='+encodeURIComponent(g_Client.Document.GetPropertyValue('Title'))
+'&data[Change][0][user_agent]='+encodeURIComponent(navigator.userAgent);$.ajax({type:'POST',url:'/documents/fork/'+encodeURIComponent(g_Client.Document.DocumentId)+'/'+encodeURIComponent(g_Client.Document.HistoryVersion),data:data,success:function(msg){try{msg=JSON.parse(msg);}
catch(e){jqAlert(msg);return;}
if(msg.Success){window.location.href='/documents/edit/'+msg.id;}
else{jqAlert('There was an error creating the new document.  Please try again.');}},error:function(){jqAlert('There was an error creating the new document.  Please try again.');},complete:function(){g_Client.UnlockUI();}});};Buttons['Cancel']=function(){};jqAlert('<p>Are you sure you wish to create a new '+Configure.document_text+' based on the version of this '+Configure.document_text+' you see displayed now?</p>',null,Buttons);});}


var dateFormat=function(){var token=/d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,timezoneClip=/[^-+\dA-Z]/g,pad=function(val,len){val=String(val);len=len||2;while(val.length<len)val="0"+val;return val;};return function(date,mask,utc){var dF=dateFormat;if(arguments.length==1&&(typeof date=="string"||date instanceof String)&&!/\d/.test(date)){mask=date;date=undefined;}
date=date?new Date(date):new Date();if(isNaN(date))throw new SyntaxError("invalid date");mask=String(dF.masks[mask]||mask||dF.masks["default"]);if(mask.slice(0,4)=="UTC:"){mask=mask.slice(4);utc=true;}
var _=utc?"getUTC":"get",d=date[_+"Date"](),D=date[_+"Day"](),m=date[_+"Month"](),y=date[_+"FullYear"](),H=date[_+"Hours"](),M=date[_+"Minutes"](),s=date[_+"Seconds"](),L=date[_+"Milliseconds"](),o=utc?0:date.getTimezoneOffset(),flags={d:d,dd:pad(d),ddd:dF.i18n.dayNames[D],dddd:dF.i18n.dayNames[D+7],m:m+1,mm:pad(m+1),mmm:dF.i18n.monthNames[m],mmmm:dF.i18n.monthNames[m+12],yy:String(y).slice(2),yyyy:y,h:H%12||12,hh:pad(H%12||12),H:H,HH:pad(H),M:M,MM:pad(M),s:s,ss:pad(s),l:pad(L,3),L:pad(L>99?Math.round(L/10):L),t:H<12?"a":"p",tt:H<12?"am":"pm",T:H<12?"A":"P",TT:H<12?"AM":"PM",Z:utc?"UTC":(String(date).match(timezone)||[""]).pop().replace(timezoneClip,""),o:(o>0?"-":"+")+pad(Math.floor(Math.abs(o)/60)*100+Math.abs(o)%60,4),S:["th","st","nd","rd"][d%10>3?0:(d%100-d%10!=10)*d%10]};return mask.replace(token,function($0){return $0 in flags?flags[$0]:$0.slice(1,$0.length-1);});};}();dateFormat.masks={"default":"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:ss",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"};dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"]};Date.prototype.format=function(mask,utc){return dateFormat(this,mask,utc);};


var hexcase=0;var b64pad="";var chrsz=8;function hex_md5(s){return binl2hex(core_md5(str2binl(s),s.length*chrsz));}
function b64_md5(s){return binl2b64(core_md5(str2binl(s),s.length*chrsz));}
function str_md5(s){return binl2str(core_md5(str2binl(s),s.length*chrsz));}
function hex_hmac_md5(key,data){return binl2hex(core_hmac_md5(key,data));}
function b64_hmac_md5(key,data){return binl2b64(core_hmac_md5(key,data));}
function str_hmac_md5(key,data){return binl2str(core_hmac_md5(key,data));}
function md5_vm_test()
{return hex_md5("abc")=="900150983cd24fb0d6963f7d28e17f72";}
function core_md5(x,len)
{x[len>>5]|=0x80<<((len)%32);x[(((len+64)>>>9)<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i<x.length;i+=16)
{var olda=a;var oldb=b;var oldc=c;var oldd=d;a=md5_ff(a,b,c,d,x[i+0],7,-680876936);d=md5_ff(d,a,b,c,x[i+1],12,-389564586);c=md5_ff(c,d,a,b,x[i+2],17,606105819);b=md5_ff(b,c,d,a,x[i+3],22,-1044525330);a=md5_ff(a,b,c,d,x[i+4],7,-176418897);d=md5_ff(d,a,b,c,x[i+5],12,1200080426);c=md5_ff(c,d,a,b,x[i+6],17,-1473231341);b=md5_ff(b,c,d,a,x[i+7],22,-45705983);a=md5_ff(a,b,c,d,x[i+8],7,1770035416);d=md5_ff(d,a,b,c,x[i+9],12,-1958414417);c=md5_ff(c,d,a,b,x[i+10],17,-42063);b=md5_ff(b,c,d,a,x[i+11],22,-1990404162);a=md5_ff(a,b,c,d,x[i+12],7,1804603682);d=md5_ff(d,a,b,c,x[i+13],12,-40341101);c=md5_ff(c,d,a,b,x[i+14],17,-1502002290);b=md5_ff(b,c,d,a,x[i+15],22,1236535329);a=md5_gg(a,b,c,d,x[i+1],5,-165796510);d=md5_gg(d,a,b,c,x[i+6],9,-1069501632);c=md5_gg(c,d,a,b,x[i+11],14,643717713);b=md5_gg(b,c,d,a,x[i+0],20,-373897302);a=md5_gg(a,b,c,d,x[i+5],5,-701558691);d=md5_gg(d,a,b,c,x[i+10],9,38016083);c=md5_gg(c,d,a,b,x[i+15],14,-660478335);b=md5_gg(b,c,d,a,x[i+4],20,-405537848);a=md5_gg(a,b,c,d,x[i+9],5,568446438);d=md5_gg(d,a,b,c,x[i+14],9,-1019803690);c=md5_gg(c,d,a,b,x[i+3],14,-187363961);b=md5_gg(b,c,d,a,x[i+8],20,1163531501);a=md5_gg(a,b,c,d,x[i+13],5,-1444681467);d=md5_gg(d,a,b,c,x[i+2],9,-51403784);c=md5_gg(c,d,a,b,x[i+7],14,1735328473);b=md5_gg(b,c,d,a,x[i+12],20,-1926607734);a=md5_hh(a,b,c,d,x[i+5],4,-378558);d=md5_hh(d,a,b,c,x[i+8],11,-2022574463);c=md5_hh(c,d,a,b,x[i+11],16,1839030562);b=md5_hh(b,c,d,a,x[i+14],23,-35309556);a=md5_hh(a,b,c,d,x[i+1],4,-1530992060);d=md5_hh(d,a,b,c,x[i+4],11,1272893353);c=md5_hh(c,d,a,b,x[i+7],16,-155497632);b=md5_hh(b,c,d,a,x[i+10],23,-1094730640);a=md5_hh(a,b,c,d,x[i+13],4,681279174);d=md5_hh(d,a,b,c,x[i+0],11,-358537222);c=md5_hh(c,d,a,b,x[i+3],16,-722521979);b=md5_hh(b,c,d,a,x[i+6],23,76029189);a=md5_hh(a,b,c,d,x[i+9],4,-640364487);d=md5_hh(d,a,b,c,x[i+12],11,-421815835);c=md5_hh(c,d,a,b,x[i+15],16,530742520);b=md5_hh(b,c,d,a,x[i+2],23,-995338651);a=md5_ii(a,b,c,d,x[i+0],6,-198630844);d=md5_ii(d,a,b,c,x[i+7],10,1126891415);c=md5_ii(c,d,a,b,x[i+14],15,-1416354905);b=md5_ii(b,c,d,a,x[i+5],21,-57434055);a=md5_ii(a,b,c,d,x[i+12],6,1700485571);d=md5_ii(d,a,b,c,x[i+3],10,-1894986606);c=md5_ii(c,d,a,b,x[i+10],15,-1051523);b=md5_ii(b,c,d,a,x[i+1],21,-2054922799);a=md5_ii(a,b,c,d,x[i+8],6,1873313359);d=md5_ii(d,a,b,c,x[i+15],10,-30611744);c=md5_ii(c,d,a,b,x[i+6],15,-1560198380);b=md5_ii(b,c,d,a,x[i+13],21,1309151649);a=md5_ii(a,b,c,d,x[i+4],6,-145523070);d=md5_ii(d,a,b,c,x[i+11],10,-1120210379);c=md5_ii(c,d,a,b,x[i+2],15,718787259);b=md5_ii(b,c,d,a,x[i+9],21,-343485551);a=safe_add(a,olda);b=safe_add(b,oldb);c=safe_add(c,oldc);d=safe_add(d,oldd);}
return Array(a,b,c,d);}
function md5_cmn(q,a,b,x,s,t)
{return safe_add(bit_rol(safe_add(safe_add(a,q),safe_add(x,t)),s),b);}
function md5_ff(a,b,c,d,x,s,t)
{return md5_cmn((b&c)|((~b)&d),a,b,x,s,t);}
function md5_gg(a,b,c,d,x,s,t)
{return md5_cmn((b&d)|(c&(~d)),a,b,x,s,t);}
function md5_hh(a,b,c,d,x,s,t)
{return md5_cmn(b^c^d,a,b,x,s,t);}
function md5_ii(a,b,c,d,x,s,t)
{return md5_cmn(c^(b|(~d)),a,b,x,s,t);}
function core_hmac_md5(key,data)
{var bkey=str2binl(key);if(bkey.length>16)bkey=core_md5(bkey,key.length*chrsz);var ipad=Array(16),opad=Array(16);for(var i=0;i<16;i++)
{ipad[i]=bkey[i]^0x36363636;opad[i]=bkey[i]^0x5C5C5C5C;}
var hash=core_md5(ipad.concat(str2binl(data)),512+data.length*chrsz);return core_md5(opad.concat(hash),512+128);}
function safe_add(x,y)
{var lsw=(x&0xFFFF)+(y&0xFFFF);var msw=(x>>16)+(y>>16)+(lsw>>16);return(msw<<16)|(lsw&0xFFFF);}
function bit_rol(num,cnt)
{return(num<<cnt)|(num>>>(32-cnt));}
function str2binl(str)
{var bin=Array();var mask=(1<<chrsz)-1;for(var i=0;i<str.length*chrsz;i+=chrsz)
bin[i>>5]|=(str.charCodeAt(i/chrsz)&mask)<<(i%32);return bin;}
function binl2str(bin)
{var str=new StringBuilder("");var mask=(1<<chrsz)-1;for(var i=0;i<bin.length*32;i+=chrsz)
str.append(String.fromCharCode((bin[i>>5]>>>(i%32))&mask));return str.toString();}
function binl2hex(binarray)
{var hex_tab=hexcase?"0123456789ABCDEF":"0123456789abcdef";var str=new StringBuilder("");for(var i=0;i<binarray.length*4;i++)
{str.append(hex_tab.charAt((binarray[i>>2]>>((i%4)*8+4))&0xF)+
hex_tab.charAt((binarray[i>>2]>>((i%4)*8))&0xF));}
return str.toString();}
function binl2b64(binarray)
{var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var str=new StringBuilder("");for(var i=0;i<binarray.length*4;i+=3)
{var triplet=(((binarray[i>>2]>>8*(i%4))&0xFF)<<16)|(((binarray[i+1>>2]>>8*((i+1)%4))&0xFF)<<8)|((binarray[i+2>>2]>>8*((i+2)%4))&0xFF);for(var j=0;j<4;j++)
{if(i*8+j*6>binarray.length*32)str.append(b64pad);else str.append(tab.charAt((triplet>>6*(3-j))&0x3F));}}
return str.toString();}


var g_Client;var LucidClient=function(User,Creator,Level){$.ajaxSetup({cache:false,timeout:20000});g_Client=this;this.User=User;this.Creator=Creator;this.Level=Level;this.Document=new LucidDocument();this.ConnectionId=null;this.ActionLog=[];this.Log=new LucidLog();this.ImageManager=new LucidImageManager();this._InitUI();this._InitPlugins();this._InitDialogs();this._InitAutoSave();this._InitInputFocus();if(this.User&&this.User.clipboard){try{this.Viewport.ClipboardData=JSON.parse(this.User.clipboard);}
catch(e){}}
var OnBeforeUnload=function(e){if(!e)e=window.event;if(g_Client.Document.IsModified()){var ret='You have made unsaved changes to this '+Configure.document_text+'.';e.returnValue=ret;return ret;}};window.onbeforeunload=OnBeforeUnload;if(is_ie){var Messages=['Want <span style="font-weight:bold;font-size:140%">10x better performance?</span> Consider using Firefox, Safari, or Chrome!','Want <span style="font-weight:bold;font-size:140%">more secure files?</span> Consider using Firefox, Safari, or Chrome!','Want <span style="font-weight:bold;font-size:140%">a better experience?</span> Consider using Firefox, Safari, or Chrome!','Want <span style="font-weight:bold;font-size:140%">no memory leaks?</span><br/>Consider using Firefox, Safari, or Chrome!'];var MessageIdx=0;function ShowMessage(){if($.cookie('noiewarnings')==null){$.jGrowl('<p>'+Messages[MessageIdx]+'</p><p><a style="text-decoration:underline;cursor:pointer;" id="noiewarnings">Stop bothering me!</a></p>');$('#noiewarnings').click(function(){$.cookie('noiewarnings','true');});}}
setInterval(function(){ShowMessage();MessageIdx=(MessageIdx+1)%Messages.length;},1000*60*5);setTimeoutFunction(function(){ShowMessage();},1000*30);}
StatusStack=[];$('body').append('<div id="ajaxStatus"></div>');$('#ajaxStatus').css({position:'absolute',left:'0',top:'0',padding:'8px',display:'none'}).addClass('ui-widget ui-state-default ui-corner-all').ajaxSend(function(e,r,settings){if(settings.status==null)return;$(this).css({left:$(g_Client.Viewport.Div).offset().left+4,top:$(g_Client.Viewport.Div).offset().top+4});if(StatusStack.length==0)
$(this).fadeIn(300);StatusStack.push(settings.status);$(this).html(settings.status);}).ajaxComplete(function(e,r,settings){if(settings.status==null)return;for(var i=0;i<StatusStack.length;i++){if(StatusStack[i]==settings.status){StatusStack.splice(i,1);if(StatusStack.length==0)
$(this).fadeOut(300);else
$(this).html(StatusStack[StatusStack.length-1]);break;}}});this.Role='viewer';}
LucidClient.prototype.IsDocumentCreator=function(){return this.Creator==null||this.User==null||this.Creator.id==this.User.id;}
LucidClient.prototype.KeyboardInputHasFocus=function(){return this.FocusedInput!=null||InlineEditor.CurrentId!=null||$('.ui-dialog:visible').size()>0;}
LucidClient.prototype.CanEdit=function(){return this.Role!='viewer'&&!this.Document.ViewingHistory;}
LucidClient.prototype.LockUI=function(msg){$.blockUI({message:'<p><img style="vertical-align:-17%" src="/img/editor/busy.gif"/> '+msg+'</p>'});}
LucidClient.prototype.UnlockUI=function(){$.unblockUI();}
LucidClient.prototype.GetUserRole=function(name,current,save,cancel,canremove,invite){this.RoleDialogSave=save;this.RoleDialogCancel=cancel==null?function(){}:cancel;if(!canremove)
$('#removeshare').css({display:'none'});else
$('#removeshare').css({display:'block'});$('input[name=role][value='+current+']').attr('checked','checked');$('#roledialoguser').html(name);this._SetUserRoleDialogInvite(invite);setTimeoutFunction(function(){$('#roledialog').dialog('open');$('button[innerText=Save]').focus();},1);}
LucidClient.prototype.InformFeatureRestriction=function(){jqAlert('<p>This feature is not available for '+this.Level.name+' subscribers.  Please consider <a target="_blank" href="/users/level">upgrading</a>!</p>');}
LucidClient.prototype.PromptLogin=function(AfterLoginAttempt){if(g_Client.IsPromptingLogin||g_Client.IsPromptingRegister)
return;g_Client.IsPromptingLogin=true;jqForm('/users/login',AfterLoginAttempt,function(dlg){dlg.find('a[innerHTML=Register]').click(function(){g_Client.IsPromptingRegister=true;dlg.dialog('close');jqForm('/users/register/free',AfterLoginAttempt,null,function(rdlg){if(!$('#eula').is(':checked')){jqAlert('<p>You must agree to the <a href="'+Configure.eula_link+'" target="_blank">'+Configure.eula_text+'</a> before registering your account with '+Configure.product+'.</p>');return false;}},null,null,function(){g_Client.IsPromptingRegister=false;});return false;});},null,null,null,function(){g_Client.IsPromptingLogin=false;});}
LucidClient.prototype.GetPublishFormat=function(currentFormat,currentDPI,save,AllowPDF){this.PublishFormatDialogSave=save;$('input[name=format][value='+currentFormat+']').attr('checked','checked');$('input[name=dpi][value='+currentDPI+']').attr('checked','checked');if(AllowPDF)
$('#publishformatpdfdiv').css({display:'block'});else
$('#publishformatpdfdiv').css({display:'none'});$('#publishformatdialog').dialog('open');}
LucidClient.prototype._InitPlugins=function(){this.PendingScripts=[];}
LucidClient.prototype._LoadNextScript=function(){if(this.PendingScripts.length==0)
return;var URL=this.PendingScripts[0];var path=URL.split('/');$('#currentpluginloading').html(path[path.length-1]);$.ajax({type:'GET',url:URL,success:function(code){g_Client.Document.RunAction({Action:'LoadPlugin',URL:URL,Code:code});g_Client.PendingScripts.splice(0,1);if(g_Client.PendingScripts.length>0)
g_Client._LoadNextScript();else
$.unblockUI();},error:function(){g_Client._LoadNextScript();}});}
LucidClient.prototype.LoadPlugin=function(URL){this.PendingScripts.push(URL);if(this.PendingScripts.length==1){$.blockUI({message:'<p>Loading plugins...<p><p id="currentpluginloading"></p>'});this._LoadNextScript();}}
LucidClient.prototype.SendChat=function(val,errCount){if(val=='')
return;if(this.Document.DocumentId==null){$.jGrowl('You must save your document before chatting.');return;}
if(errCount==null)
errCount=0;if(errCount>5)
return;$.ajax({type:"POST",url:"/chats/send",data:'data[Chat][message]='+encodeURIComponent(val)+'&data[Chat][document_id]='+encodeURIComponent(this.Document.DocumentId),error:function(){g_Client.SendChat(val,errCount+1);},status:'Sending chat message'});}
LucidClient.prototype._GetConnectionId=function(DocumentId,done){var url='/connections/create';if(DocumentId!=null)
url+='/'+DocumentId;$.ajax({type:'GET',url:url,success:function(msg){g_Client.Log.Log('chat',msg);g_Client.ConnectionId=msg;if(done!=null)
done();},error:function(){g_Client._GetConnectionId(DocumentId);}});}
LucidClient.prototype.New=function(Templates){var LoadedAutoSave=false;this.Role='owner';this.PendingAutoSaveDecision=true;this._GetConnectionId(null);$('body').append('<div id="TemplateList"></div>');var TemplateCount=0;var LastTemplateData=null;var AddTemplate=function(data){if(Configure.auto_template!=null&&data.DocumentTemplate.name!=Configure.auto_template)
return;TemplateCount++;LastTemplateData=data;var t=data.DocumentTemplate;var u=data.User;if(g_Client.User&&u.id&&u.id!=g_Client.User.id)
t.name+=htmlspecialchars(' ('+u.first_name+' '+u.last_name+')');$('#TemplateList').append('<div class="TemplateListItem">'
+'<h1 id="template_'+t.name.replace(/[^a-zA-Z0-9]/g,'')+'">'+t.name+'</h1>'
+'<p>'+t.description+'</p>'
+'</div>');$('#TemplateList h1:last').click(function(){$('#TemplateList h1').unbind('click');g_Client.LoadTemplate(t);if(!data.AutoSave){for(var i=0;i<g_Client.NewDocumentHooks.length;i++)
g_Client.NewDocumentHooks[i]();}
g_Client.PendingAutoSaveDecision=false;$.unblockUI();});};if(this.User!=null&&this.User.AutoSave!=null&&this.User.AutoSave.changes!=null){var as=this.User.AutoSave;$('#TemplateList').append('<h1>Auto-Saved '+Configure.Document_text+'</h1>');AddTemplate({User:this.User,DocumentTemplate:{name:'Auto-saved new '+Configure.document_text,description:'You left unsaved changes on a new '+Configure.document_text+'.  Would you like to load them now?',changes:as.changes},AutoSave:true});}
$('#TemplateList .TemplateListItem:last').css({'border-bottom':'0'});$('#TemplateList').append('<h1>'+Configure.product+' '+Configure.Document_text+' Templates</h1>');for(var i=0;i<Templates.System.length;i++)
AddTemplate(Templates.System[i]);if(Templates.User.length>0){$('#TemplateList .TemplateListItem:last').css({'border-bottom':'0'});$('#TemplateList').append('<h1>Your User-Created '+Configure.Document_text+' Templates</h1>');for(var i=0;i<Templates.User.length;i++)
AddTemplate(Templates.User[i]);}
if(Templates.Organization.length>0){$('#TemplateList .TemplateListItem:last').css({'border-bottom':'0'});$('#TemplateList').append('<h1>'+Configure.Document_text+' Templates From Your Organization</h1>');for(var i=0;i<Templates.Organization.length;i++)
AddTemplate(Templates.Organization[i]);}
if(TemplateCount==1){g_Client.LoadTemplate(LastTemplateData.DocumentTemplate);if(!LastTemplateData.AutoSave){for(var i=0;i<g_Client.NewDocumentHooks.length;i++)
g_Client.NewDocumentHooks[i]();}
g_Client.PendingAutoSaveDecision=false;$('#TemplateList').remove();}
else{$('#TemplateList').attr('id','TemplateList2');$.blockUI({message:'<div id="TemplateList" style="overflow-y:auto;overflow-x:hidden;text-align:left;height:'+Math.round(WindowHeight()*.6)+'px;">'
+'</div>',css:{cursor:'auto',top:'20%',width:'400px',border:'1px solid black'}});$('#TemplateList').append($('#TemplateList2'));}
if(this.User!=null){setTimeoutFunction(function(){g_Client.GetChat();},1000);}}
LucidClient.prototype.NewDocumentHooks=[];LucidClient.prototype.HookNewDocument=function(f){this.NewDocumentHooks.push(f);}
LucidClient.prototype.LoadTemplate=function(t){g_Client.LogAction('template-'+t.name);var c=JSON.parse(t.changes);for(var i=0;i<c.length;i++)
this.Document.RunAction(c[i]);this.Document.ClearUndoHistory();this.Viewport.SelectFirstPage();}
LucidClient.prototype.GetPreference=function(p){if(this.User&&this.User.preferences&&this.User.preferences[p])
return this.User.preferences[p];return null;}
LucidClient.prototype.Load=function(Document){this._GetConnectionId(Document.Document.id);this.Role=Document.DocumentsUser.role;if(this.Role==null)
this.Role='viewer';var ActionHistory=[];var SaveHistory=[];for(var i=0;i<Document.Change.length;i++){var c=Document.Change[i];if(c.changes.length>2)
ActionHistory.push(c.changes.substr(1,c.changes.length-2));SaveHistory.push({UserName:c['Change']['0']['UserName'],Date:c.created,Count:eval(c.changes).length});}
this.Document.Deserialize('['+ActionHistory.join(',')+']',Document.Document.id,Document.Document.next_connection_id,SaveHistory,function(){g_Client.Document.IsPublished=Document.published==1;g_Client.Document.PublicSegment=Document.PublicSegment;g_Client.Viewport.SelectFirstPage();setTimeoutFunction(function(){g_Client.GetChat();},1000);if(g_Client.User!=null){for(var key in Document.AutoSave){var as=Document.AutoSave[key];if(as.user_id==g_Client.User.id){g_Client.PendingAutoSaveDecision=true;jqAlert('You left unsaved changes on this '+Configure.document_text+'.  Would you like to load them now?',null,{Yes:function(){var changes=JSON.parse(as.changes);for(var i=0;i<changes.length;i++)
g_Client.Document.RunAction(changes[i],true);g_Client.Document.ClearUndoHistory();g_Client.LogAction('useAutoSaveExisting');},No:function(){},'Discard Unsaved Changes':function(){$.ajax({type:'POST',url:'/autoSaves/delete',data:'data[AutoSave][id]='+encodeURIComponent(as.id)});}},null,null,function(){g_Client.PendingAutoSaveDecision=false;});break;}}}});}
LucidClient.prototype.SaveAs=function(){jqPrompt('Please enter a title for this new copy.',g_Client.Document.GetPropertyValue('Title'),function(NewTitle){g_Client.Document.RunAction({Action:'SetProperty',id:null,Property:'Title',Value:NewTitle});g_Client.Document.MakeUnsaved();g_Client.Role='owner';g_Client.ConnectionId=null;g_Client.DiscardGetChat=true;g_Client._GetConnectionId(null,function(){g_Client.Save();});});}
LucidClient.prototype.SaveTemplate=function(){var formdata=null;var SaveTemplate=function(){if($('#DocumentTemplateName').val()==''){jqAlert('Please enter a name for this '+Configure.document_text+' template.');return false;}
var changes=g_Client.Document.SerializeChanges(true);var md5=g_Client._md5(changes);if(formdata==null)
formdata=GetFormQueryString('#templateform');data='data[DocumentTemplate][md5]='+encodeURIComponent(md5)+'&'+formdata;data+='&data[DocumentTemplate][changes]='+encodeURIComponent(changes);data+='&data[DocumentTemplate][version]=2';$.ajax({type:'POST',url:'/documentTemplates/save',data:data,success:function(msg){msg=JSON.parse(msg);if(msg.Success){}
else if(msg.Code==1){g_Client.PromptLogin(function(){SaveTemplate();});}
else if(msg.Code==2){jqAlert('<p>'+g_Client.Level.name+' does not support custom document templates.</p>'
+'<p>If you wish to remove this restriction, you should <a target="_blank" href="/users/level">upgrade</a> to a higher subscription level.</p>');}
else{$.jGrowl(Configure.Document_text+' template could not be saved.  Please try again.');}},error:function(){$.jGrowl(Configure.Document_text+' template could not be saved.  Please try again.');},status:'Saving '+Configure.Document_text+' template'});};jqAlert('<div id="templateform">'
+'<p>This will save this '+Configure.document_text+' as a new <i>template</i>.  This means that each time you create '
+'a new '+Configure.document_text+' in '+Configure.product+', you will be able to use this '+Configure.document_text+' as a starting point.</p>'
+'<div class="input text"><label for="DocumentTemplateName">Template Name</label><input name="data[DocumentTemplate][name]" id="DocumentTemplateName" type="text" maxlength="80" value="New Template" />'
+'<div class="input text"><label for="DocumentTemplateDescription">Description</label><textarea name="data[DocumentTemplate][description]" id="DocumentTemplateDescription"></textarea>'
+'</div>','Save '+Configure.Document_text+' Template',{'Save Template':SaveTemplate,Cancel:function(){}},400,true);}
LucidClient.prototype.Save=function(Silent){if(this.IsSaving){if(g_Client.Document.GetPropertyValue('RealTimeCollaboration'))
g_Client.AutoSaveCall.Queue(10);return;}
if(this.Role=='viewer')
return;if(this.Document.ViewingHistory)
this.Document.ExitHistoryView();if(!this.Document.IsModified()){if(!Silent)
$.jGrowl('No changes to save.');return;}
if(!this.Document.HasSetTitle()){if(!Silent){g_Client.EditTitle(function(){g_Client.Save();});return;}}
this.IsSaving=true;g_Client.Log.Log('iss','true');var c=this;var RevisionSaved=this.Document.ActionHistory.length;g_Client.Log.Log('Save','Prep work done');var changes=this.Document.SerializeChanges();g_Client.Log.Log('Save','Serialized changes');var pdfdata=g_Client.Document.GetPDFData();g_Client.Log.Log('Save','Got PDF data');pdfdata=JSON.stringify(pdfdata);g_Client.Log.Log('Save','Serialized PDF data');var data='data[Change][0][md5]='+encodeURIComponent(this._md5(changes))
+'&data[Document][title]='+encodeURIComponent(this.Document.GetPropertyValue('Title'))
+'&data[Change][0][version]=2'
+'&data[Change][0][user_agent]='+encodeURIComponent(navigator.userAgent)
+'&data[Document][pdfdata]='+encodeURIComponent(pdfdata)
+'&data[Change][0][changes]='+encodeURIComponent(changes)
+'&data[LoadedActionHistoryLength]='+encodeURIComponent(this.Document.LoadedActionHistory.length);if(this.Document.DocumentId!=null){data='data[Document][id]='+encodeURIComponent(this.Document.DocumentId)+'&'+data;}
g_Client.Log.Log('update','**** Saving - '+JSON.stringify({Document_LoadedActionHistory_length:this.Document.LoadedActionHistory.length,Document_ActionHistory_length:this.Document.ActionHistory.length,sent_length:JSON.parse(changes).length}));this.Document.LockUpdates();$.ajax({type:"POST",url:"/documents/save/"+this.ConnectionId,data:data,timeout:Math.max(20000,data.length),success:function(msg){g_Client.Log.Log('save',msg);g_Client.Log.Log('update','Save returned: '+msg);try{var d=JSON.parse(msg);}
catch(err){return;}
if(g_Client.Document.DocumentId==null)
g_Client.Document.DocumentId=d.id;if(d.Success){g_Client.Document.MarkAllActionsCommitted(RevisionSaved);if(g_Client.User==null){window.location.href='/documents/edit/'+d.id;return;}}
else if(d.Update){var Conflicts=g_Client.Document.Update(d.Update,d.SaveHistory,d.ActionHistoryLength,d.SavedActionHistoryLength);g_Client.AutoSaveCall.Queue(10);if(!Silent){if(Conflicts!=null&&Conflicts.length>0){$.jGrowl('<b>Your changes are not yet saved</b>.  Other users have changed this '+Configure.document_text+'.  Their changes have been merged into yours; please check to make sure everything looks OK.',{life:10000});}
else{$.jGrowl('<b>Your changes are not yet saved</b>.  Other users have changed this '+Configure.document_text+'.  Their changes have been merged into yours without any problems.',{life:7000});}}}
else if(d.Code==1){g_Client.PromptLogin(function(){g_Client.Save();});}
else if(d.Code==4){if(g_Client.IsDocumentCreator()){var message='<p>You have used up the '+(g_Client.Level.storage/1024)+'MB of storage allowed by '+g_Client.Level.name+'.</p>'
+'<p>To continue saving your changes, you need to <a target="_blank" href="/users/level">upgrade</a> to a higher subscription level.</p>';}
else{var message='<p>'+g_Client.Creator.first_name+' '+g_Client.Creator.last_name+' has used up the '+(g_Client.Level.storage/1024)+'MB of storage allowed by '+g_Client.Level.name+'.</p>'
+'<p>To continue saving changes to this document, '+g_Client.Creator.first_name+' '+g_Client.Creator.last_name+' needs to <a target="_blank" href="/users/level">upgrade</a> to a higher subscription level.</p>';}
jqAlert(message);}
else{g_Client.AutoSaveCall.Queue(10);if(!Silent)
$.jGrowl(d.Error);}},error:function(){g_Client.AutoSaveCall.Queue(10);if(!Silent)
$.jGrowl('Save timed out.  Please try again.');},complete:function(){g_Client.IsSaving=false;g_Client.Log.Log('iss','false');g_Client.Document.UnlockUpdates();},status:Silent?null:'Saving'});}
LucidClient.prototype.Print=function(format,PageId,SelectArea,DPI){if(PageId==null)
var data=this.Document.GetPDFData();else
var data=this.Document.GetPDFData(this.Document.Pages[PageId]);var url='/documents/pdf';if(format!=null){url+='/'+format;if(!SelectArea){if(DPI==null)
DPI=this.Viewport.SelectedPage.GetPropertyValue('DPI')*this.Viewport.Scale;url+='/'+DPI;}}
if(SelectArea){this.Viewport.SelectPageSegment('Select a portion of this page to print.',function(x,y,w,h){if(DPI==null)
DPI=g_Client.Viewport.SelectedPage.GetPropertyValue('DPI')*g_Client.Viewport.Scale;url+='/'+DPI;url+='/'+x+'/'+y+'/'+w+'/'+h;$('#PDFForm').attr('action',url);$('#PDFPages').val(JSON.stringify(data));$('#PDFTitle').val(g_Client.Document.GetPropertyValue('Title'));$('#PDFForm').submit();});}
else{$('#PDFForm').attr('action',url);$('#PDFPages').val(JSON.stringify(data));$('#PDFTitle').val(g_Client.Document.GetPropertyValue('Title'));$('#PDFForm').submit();}}
LucidClient.prototype.Close=function(){window.close();}
LucidClient.prototype._InitMarkupWatcher=function(){this.MarkupItems=[];var Tick=function(){var WasDirty=false;for(var i=0;i<g_Client.MarkupItems.length;i++){if(g_Client.MarkupItems[i].MarkupDirty){g_Client.MarkupItems[i].RefreshMarkup();for(var j=0;j<g_Client.MarkupItems[i].MarkupHooks.length;j++)
g_Client.MarkupItems[i].MarkupHooks[j]();g_Client.MarkupItems[i].MarkupDirty=false;WasDirty=true;}}
if(WasDirty){g_Client._Layout();g_Client.Log.Log('Render','g_Client._Layout (MarkupWatcher.Tick)');}};setInterval(Tick,100);}
LucidClient.prototype._RegisterMarkupItem=function(Item,RefreshMarkup){Item.MarkupDirty=true;Item.RefreshMarkup=RefreshMarkup;this.MarkupItems.push(Item);Item.MarkupHooks=[];Item.RegisterMarkupHook=function(f){this.MarkupHooks.push(f);}}
LucidClient.prototype._InitLayout=function(){this.LayoutDirty=false;setInterval(function(){var w=Math.max(400,WindowWidth());var h=Math.max(400,WindowHeight());if(g_Client.LastLayoutWidth!=w||g_Client.LastLayoutHeight!=h){g_Client.Log.Log('Render','g_Client.LayoutDirty=true (LayoutDirty.Tick/SizeChange)');g_Client.LayoutDirty=true;}
if(g_Client.LayoutDirty){g_Client.Log.Log('Render','g_Client._Layout (LayoutDirty.Tick)');g_Client._Layout();g_Client.LayoutDirty=false;g_Client.LastLayoutWidth=w;g_Client.LastLayoutHeight=h;}},100);$(window).bind('load','resize',function(){g_Client._Layout();g_Client.Log.Log('Render','g_Client._Layout (Window.Load/Resize)');});}
LucidClient.prototype._Layout=function(){for(var i=0;i<3;i++){$('div.panel').each(function(){if(g_Client.TabControl.SelectedPanel==null||this.id!=g_Client.TabControl.SelectedPanel.PanelId)
$(this).css({display:'none'});});if(this.Role=='viewer')
$('#toolboxdiv,#menu_Properties').css({display:'none'});else
$('#toolboxdiv,#menu_Properties').css({display:'block'});if(this.User==null&&this.Role=='viewer')
$('#panelcontrol').css({display:'none'});else
$('#panelcontrol').css({display:'block'});var layout=[{DOM:'#title',Dock:'top'},{Dock:'top',Size:25,Children:[{DOM:'#menu',Dock:'left',Align:'bottom',Size:this.MainMenu.GetTargetWidth()},{DOM:'#panelcontrol',Dock:'right',Align:'bottom',Size:this.TabControl.GetTargetWidth()}]},{Dock:'left',Size:180,Children:[{DOM:'#thumbnaildiv',Dock:'top'},{DOM:'#logo',Dock:'bottom',w:180},{DOM:'#toolboxdiv',wd:-4}]},{DOM:'#pagesdiv',Dock:'bottom'},{DOM:'#viewport'}];if(this.TabControl.SelectedPanel!=null){$('#'+this.TabControl.SelectedPanel.PanelId).css({display:'block',width:this.TabControl.SelectedPanel.Width+'px'});layout.splice(4,0,{DOM:'#'+this.TabControl.SelectedPanel.PanelId,Dock:'right',AutoSize:false});}
$('#menu,#panelcontrol').css({height:'auto'});SetupLayout(layout);}
this.ShareTab.Layout();this.Viewport.Invalidate();g_Client.Log.Log('Render','Viewport.Invalidate (Client._Layout)');}
$(function(){$.extend($.fn.disableTextSelect=function(){return this.each(function(){if($.browser.mozilla){$(this).css('MozUserSelect','none');}else if($.browser.msie){$(this).bind('selectstart',function(){return false;});}else{$(this).mousedown(function(){return false;});}});});$('.noSelect').disableTextSelect();});LucidClient.prototype._InitUI=function(){this._InitLayout();this._InitMarkupWatcher();this._InitToolbox();this._InitViewport();this._InitThumbnail();this._InitPageList();this._InitMainMenu();this._InitTabControl();this._InitTitle();this._InitArrowKeys();$('body').append('<img id="logo" style="width:180px;height:32px" src="/img/logo_client.png"/>');$('body').append('<div id="testtext" style="position:absolute;left:-10000px;width:200px;height:200px;"></div>');$('body').append("<iframe name='pdfframe' style='display:none;'></iframe><form id='PDFForm' target='pdfframe' method='POST' action='/documents/pdf'><input type='hidden' name='pages' id='PDFPages'/><input type='hidden' name='title' id='PDFTitle'/></form>");if(is_ie){$('#PDFForm').attr('target','_blank');}
this.Document.HookActions(function(a){if(a.Action=='SetProperty'&&a.id==null&&a.Property=='Title')
document.title=a.Value+' - '+Configure.product;});setInterval(function(){$('#toolboxdiv,#menu,#panelcontrol,#title,#thumbnaildiv,#logo,#pagesdiv').disableTextSelect().find('a').bind('dragstart',function(e){return false;});},5000);}
LucidClient.prototype._InitArrowKeys=function(){function OneArrowKey(key,x,y){$(document).bind('keydown',key,function(){if(!g_Client.KeyboardInputHasFocus()){g_Client.Document.StartUndoBatch();var GridSpacing=g_Client.Viewport.SelectedPage.GetPropertyValue('GridSpacing');var Items=g_Client.Viewport.SelectedPage.GetSelection();var Offsets={};for(var i=0;i<Items.length;i++){Offsets[Items[i].id]={x:x*GridSpacing,y:y*GridSpacing,w:0,h:0};}
g_Client.Viewport.MoveItems(Items,Offsets);g_Client.Document.EndUndoBatch();return false;}});}
OneArrowKey('up',0,-1);OneArrowKey('down',0,1);OneArrowKey('left',-1,0);OneArrowKey('right',1,0);}
LucidClient.prototype.EditTitle=function(after){if(!g_Client.CanEdit())return;jqPrompt('Please enter a title for this new '+Configure.document_text+'.',g_Client.Document.GetPropertyValue('Title'),function(NewTitle){g_Client.Document.RunAction({Action:'SetProperty',id:null,Property:'Title',Value:NewTitle});if(after!=null)
after();});}
LucidClient.prototype._InitTitle=function(){$('body').append('<h1 id="title"><span title="Click to rename this document">'+g_Client.Document.GetPropertyValue('Title')+'</span><span id="titlestatus"></span></h1>');$('#title span:first').click(function(){g_Client.EditTitle();});$('#title').append('<div id="complexitybar"><div id="complexity"></div>Document Complexity</div>');$('#complexitybar').css({display:'none',position:'absolute',textAlign:'center',right:'4px',top:'4px',height:'16px',width:'192px',font:'12px arial',border:'1px solid #aaaaaa',padding:'2px 4px',cursor:'pointer'}).addClass('ui-corner-all').click(function(){if(g_Client.IsDocumentCreator()){jqAlert('<p>'+g_Client.Level.name+' only allows up to '+g_Client.Level.document_objects+' objects to be drawn on each document.  This bar will fill up as you approach that limit.</p>'
+'<p>If you wish to remove this restriction, you should <a target="_blank" href="/users/level">upgrade</a> to a paid subscription.</p>');}
else{jqAlert('<p>'+g_Client.Level.name+' only allows up to '+g_Client.Level.document_objects+' objects to be drawn on each document.  This bar will fill up as you approach that limit.</p>'
+'<p>To remove this restriction from this document, '+g_Client.Creator.first_name+' '+g_Client.Creator.last_name+' should <a target="_blank" href="/users/level">upgrade</a> to a paid subscription.</p>');}});$('#complexity').css({background:'url(/img/editor/complexity_gradient.png)',position:'absolute',top:'0px',left:'0px',height:'20px',width:'32px',zIndex:-1});setInterval(function(){if(g_Client.Level.document_objects>0){var ratio=g_Client.Document.NumObjects/g_Client.Level.document_objects;if(ratio==1){if(g_Client.IsDocumentCreator())
$.jGrowl('You have reached the document complexity limit.  Consider upgrading.');else
$.jGrowl('You have reached the document complexity limit.  Please urge '+g_Client.Creator.first_name+' '+g_Client.Creator.last_name+' to upgrade.');}
else if(ratio>0.8){if(g_Client.IsDocumentCreator())
$.jGrowl('You are nearing the document complexity limit.  Consider upgrading.');else
$.jGrowl('You are nearing the document complexity limit.  Please urge '+g_Client.Creator.first_name+' '+g_Client.Creator.last_name+' to upgrade.');}}},90000);setInterval(function(){if(g_Client.Level.document_objects>0){$('#complexitybar').css({display:'block'});var ratio=g_Client.Document.NumObjects/g_Client.Level.document_objects;$('#complexity').css({width:(ratio*200)+'px'});}
else
$('#complexitybar').css({display:'none'});if(g_Client.Document.DocumentId==null)
$('#titlestatus').html(' (Unsaved)');else{if(g_Client.Document.IsModified()&&!g_Client.Document.GetPropertyValue('RealTimeCollaboration'))
$('#titlestatus').html(' (Modified)');else
$('#titlestatus').html('');}},1000);}
LucidClient.prototype._InitTabControl=function(){this.TabControl=new LucidTabControl();this.PropertiesTab=new LucidPropertiesTab();this.ShareTab=new LucidShareTab();this.PublishTab=new LucidPublishTab();this.HistoryTab=new LucidHistoryTab();}
LucidClient.prototype._InitPageList=function(){this.PageList=new LucidPageList();}
LucidClient.prototype._InitMainMenu=function(){var OneLineSelected=function(){if(g_Client.Viewport.SelectedPage==null)
return false;var s=g_Client.Viewport.SelectedPage.GetSelection();return s.length==1&&s[0].IsLine;}
var LinesSelected=function(){if(g_Client.Viewport.SelectedPage==null)
return false;var s=g_Client.Viewport.SelectedPage.GetSelection();for(var i=0;i<s.length;i++){if(!s[i].IsLine)
return false;}
return s.length>0;}
var HasSelection=function(){return g_Client.Viewport.SelectedPage&&g_Client.Viewport.SelectedPage.GetSelection().length>0;}
var HasClipboard=function(){return g_Client.Viewport.ClipboardData!=null;}
this.ContextMenu=new LucidMenu(true,'CanvasContextMenu',this.Viewport.Canvas.container);this.ContextMenu.AddMenuItem('Add Text',function(c){var a={Action:'SetProperty',id:g_Client.Viewport.SelectedPage.GetSelection()[0].id,Property:'TextAreas',Value:{Text:{Location:.5,Side:0,Value:'Text'}}};g_Client.Document.RunAction(a);g_Client.Document._FindObject(a.id)._EditText('Text');g_Client.LogAction('addTextToLine');},function(){if(!OneLineSelected())
return false;var ta=g_Client.Viewport.SelectedPage.GetSelection()[0].GetPropertyValue('TextAreas');return ta.Text==null;},null,'page_edit.png');this.ContextMenu.AddMenuItem('Remove Text',function(c){var a={Action:'SetProperty',id:g_Client.Viewport.SelectedPage.GetSelection()[0].id,Property:'TextAreas',Value:{Text:null}};g_Client.Document.RunAction(a);},function(){if(!OneLineSelected())
return false;var ta=g_Client.Viewport.SelectedPage.GetSelection()[0].GetPropertyValue('TextAreas');return ta.Text!=null;},null,'page_edit.png');this.ContextMenu.AddMenuItem('Copy',CallerFn(LucidViewport.prototype.CopySelectionToClipboard,this.Viewport),HasSelection,null,'page_copy.png');this.ContextMenu.AddMenuItem('Cut',function(){g_Client.Viewport.CopySelectionToClipboard();g_Client.Viewport.DeleteSelection();},HasSelection,null,'cut.png');this.ContextMenu.AddMenuItem('Paste',function(c,pos){var va=g_Client.Viewport.ViewableArea();g_Client.Viewport.PasteFromClipboard(pos.x,pos.y);},HasClipboard,null,'paste_plain.png');this.ContextMenu.AddMenuItem('Bring To Front',CallerFn(LucidViewport.prototype.BringSelectionToFront,this.Viewport),HasSelection,null,'shape_move_front.png');this.ContextMenu.AddMenuItem('Send To Back',CallerFn(LucidViewport.prototype.SendSelectionToBack,this.Viewport),HasSelection,null,'shape_move_back.png');this.ContextMenu.AddMenuItem('Delete',function(){g_Client.Viewport.DeleteSelection();},HasSelection,null,'delete.png');this.ContextMenu.AddMenuItem('Reset Default Shape',function(){g_Client.Document.StartUndoBatch();var s=g_Client.Viewport.SelectedPage.GetSelection();for(var i=0;i<s.length;i++){g_Client.Document.RunAction({Action:'SetProperty',id:s[i].id,Property:'ControlPoints',Value:{}});g_Client.Document.RunAction({Action:'SetProperty',id:s[i].id,Property:'Points',Value:null});}
g_Client.Document.EndUndoBatch();g_Client.LogAction('resetLineShape');},LinesSelected,null,'page_white_edit.png');this.ContextMenu.AddMenuItem('Edit Line Shape',function(){g_Client.Viewport.EditLinePoints(g_Client.Viewport.SelectedPage.GetSelection()[0]);},OneLineSelected,null,'page_white_edit.png');this.ContextMenu.AddMenuItem('More Properties',function(){g_Client.TabControl.ShowPanel('Properties');},null,null,'application_form_edit.png');this.PageListContextMenu=new LucidMenu(true,'PageListContextMenu');this.PageListContextMenu.AddMenuItem('Rename',function(c){$(c).dblclick();},null,null,'textfield_rename.png');this.PageListContextMenu.AddMenuItem('Delete Page',function(c){g_Client.Document.RunAction({Action:'RemovePage',id:$(c).attr('PageId')});},function(){return ObjectSize(g_Client.Document.Pages)>1;},null,'delete.png');this.MainMenu=new LucidMenu();this.MainMenu.AddMenuItem('File/New '+Configure.Document_text,function(){window.open('/documents/edit');});this.MainMenu.AddMenuItem('File/Rename '+Configure.Document_text,function(){$('#title span:first').click();});this.MainMenu.AddMenuItem('File/Save',CallerFn(LucidClient.prototype.Save,this),null,'Ctrl+S');this.MainMenu.AddMenuItem('File/Save As (Copy)',CallerFn(LucidClient.prototype.SaveAs,this));this.MainMenu.AddMenuItem('File/Save Template',CallerFn(LucidClient.prototype.SaveTemplate,this));this.MainMenu.AddMenuItem('File/Print To PDF',function(){g_Client.Print();},null,'Ctrl+P');this.MainMenu.AddMenuItem('File/Close Document',CallerFn(LucidClient.prototype.Close,this));this.MainMenu.AddMenuItem('Page/Print To PDF Or Image',function(){g_Client.GetPublishFormat('pdf','',function(format,dpi){if(format=='pdf')
g_Client.Print('pdf',g_Client.Viewport.SelectedPage.id);else{if(dpi=='')
dpi=Math.round(g_Client.Viewport.SelectedPage.GetPropertyValue('DPI')*g_Client.Viewport.Scale);g_Client.Print(format,g_Client.Viewport.SelectedPage.id,false,dpi);}},true);});this.MainMenu.AddMenuItem('Page/Print Portion To Image',function(){g_Client.GetPublishFormat('png','',function(format,dpi){if(dpi=='')
dpi=Math.round(g_Client.Viewport.SelectedPage.GetPropertyValue('DPI')*g_Client.Viewport.Scale);g_Client.Print(format,g_Client.Viewport.SelectedPage.id,true,dpi);},false);});this.MainMenu.AddMenuItem('Page/Stretch Content To Fit',function(){g_Client.Viewport.SelectedPage.FitContent();});this.MainMenu.AddMenuItem('Page/Rename Current Page',function(){$('li[PageId='+g_Client.Viewport.SelectedPage.id+']').dblclick();});this.MainMenu.AddMenuItem('Page/Delete Current Page',function(){g_Client.Document.RunAction({Action:'RemovePage',id:g_Client.Viewport.SelectedPage.id});},function(){return ObjectSize(g_Client.Document.Pages)>1;});this.MainMenu.AddMenuItem('Edit/Draw Line',CallerFn(LucidViewport.prototype.EnterDrawLineMode,this.Viewport),null,'L');this.MainMenu.AddMenuItem('Edit/Undo',CallerFn(LucidDocument.prototype.Undo,this.Document),function(){return g_Client.Document.CanUndo()&&g_Client.CanEdit();},'Ctrl+Z');this.MainMenu.AddMenuItem('Edit/Redo',CallerFn(LucidDocument.prototype.Redo,this.Document),function(){return g_Client.Document.CanRedo()&&g_Client.CanEdit();},'Ctrl+Y');this.MainMenu.AddMenuItem('Edit/Delete',CallerFn(LucidViewport.prototype.DeleteSelection,this.Viewport),function(){return g_Client.Viewport.SelectedPage&&g_Client.Viewport.SelectedPage.GetSelection().length>0;},'Del');this.MainMenu.AddMenuItem('Edit/Copy',CallerFn(LucidViewport.prototype.CopySelectionToClipboard,this.Viewport),HasSelection,'Ctrl+C');this.MainMenu.AddMenuItem('Edit/Cut',function(){g_Client.Viewport.CopySelectionToClipboard();g_Client.Viewport.DeleteSelection();},HasSelection,'Ctrl+X');this.MainMenu.AddMenuItem('Edit/Paste',function(){var va=g_Client.Viewport.ViewableArea();g_Client.Viewport.PasteFromClipboard(va.x+va.w/2,va.y+va.h/2);},HasClipboard,'Ctrl+V');this.MainMenu.AddMenuItem('Edit/Preferences',function(){jqForm('/users/preferences');});this.MainMenu.AddMenuItem('View/Zoom In',function(){g_Client.Viewport.ZoomIn();},null,'Ctrl+Up');this.MainMenu.AddMenuItem('View/Zoom Out',function(){g_Client.Viewport.ZoomOut();},null,'Ctrl+Down');this.MainMenu.AddMenuItem('View/Zoom Normal',function(){g_Client.Viewport.ZoomNormal();},null,'Ctrl+Left');this.MainMenu.AddMenuItem('View/Zoom Page Width',function(){g_Client.Viewport.ZoomWidth();},null,'Ctrl+Right');this.MainMenu.AddMenuItem('View/Zoom Full Page',function(){g_Client.Viewport.ZoomPage();},null);$(document).bind('keydown','F9',function(){jqPrompt('Which log would you like to view?','Render',function(val){g_Client.Log.ShowLog(val);});});}
LucidClient.prototype._InitInputFocus=function(){this.FocusedInput=null;this.AllInputs=[];setInterval(function(){g_Client._UpdateInputFocusEvents();},1000);}
LucidClient.prototype._UpdateInputFocusEvents=function(){var NewInputs=[];$('input[type=text],textarea').each(function(){NewInputs.push(this);if(arrayIndexOf(g_Client.AllInputs,this)==-1){$(this).focus(function(){g_Client.FocusedInput=this;});$(this).blur(function(){g_Client.FocusedInput=null;});}});this.AllInputs=NewInputs;if(this.FocusedInput!=null&&arrayIndexOf(this.AllInputs,this.FocusedInput)==-1)
this.FocusedInput=null;}
LucidClient.prototype._InitToolbox=function(){this.Toolbox=new LucidToolbox();}
LucidClient.prototype._InitViewport=function(){this.Viewport=new LucidViewport();}
LucidClient.prototype._InitThumbnail=function(){this.Thumbnail=new LucidThumbnail();}
LucidClient.prototype.LogAction=function(a){if(!this.User||!this.User.actions)
return;if($.inArray(a,this.User.actions)==-1)
this.User.actions.push(a);this.ActionLog.push({Action:a,Date:(new Date()).toUTCString()});}
LucidClient.prototype.GetChat=function(){if(this.LastChatId==null)
this.LastChatId=0;if(this.ConnectionId==null){setTimeout(function(){g_Client.GetChat();},1000);return;}
var url='/chats/get/'+this.ConnectionId;if(this.Document.DocumentId!=null)
url+='/'+encodeURIComponent(this.Document.LoadedActionHistory.length)+'/'+encodeURIComponent(this.LastChatId);else
url+='/NULL/NULL';var ActionLog=this.ActionLog;this.ActionLog=[];var ChatError=false;g_Client.Log.Log('chat',url);this.GetChatAjaxCall=$.ajax({type:"POST",url:url,timeout:25000,data:'NoSSLChange=true&Now='+encodeURIComponent((new Date()).toUTCString())+'&Actions='+encodeURIComponent(JSON.stringify(ActionLog)),success:function(msg){g_Client.Log.Log('chat',msg);if(g_Client.DiscardGetChat){g_Client.DiscardGetChat=false;return;}
try{var d=JSON.parse(msg);}catch(e){ChatError=true;return;}
if(g_Client.Document.DocumentId==null)
g_Client.Document.DocumentId=d.document_id;if(d['clipboard']!=null){try{g_Client.Viewport.ClipboardData=JSON.parse(d['clipboard']);}
catch(e){}}
if(g_Client.User){if(g_Client.User.preferences.HideGrid!=d.preferences.HideGrid)
g_Client.Viewport.InvalidateBackground();g_Client.User.preferences=d.preferences;}
g_Client.Level=d.level;if(g_Client.Document.DocumentId!=null){g_Client.LastChatId=d['last_id'];if(g_Client.User!=null)
g_Client.ShareTab.DealWithGetChatResult(d);g_Client.Document.IsPublished=d.published==1;g_Client.Document.PublicSegments=d.public_segments;g_Client.PublishTab._UpdateAll();g_Client.Viewport.InvalidateBackground();if(d['ActionHistoryLength']>g_Client.Document.LoadedActionHistory.length){var Conflicts=g_Client.Document.Update(d.changes,d.SaveHistory,d.ActionHistoryLength,d.SavedActionHistoryLength);if(Conflicts!=null){if(!g_Client.Document.GetPropertyValue('RealTimeCollaboration')){if(Conflicts.length>0){$.jGrowl('Other users have changed this '+Configure.document_text+'.  Their changes have been merged into yours; please check to make sure everything looks OK.',{life:10000});}
else{$.jGrowl('Other users have changed this '+Configure.document_text+'.  Their changes have been merged into yours without any problems.',{life:7000});}}}}}},error:function(XMLHttpRequest,textStatus,errorThrown){ChatError=true;g_Client.ActionLog.concat(ActionLog);g_Client.Log.Log('chat',JSON.stringify(['Error result.',textStatus,errorThrown]));},complete:function(){if(ChatError){setTimeoutFunction(function(){g_Client.GetChat();},1000*10);}
else{g_Client.GetChat();}}});}
LucidClient.prototype._InitDialogs=function(){this._InitUserRoleDialog();this._InitPublishFormatDialog();}
LucidClient.prototype._InitPublishFormatDialog=function(){$('body').append("<div class='dialog' id='publishformatdialog'>"
+"<p>What format would you like to publish in?</p>"
+"<p><div id='publishformatpdfdiv'><input type='radio' name='format' value='pdf' id='format_pdf'/> <label for='format_pdf'>PDF - Recommended for printing.</label><br/></div>"
+"<input type='radio' name='format' value='png' id='format_png'/> <label for='format_png'>PNG - Recommended image format.</label><br/>"
+"<input type='radio' name='format' value='jpeg' id='format_jpeg'/> <label for='format_jpeg'>JPEG</label></p>"
+"<p>If you selected PNG or JPEG, please select the image quality you would prefer.</p>"
+"<p><input type='radio' name='dpi' value='300' id='format_300dpi'/> <label for='format_300dpi'>Print quality (300 DPI)</label><br/>"
+"<input type='radio' name='dpi' value='160' id='format_160dpi'/> <label for='format_160dpi'>Screen quality (160 DPI)</label><br/>"
+"<input type='radio' name='dpi' value='' id='format_zdpi'/> <label for='format_zdpi'>Current zoom level</label></p>"
+"</div>");$('#publishformatdialog').dialog({autoOpen:false,buttons:{Save:function(){if($('input[Name=format]:checked').size()==0){jqAlert('Please select a format for publishing.');return;}
if($('input[Name=format]:checked').val()=='pdf'&&$('input[Name=dpi]:checked').size()==0){jqAlert('Please select a quality/DPI setting for publishing.');return;}
g_Client.PublishFormatDialogSave($('input[Name=format]:checked').val(),$('input[Name=dpi]:checked').val());$('#publishformatdialog').dialog('close');},Cancel:function(){$('#publishformatdialog').dialog('close');}},height:300,width:500,modal:true,resizable:false,title:'Select Format and Quality'});}
LucidClient.prototype._InitUserRoleDialog=function(){$('body').append("<div class='dialog' id='roledialog'>"
+"<p>What role should <span id='roledialoguser'>USER</span> have for this "+Configure.document_text+"?</p>"
+"<p><input type='radio' name='role' value='owner' id='role_owner'/> <label for='role_owner'>Owner - This user has full permissions for this "+Configure.document_text+", including changing other users' permissions for this "+Configure.document_text+".</label></p>"
+"<p><input type='radio' name='role' value='author' id='role_author'/> <label for='role_author'>Author - This user may view and make changes to this "+Configure.document_text+".</label></p>"
+"<p><input type='radio' name='role' value='viewer' id='role_viewer'/> <label for='role_viewer'>Viewer - This user may view this "+Configure.document_text+", but may not make changes or view its history.</label></p>"
+"<p id='removeshare'><input type='radio' name='role' id='role_none' value=''/> <label for='role_none'>None - This user will no longer be allowed to access this "+Configure.document_text+".</label></p>"
+"</div>");this._SetUserRoleDialogInvite=function(IsInvite){if(IsInvite)
$('label[for=role_none]').html("None - The invitation to share this "+Configure.document_text+" will be canceled.");else
$('label[for=role_none]').html("None - This user will no longer be allowed to access this "+Configure.document_text+".");}
$('#roledialog').dialog({autoOpen:false,buttons:{Save:function(){if($('input[Name=role]:checked').size()==0){jqAlert('Please select a role for this user.');return;}
g_Client.RoleDialogSave($('input[Name=role]:checked').val());$('#roledialog').dialog('close');},Cancel:function(){g_Client.RoleDialogCancel();$('#roledialog').dialog('close');}},height:300,width:500,modal:true,resizable:false,title:'Select User Role'});}
LucidClient.prototype._md5=function(data){if(is_ie){return"length:"+Utf8.encode(data).length;}
else{return hex_md5(Utf8.encode(data));}}
LucidClient.prototype._InitAutoSave=function(){var AutoSave=new ConsolidatedFunctionCall(function(){g_Client.Log.Log('AutoSave','AutoSave function called');if(g_Client.IsSaving){g_Client.Log.Log('AutoSave','Returned because currently saving');return;}
if(g_Client.PendingAutoSaveDecision||g_Client.Document.ViewingHistory||g_Client.Document.IsDeserializing){g_Client.Log.Log('AutoSave','Returned because of Document state: '+[g_Client.PendingAutoSaveDecision,g_Client.Document.ViewingHistory,g_Client.Document.IsDeserializing]);return;}
if(g_Client.Document.GetPropertyValue('RealTimeCollaboration')&&g_Client.Document.DocumentId!=null){g_Client.Log.Log('AutoSave','Saving instead of AutoSave (real-time)');g_Client.Save(true);return;}
if(g_Client.User!=null&&g_Client.Document.IsModified()){if(g_Client.CurrentlyAutosaving){g_Client.Log.Log('AutoSave','Currently autosaving already, skipping...');g_Client.AutoSaveCall.Queue(500);return;}
var BeforePrep=new Date();var changes=g_Client.Document.SerializeChanges();var data='data[AutoSave][md5]='+encodeURIComponent(g_Client._md5(changes))
+'&data[AutoSave][user_id]='+encodeURIComponent(g_Client.User.id)
+'&data[AutoSave][changes]='+encodeURIComponent(changes)
+'&data[AutoSave][version]=2';if(g_Client.Document.DocumentId!=null)
data+='&data[AutoSave][document_id]='+encodeURIComponent(g_Client.Document.DocumentId);var AfterPrep=new Date();g_Client.Log.Log('AutoSave','Autosave, data length '+changes.length+', prep took '+(AfterPrep.getTime()-BeforePrep.getTime())+'ms');g_Client.CurrentlyAutosaving=true;$.ajax({type:'POST',url:'/autoSaves/save',data:data,success:function(msg){try{var d=JSON.parse(msg);}
catch(e){return;}
if(d.Success){}},complete:function(){g_Client.CurrentlyAutosaving=false;}});}
else{g_Client.Log.Log('AutoSave','Skipped because demo or unmodified');}},3000);this.AutoSaveCall=AutoSave;this.Document.HookActions(function(a){if(g_Client.Document.GetPropertyValue('RealTimeCollaboration'))
AutoSave.Queue(10);else
AutoSave.Queue();});setInterval(function(){if(g_Client.Document.GetPropertyValue('RealTimeCollaboration')){if(g_Client.Document.IsModified())
AutoSave.Queue(10);}},100);setInterval(function(){if(!g_Client.Document.GetPropertyValue('RealTimeCollaboration')){if(g_Client.Document.IsModified())
AutoSave.Queue();}},1000*60);}
LucidClient.prototype.GoCrazy=function(){function DoOneThing(){if(g_Client.Viewport.SelectedPage==null)
return;var r=Math.floor(Math.random()*11);if(r==0)
g_Client.Save();else if(r==1){g_Client.Document.RunAction({"Action":"CreateBlock","Class":"PreparationBlock","Properties":{"ZOrder":1,"LineWidth":2,"LineColor":"#000000","FillColor":"#ffffff","BoundingBox":{"x":Math.floor(Math.random()*1000),"y":Math.floor(Math.random()*1000),"w":160,"h":120}},"Page":g_Client.Viewport.SelectedPage.id});}
else if(r==2){g_Client.Document.RunAction({"Action":"CreateLine","Page":g_Client.Viewport.SelectedPage.id,"Properties":{"LineColor":"#000000","LineWidth":2,"ZOrder":12,"StrokeStyle":"solid","TextAreas":{"IsFullPropSettings":true},"Endpoint1":{"x":Math.floor(Math.random()*1000),"y":Math.floor(Math.random()*1000),"Style":"None"},"Endpoint2":{"x":Math.floor(Math.random()*1000),"y":Math.floor(Math.random()*1000),"Style":"Arrow"},"Shape":"curve"}});}
else if(r==3){for(var id in g_Client.Viewport.SelectedPage.Blocks){g_Client.Document.RunAction({"Action":"RemoveBlock","id":id});break;}}
else if(r==4||r==9){for(var id in g_Client.Viewport.SelectedPage.Lines){g_Client.Document.RunAction({"Action":"RemoveLine","id":id});break;}}
else if(r<=7){for(var id in g_Client.Viewport.SelectedPage.Blocks){g_Client.Document.RunAction({"Action":"SetProperty","id":id,"Property":"LineColor","Value":"#ff00ff"});break;}}
else{for(var id in g_Client.Viewport.SelectedPage.Lines){g_Client.Document.RunAction({"Action":"SetProperty","id":id,"Property":"LineColor","Value":"#00ffff"});break;}}}
this.CrazyInterval=setInterval(DoOneThing,100);}
LucidClient.prototype.StopCrazy=function(){clearInterval(this.CrazyInterval);}

