
var saveDataLocation=appName+"/Main/saveXMLData.xdo";var saveXMLLocation=appName+"/Main/saveXMLData.xdo";var resourcePrefix=appName+"/jsgi/themes/"+themeName+"/artwork/";var ajaxQueryLocation=appName+"/Main/ajax.do";var keyFieldPattern="|tableName|id";var helpLinkLocation=appName+"/Main/helpLinks.do";var defaultHelpLocation=appName+"/System/Help.do";var hoveredTable=null;var csvLocation=appName+"/Main/outputCSV.do";var imageMap={clearPx:"clear-pixel.gif",clearButton:"table/clear-filter.png",newRecord:"table/toolbar/add-row.png",deleteRecords:"table/toolbar/trashcan.png",showTrash:"table/toolbar/trashcan.png",close:"table/close-popup.png",print:"table/toolbar/print.png",csv:"table/toolbar/csv.png",subtotals:"table/toolbar/subtotals.png",spreadsheetOn:"table/settings/spreadsheet-mode.png",spreadsheetOff:"table/settings/spreadsheet-mode-off.png",colToggle:"table/settings/col-widget-inactive.png",colToggleActive:"table/settings/col-widget-active.png",scrollUp:"table/scroll/up.png",scrollDown:"table/scroll/down.png",save:"page/save-inactive.png",saveActive:"page/save-active.png",calendar:"page/calendar.png",closeWeek:"page/close-week.png",grabLight:"page/grabLight.png",grabDark:"page/grabDark.png",zoomRow:"table/zoom-row.gif",share:"calendar/share.png",editRoot:"table/sourcelist/edit-root.png",editRootHover:"table/sourcelist/edit-root-hover.png",trashcan:"calendar/trashcan.png",addEvent:"calendar/add-event.png",logout:"page/logout.png",pageInfo:"page/info.png",systemHelp:"page/help.png",saveInactive:"page/save-inactive.png",back:"page/back.gif"};function loadPersonalMenu(){if(typeof menu_html=="undefined"){jQuery.get("/main/generate_menu",function(userid){jQuery.getScript("/javascripts/menucache-"+userid+".js",function(stuff){jQuery('#systemMenu').html(menu_html);});});}else{jQuery('#systemMenu').html(menu_html);}}
function loadPersonalSlider(){if(typeof menu_html=="undefined"){jQuery.get("/main/generate_slider",function(userid){jQuery.getScript("/javascripts/menucache-"+userid+".js",function(stuff){jQuery('#systemMenu').html(menu_html);});});}else{jQuery('#systemMenu').html(menu_html);}}
function getSectionName(){var locParts=window.location.pathname.split('/');return locParts[3];}
(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.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")}})})();(function($){$.extend($.fn,{livequery:function(type,fn,fn2){var self=this,q;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&type==query.type&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid))return(q=query)&&false;});q=q||new $.livequery(this.selector,this.context,type,fn,fn2);q.stopped=false;$.livequery.run(q.id);return this;},expire:function(type,fn,fn2){var self=this;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&(!type||type==query.type)&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid)&&!this.stopped)$.livequery.stop(query.id);});return this;}});$.livequery=function(selector,context,type,fn,fn2){this.selector=selector;this.context=context||document;this.type=type;this.fn=fn;this.fn2=fn2;this.elements=[];this.stopped=false;this.id=$.livequery.queries.push(this)-1;fn.$lqguid=fn.$lqguid||$.livequery.guid++;if(fn2)fn2.$lqguid=fn2.$lqguid||$.livequery.guid++;return this;};$.livequery.prototype={stop:function(){var query=this;if(this.type)this.elements.unbind(this.type,this.fn);else if(this.fn2)this.elements.each(function(i,el){query.fn2.apply(el);});this.elements=[];this.stopped=true;},run:function(){if(this.stopped)return;var query=this;var oEls=this.elements,els=$(this.selector,this.context),nEls=els.not(oEls);this.elements=els;if(this.type){nEls.bind(this.type,this.fn);if(oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)$.event.remove(el,query.type,query.fn);});}else{nEls.each(function(){query.fn.apply(this);});if(this.fn2&&oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)query.fn2.apply(el);});}}};$.extend($.livequery,{guid:0,queries:[],queue:[],running:false,timeout:null,checkQueue:function(){if($.livequery.running&&$.livequery.queue.length){var length=$.livequery.queue.length;while(length--)$.livequery.queries[$.livequery.queue.shift()].run();}},pause:function(){$.livequery.running=false;},play:function(){$.livequery.running=true;$.livequery.run();},registerPlugin:function(){$.each(arguments,function(i,n){if(!$.fn[n])return;var old=$.fn[n];$.fn[n]=function(){var r=old.apply(this,arguments);$.livequery.run();return r;}});},run:function(id){if(id!=undefined){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);}else
$.each($.livequery.queries,function(id){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);});if($.livequery.timeout)clearTimeout($.livequery.timeout);$.livequery.timeout=setTimeout($.livequery.checkQueue,20);},stop:function(id){if(id!=undefined)$.livequery.queries[id].stop();else
$.each($.livequery.queries,function(id){$.livequery.queries[id].stop();});}});$.livequery.registerPlugin('append','prepend','after','before','wrap','attr','removeAttr','addClass','removeClass','toggleClass','empty','remove');$(function(){$.livequery.play();});var init=$.prototype.init;$.prototype.init=function(a,c){var r=init.apply(this,arguments);if(a&&a.selector)r.context=a.context,r.selector=a.selector;if(typeof a=='string')r.context=c||document,r.selector=a;return r;};$.prototype.init.prototype=$.prototype;})(jQuery);jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};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;}};(function($){$.fn.ajaxSubmit=function(options){if(typeof options=='function')
options={success:options};options=$.extend({url:this.attr('action')||window.location,type:this.attr('method')||'GET'},options||{});var a=this.formToArray(options.semantic);if(options.beforeSubmit&&options.beforeSubmit(a,this,options)===false)return this;var veto={};$.event.trigger('form.submit.validate',[a,this,options,veto]);if(veto.veto)
return this;var q=$.param(a);if(options.type.toUpperCase()=='GET'){options.url+=(options.url.indexOf('?')>=0?'&':'?')+q;options.data=null;}
else
options.data=q;var $form=this,callbacks=[];if(options.resetForm)callbacks.push(function(){$form.resetForm();});if(options.clearForm)callbacks.push(function(){$form.clearForm();});if(!options.dataType&&options.target){var oldSuccess=options.success;callbacks.push(function(data){$(options.target).attr("innerHTML",data).evalScripts().each(oldSuccess,arguments);});}
else if(options.success)
callbacks.push(options.success);options.success=function(data,status){for(var i=0,max=callbacks.length;i<max;i++)
callbacks[i](data,status,$form);};var files=$('input:file',this).fieldValue();var found=false;for(var j=0;j<files.length;j++)
if(files[j])
found=true;if(options.iframe||found)
fileUpload();else
$.ajax(options);$.event.trigger('form.submit.notify',[this,options]);return this;function fileUpload(){var form=$form[0];var opts=$.extend({},$.ajaxSettings,options);var id='jqFormIO'+$.fn.ajaxSubmit.counter++;var $io=$('<iframe id="'+id+'" name="'+id+'" />');var io=$io[0];var op8=$.browser.opera&&window.opera.version()<9;if($.browser.msie||op8)io.src='javascript:false;document.write("");';$io.css({position:'absolute',top:'-1000px',left:'-1000px'});var xhr={responseText:null,responseXML:null,status:0,statusText:'n/a',getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){}};var g=opts.global;if(g&&!$.active++)$.event.trigger("ajaxStart");if(g)$.event.trigger("ajaxSend",[xhr,opts]);var cbInvoked=0;var timedOut=0;setTimeout(function(){$io.appendTo('body');io.attachEvent?io.attachEvent('onload',cb):io.addEventListener('load',cb,false);var encAttr=form.encoding?'encoding':'enctype';var t=$form.attr('target');$form.attr({target:id,method:'POST',encAttr:'multipart/form-data',action:opts.url});if(opts.timeout)
setTimeout(function(){timedOut=true;cb();},opts.timeout);form.submit();$form.attr('target',t);},10);function cb(){if(cbInvoked++)return;io.detachEvent?io.detachEvent('onload',cb):io.removeEventListener('load',cb,false);var ok=true;try{if(timedOut)throw'timeout';var data,doc;doc=io.contentWindow?io.contentWindow.document:io.contentDocument?io.contentDocument:io.document;xhr.responseText=doc.body?doc.body.innerHTML:null;xhr.responseXML=doc.XMLDocument?doc.XMLDocument:doc;if(opts.dataType=='json'||opts.dataType=='script'){var ta=doc.getElementsByTagName('textarea')[0];data=ta?ta.value:xhr.responseText;if(opts.dataType=='json')
eval("data = "+data);else
$.globalEval(data);}
else if(opts.dataType=='xml'){data=xhr.responseXML;if(!data&&xhr.responseText!=null)
data=toXml(xhr.responseText);}
else{data=xhr.responseText;}}
catch(e){ok=false;$.handleError(opts,xhr,'error',e);}
if(ok){opts.success(data,'success');if(g)$.event.trigger("ajaxSuccess",[xhr,opts]);}
if(g)$.event.trigger("ajaxComplete",[xhr,opts]);if(g&&!--$.active)$.event.trigger("ajaxStop");if(opts.complete)opts.complete(xhr,ok?'success':'error');setTimeout(function(){$io.remove();xhr.responseXML=null;},100);};function toXml(s,doc){if(window.ActiveXObject){doc=new ActiveXObject('Microsoft.XMLDOM');doc.async='false';doc.loadXML(s);}
else
doc=(new DOMParser()).parseFromString(s,'text/xml');return(doc&&doc.documentElement&&doc.documentElement.tagName!='parsererror')?doc:null;};};};$.fn.ajaxSubmit.counter=0;$.fn.ajaxForm=function(options){return this.ajaxFormUnbind().submit(submitHandler).each(function(){this.formPluginId=$.fn.ajaxForm.counter++;$.fn.ajaxForm.optionHash[this.formPluginId]=options;$(":submit,input:image",this).click(clickHandler);});};$.fn.ajaxForm.counter=1;$.fn.ajaxForm.optionHash={};function clickHandler(e){var $form=this.form;$form.clk=this;if(this.type=='image'){if(e.offsetX!=undefined){$form.clk_x=e.offsetX;$form.clk_y=e.offsetY;}else if(typeof $.fn.offset=='function'){var offset=$(this).offset();$form.clk_x=e.pageX-offset.left;$form.clk_y=e.pageY-offset.top;}else{$form.clk_x=e.pageX-this.offsetLeft;$form.clk_y=e.pageY-this.offsetTop;}}
setTimeout(function(){$form.clk=$form.clk_x=$form.clk_y=null;},10);};function submitHandler(){var id=this.formPluginId;var options=$.fn.ajaxForm.optionHash[id];$(this).ajaxSubmit(options);return false;};$.fn.ajaxFormUnbind=function(){this.unbind('submit',submitHandler);return this.each(function(){$(":submit,input:image",this).unbind('click',clickHandler);});};$.fn.formToArray=function(semantic){var a=[];if(this.length==0)return a;var form=this[0];var els=semantic?form.getElementsByTagName('*'):form.elements;if(!els)return a;for(var i=0,max=els.length;i<max;i++){var el=els[i];var n=el.name;if(!n)continue;if(semantic&&form.clk&&el.type=="image"){if(!el.disabled&&form.clk==el)
a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y});continue;}
var v=$.fieldValue(el,true);if(v&&v.constructor==Array){for(var j=0,jmax=v.length;j<jmax;j++)
a.push({name:n,value:v[j]});}
else if(v!==null&&typeof v!='undefined')
a.push({name:n,value:v});}
if(!semantic&&form.clk){var inputs=form.getElementsByTagName("input");for(var i=0,max=inputs.length;i<max;i++){var input=inputs[i];var n=input.name;if(n&&!input.disabled&&input.type=="image"&&form.clk==input)
a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y});}}
return a;};$.fn.formSerialize=function(semantic){return $.param(this.formToArray(semantic));};$.fn.fieldSerialize=function(successful){var a=[];this.each(function(){var n=this.name;if(!n)return;var v=$.fieldValue(this,successful);if(v&&v.constructor==Array){for(var i=0,max=v.length;i<max;i++)
a.push({name:n,value:v[i]});}
else if(v!==null&&typeof v!='undefined')
a.push({name:this.name,value:v});});return $.param(a);};$.fn.fieldValue=function(successful){for(var val=[],i=0,max=this.length;i<max;i++){var el=this[i];var v=$.fieldValue(el,successful);if(v===null||typeof v=='undefined'||(v.constructor==Array&&!v.length))
continue;v.constructor==Array?$.merge(val,v):val.push(v);}
return val;};$.fieldValue=function(el,successful){var n=el.name,t=el.type,tag=el.tagName.toLowerCase();if(typeof successful=='undefined')successful=true;if(successful&&(!n||el.disabled||t=='reset'||t=='button'||(t=='checkbox'||t=='radio')&&!el.checked||(t=='submit'||t=='image')&&el.form&&el.form.clk!=el||tag=='select'&&el.selectedIndex==-1))
return null;if(tag=='select'){var index=el.selectedIndex;if(index<0)return null;var a=[],ops=el.options;var one=(t=='select-one');var max=(one?index+1:ops.length);for(var i=(one?index:0);i<max;i++){var op=ops[i];if(op.selected){var v=$.browser.msie&&!(op.attributes['value'].specified)?op.text:op.value;if(one)return v;a.push(v);}}
return a;}
return el.value;};$.fn.clearForm=function(){return this.each(function(){$('input,select,textarea',this).clearFields();});};$.fn.clearFields=$.fn.clearInputs=function(){return this.each(function(){var t=this.type,tag=this.tagName.toLowerCase();if(t=='text'||t=='password'||tag=='textarea')
this.value='';else if(t=='checkbox'||t=='radio')
this.checked=false;else if(tag=='select')
this.selectedIndex=-1;});};$.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=='function'||(typeof this.reset=='object'&&!this.reset.nodeType))
this.reset();});};})(jQuery);$.fn.autocompletify=function(){return this.each(function(){if($(this).hasClass("marked")){return;}
var $autocomplete=$('<ul id="'+$(this).attr("name")+'-results"></ul>').addClass("autocompleteOptions").hide().insertAfter($(this));var $tb=$(this);$(this).addClass("marked");var selectedItem=null;var setSelectedItem=function(item){selectedItem=item;if(selectedItem===null){$autocomplete.hide();return;}
if(selectedItem<0){selectedItem=0;}
if(selectedItem>=$autocomplete.find('li').length){selectedItem=$autocomplete.find('li').length-1;}
$autocomplete.find('li').removeClass('selected');$autocomplete.find('li:eq('+selectedItem+')').addClass('selected');$autocomplete.show();};var populateSearchField=function(){$tb.val($autocomplete.find('li:eq('+selectedItem+')').text());if($tb.attr("submitafter")){$tb.parents("form").trigger("submit");}else{var parts=$tb.val().split(". ");var id=parts[0];var label=parts[1];var summary=$("<div class='lookup_summary'></div>").append('<input type="hidden" name="'+$tb.attr("name")+'-id"  value="'+id+'" />').append(label).append($('<button>Change</button>').click(function(event){$(event.target).parent().hide("fast").remove();summary=null;$tb.show("fast").val("").focus();}));$tb.hide().parent().find(".lookup_summary").remove().end().append(summary);}
$(':text.autocomplete').autocompletify();setSelectedItem(null);};if(!$(this).attr("default_text")==$(this).val()){$(this).val($(this).attr("default_text")).addClass("hinted")}
$(this).attr('autocomplete','off').keyup(function(event){console.log(event.keyCode);if(event.keyCode>40||event.keyCode==8){var q={};q[$(event.target).attr("name")]=$(event.target).val();$.ajax({url:event.target.getAttribute("href"),data:q,type:'GET',success:function(data){$autocomplete.empty().append(data).find("li").click(populateSearchField);setSelectedItem(0);}});}else if(event.keyCode==38&&selectedItem!==null){setSelectedItem(selectedItem-1);event.preventDefault();}else if(event.keyCode==40&&selectedItem!==null){setSelectedItem(selectedItem+1);event.preventDefault();}else if(event.keyCode==27&&selectedItem!==null){setSelectedItem(null);}}).keypress(function(event){if(event.keyCode==13&&selectedItem!==null){populateSearchField();event.preventDefault();}}).focus(function(event){event.target.value="";$(event.target).removeClass("hinted");}).blur(function(event){setTimeout(function(){setSelectedItem(null);},250);});});}
jQuery.autocomplete=function(input,options){var me=this;var $input=$(input).attr("autocomplete","off");var elID,elName;var keyFieldName=(options.createKeyField)?addKeyField():options.existingKeyField||null;function addKeyField(){elID=input.getAttribute('id');elName=input.getAttribute('name');input.setAttribute('id',elID+'_fmtval');input.setAttribute('name',elName+'_fmtval');return createKeyField();}
function createKeyField(){var kf=document.createElement('input');kf.setAttribute('type','hidden');kf.setAttribute('id',elID);kf.setAttribute('name',elName);input.parentNode.appendChild(kf);return kf.getAttribute('name');}
function getKeyField(name){return $('[name='+name+']').get(0);}
if(options.inputClass){$input.addClass(options.inputClass);}
var results=document.createElement("div");var $results=$(results);$results.hide().addClass(options.resultsClass).css("position","absolute");if(options.width>0){$results.css("width",options.width);}
$("body").append(results);input.autocompleter=me;var timeout=null;var prev="";var active=-1;var cache={};var keyb=false;var hasFocus=false;var lastKeyPressCode=null;function flushCache(){cache={};cache.data={};cache.length=0;}
flushCache();if(options.data!=null){var sFirstChar="",stMatchSets={},row=[];if(typeof options.url!="string"){options.cacheLength=1;}
for(var i=0,len=options.data.length;i<len;i++){row=(typeof options.data[i]=="string")?[options.data[i]]:options.data[i];if(row[0].length>0){sFirstChar=row[0].substring(0,1).toLowerCase();if(!stMatchSets[sFirstChar]){stMatchSets[sFirstChar]=[];}
stMatchSets[sFirstChar].push(row);}}
for(var k in stMatchSets){options.cacheLength++;addToCache(k,stMatchSets[k]);}}
$input.keydown(function(e){lastKeyPressCode=e.keyCode;switch(e.keyCode){case 38:e.preventDefault();moveSelect(-1);break;case 40:e.preventDefault();moveSelect(1);break;case 9:case 13:if(selectCurrent()){$input.get(0).blur();e.preventDefault();}
break;default:active=-1;if(timeout){clearTimeout(timeout);}
timeout=setTimeout(function(){onChange();},options.delay);break;}}).focus(function(){hasFocus=true;}).blur(function(){hasFocus=false;hideResults();});hideResultsNow();function onChange(){if(lastKeyPressCode==46||(lastKeyPressCode>8&&lastKeyPressCode<32)){return $results.hide();}
var v=$input.val();if(v==prev){return;}
prev=v;if(v.length>=options.minChars){$input.addClass(options.loadingClass);requestData(v);}
else{$input.removeClass(options.loadingClass);$results.hide();}}
function moveSelect(step){var lis=$("li",results);if(!lis){return;}
active+=step;if(active<0){active=0;}
else if(active>=lis.size()){active=lis.size()-1;}
lis.removeClass("ac_over");$(lis[active]).addClass("ac_over");}
function selectCurrent(){var li=$("li.ac_over",results)[0];if(!li){var $li=$("li",results);if(options.selectOnly){if($li.length==1){li=$li[0];}}
else if(options.selectFirst){li=$li[0];}}
if(li){selectItem(li);return true;}
else{return false;}}
function selectItem(li){if(!li){li=document.createElement("li");li.data={};li.selectValue="";}
var v=$.trim(li.selectValue?li.selectValue:li.innerHTML);input.lastSelected=v;prev=v;$results.html("");$input.val(v);hideResultsNow();if(keyFieldName){setTimeout(function(){var keyField=getKeyField(keyFieldName);keyField.value=li.data[keyFieldName];},1);}
if(options.onItemSelect){setTimeout(function(){options.onItemSelect(input,getKeyField(keyFieldName),li);},1);}}
function createSelection(start,end){var field=$input.get(0);if(field.createTextRange){var selRange=field.createTextRange();selRange.collapse(true);selRange.moveStart("character",start);selRange.moveEnd("character",end);selRange.select();}
else if(field.setSelectionRange){field.setSelectionRange(start,end);}
else{if(field.selectionStart){field.selectionStart=start;field.selectionEnd=end;}}
field.focus();}
function autoFill(sValue){if(lastKeyPressCode!=8){$input.val($input.val()+sValue.substring(prev.length));createSelection(prev.length,sValue.length);}}
function showResults(){var pos=findPos(input);var iWidth=(options.width>0)?options.width:$input.width();$results.css({width:parseInt(iWidth)+"px",top:(pos.y+input.offsetHeight)+"px",left:pos.x+"px"}).show();getKeyField(keyFieldName).value='';}
function hideResults(){if(timeout){clearTimeout(timeout);}
timeout=setTimeout(hideResultsNow,200);}
function hideResultsNow(){if(timeout){clearTimeout(timeout);}
$input.removeClass(options.loadingClass);if($results.is(":visible")){$results.hide();}
if(options.mustMatch){var v=$input.val();if(v!=input.lastSelected){selectItem(null);}}}
function receiveData(q,data){if(data){$input.removeClass(options.loadingClass);results.innerHTML="";if(!hasFocus||data.length==0){return hideResultsNow();}
if($.browser.msie){$results.append(document.createElement('iframe'));}
results.appendChild(dataToDom(data));if(options.autoFill&&($input.val().toLowerCase()==q.toLowerCase())){autoFill(data[0].value);}
showResults();}
else{hideResultsNow();}}
function dataToDom(data){var ul=document.createElement("ul");var num=((options.maxItemsToShow>0)&&(options.maxItemsToShow<num))?options.maxItemsToShow:data.length;for(var i=0;i<num;i++){var row=data[i];if(!row){continue;}
var li=document.createElement("li");li.selectValue=row.value;li.innerHTML=(options.formatItem)?options.formatItem(row,i,num):row.value;li.data=row;ul.appendChild(li);$(li).hover(function(){$("li",ul).removeClass("ac_over");$(this).addClass("ac_over");active=$("li",ul).indexOf($(this).get(0));},function(){$(this).removeClass("ac_over");}).click(function(e){e.preventDefault();e.stopPropagation();selectItem(this);});}
return ul;}
function requestData(q){if(!options.matchCase){q=q.toLowerCase();}
var data=options.cacheLength?loadFromCache(q):null;if(data){receiveData(q,data);}
else if((typeof options.url=="string")&&(options.url.length>0)){options.extraParams.q=q;$.post(options.url,options.extraParams,function(data){addToCache(q,data);receiveData(q,data);},'json');}
else{$input.removeClass(options.loadingClass);}}
function addToCache(q,data){if(!data||!q||!options.cacheLength){return;}
if(!cache.length||cache.length>options.cacheLength){flushCache();cache.length++;}
else if(!cache[q]){cache.length++;}
cache.data[q]=data;}
function loadFromCache(q){if(!q){return null;}
if(cache.data[q]){return cache.data[q];}
if(options.matchSubset){for(var i=q.length-1;i>=options.minChars;i--){var qs=q.substr(0,i);var c=cache.data[qs];if(c){var csub=[];for(var j=0;j<c.length;j++){var x=c[j];var x0=x[keyFieldName];if(matchSubset(x0,q)){csub[csub.length]=x;}}
return csub;}}}
return null;}
function matchSubset(s,sub){if(!options.matchCase){s=s.toLowerCase();}
var i=s.indexOf(sub);if(i==-1){return false;}
return i==0||options.matchContains;}
this.flushCache=function(){flushCache();}
this.setExtraParams=function(p){options.extraParams=p;}
this.findValue=function(){var q=$input.val();if(!options.matchCase){q=q.toLowerCase();}
var data=options.cacheLength?loadFromCache(q):null;if(data){findValueCallback(q,data);}
else if((typeof options.url=="string")&&(options.url.length>0)){options.extraParams.q=q;$.post(options.url,options.extraParams,function(data){addToCache(q,data);findValueCallback(q,data);},'json');}
else{findValueCallback(q,null);}}
function findValueCallback(q,data){if(data){$input.removeClass(options.loadingClass);}
var num=(data)?data.length:0;var li=null;for(var i=0;i<num;i++){var row=data[i];if(row.value.toLowerCase()==q.toLowerCase()){li=document.createElement("li");li.selectValue=row.value;li.innerHTML=(options.formatItem)?options.formatItem(row,i,num):row.value;li.data=row;}}
if(options.onFindValue){setTimeout(function(){options.onFindValue(li)},1);}}
function findPos(obj){var curleft=obj.offsetLeft||0;var curtop=obj.offsetTop||0;while(obj=obj.offsetParent){curleft+=obj.offsetLeft
curtop+=obj.offsetTop}
return{x:curleft,y:curtop};}};jQuery.fn.autocomplete=function(url,options,data){options=options||{};options.url=url;options.data=((typeof data=="object")&&(data.constructor==Array))?data:null;options.inputClass=options.inputClass||"ac_input";options.resultsClass=options.resultsClass||"ac_results";options.lineSeparator=options.lineSeparator||"\n";options.cellSeparator=options.cellSeparator||"|";options.minChars=options.minChars||1;options.delay=options.delay||400;options.matchCase=(options.matchCase!=null)?options.matchCase:0;options.matchSubset=(options.matchSubset!=null)?options.matchSubset:1;options.matchContains=options.matchContains||1;options.cacheLength=options.cacheLength||1;options.mustMatch=options.mustMatch||0;options.extraParams=options.extraParams||{};options.loadingClass=options.loadingClass||"ac_loading";options.selectFirst=options.selectFirst||false;options.selectOnly=options.selectOnly||false;options.maxItemsToShow=options.maxItemsToShow||-1;options.autoFill=options.autoFill||false;options.width=parseInt(options.width,10)||0;options.createKeyField=options.createKeyField||false;options.existingKeyField=options.existingKeyField||null;this.each(function(){var input=this;new jQuery.autocomplete(input,options);});return this;};jQuery.fn.autocompleteArray=function(data,options){return this.autocomplete(null,options,data);};jQuery.fn.indexOf=function(e){for(var i=0,len=this.length;i<len;i++){if(this[i]==e){return i;}}
return-1;};var JSGI={autoTabSequences:{},firstNewRowBox:null,messageCounter:0,validationSaveBlock:0,hoveredTable:null,pageElements:{},pageElementCounter:1,click:{},dblclick:{},mouseover:{},mouseout:{},mousemove:{},mousedown:{},mouseup:{},focus:{},blur:{},counters:{},keyup:{},util:{},controls:{},CRUD:{},KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,incrementCounter:function(name){if(!this.counters[name]){this.counters[name]=0;}
this.counters[name]++;},decrementCounter:function(name){this.counters[name]--;},currentCount:function(name){return this.counters[name];},getEventRef:function(evt){if(typeof evt=='undefined'||!evt){return event;}else{return evt;}},getEventTarget:function(e){evt=e||event;return(evt.target)?evt.target:((evt.srcElement)?evt.srcElement:null);},getCoordinates:function(e){var posx=0;var posy=0;if(!e){var e=window.event;}
if(e.pageX||e.pageY){posx=e.pageX;posy=e.pageY;}
else if(e.clientX||e.clientY){posx=e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;posy=e.clientY+document.body.scrollTop+document.documentElement.scrollTop;}
return{top:posy,left:posx};},RoundRect:function(width,borderSize,color,innerColor,message){var main=HTML.div();HTML.setWidth(main,width);template=Images.get('clearPx');template.style.backgroundColor=color;template.style.height='1px';var lines=[];for(var i=0;i<borderSize;i++){var line=template.cloneNode(true);line.style.marginLeft=i+'px';line.style.width=(width-(i*2))+'px';lines.push(line);}
var topLines=lines.reverse();for(var i=0,len=topLines.length;i<len;i++){main.appendChild(topLines[i]);}
var content=HTML.div();content.style.width=(jQuery.browser.msie)?width+'px':(width-12-(borderSize*2))+'px';content.style.border='0 solid black';content.style.borderColor=color;content.style.padding='6px';content.style.borderWidth="0 "+borderSize+'px';content.style.backgroundColor=innerColor;if(arguments[5]){message+="<br/><a class='messageDetailLink' href=\"javascript:manualMessageClose('"+JSGI.messageCounter+"');\">Close</a> :: <a class='messageDetailLink' href=\"javascript:showDetails('"+JSGI.messageCounter+"')\">Details >></a>";message+="<div class='messageDetail' id='detail"+JSGI.messageCounter+"'>"+arguments[5]+"</div>";}
content.innerHTML=message;main.appendChild(content);for(var i=0;i<borderSize;i++){var line=template.cloneNode(true);line.style.marginLeft=i+'px';line.style.width=(width-(i*2))+'px';main.appendChild(line);}
return main;}};function object(baseObject){function F(){};F.prototype=baseObject
return F();}
function mapDom(node,fn){fn(node);node=node.firstChild;while(node){mapDom(node,fn);node=node.nextSibling;}}
function isUndefined(x){return typeof x=='undefined';}
function isInt(x){return typeof x=='integer';}
function getViewSize(){var myWidth=0,myHeight=0;if(typeof(window.innerWidth)=='number'){myWidth=window.innerWidth;myHeight=window.innerHeight;}
else if(document.documentElement&&(document.documentElement.clientWidth||document.documentElement.clientHeight)){myWidth=document.documentElement.clientWidth;myHeight=document.documentElement.clientHeight;}
else if(document.body&&(document.body.clientWidth||document.body.clientHeight)){myWidth=document.body.clientWidth;myHeight=document.body.clientHeight;}
return{height:myHeight,width:myWidth};}
function getScrollOffset(){var scrOfX=0,scrOfY=0;if(typeof(window.pageYOffset)=='number'){scrOfY=window.pageYOffset;scrOfX=window.pageXOffset;}
else if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){scrOfY=document.body.scrollTop;scrOfX=document.body.scrollLeft;}
else if(document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)){scrOfY=document.documentElement.scrollTop;scrOfX=document.documentElement.scrollLeft;}
return{left:scrOfX,top:scrOfY};}
function getOnScreenTop(el){var viewSize=getViewSize().height;var previewHeight=el.offsetHeight;var originalTop=arguments[1]?arguments[1]:getAbsPos(el,'Top');var overFlow=(originalTop+previewHeight)-viewSize;var newTop=(overFlow>0)?(originalTop-overFlow):originalTop;if(newTop<0){newTop=getScrollOffset().top;}
return newTop;}
function centerOnScreen(el){var scroll=getScrollOffset();var dimensions=getViewSize();var elWidth=el.offsetWidth;var elHeight=el.offsetHeight;var x_midpoint=dimensions.width/2;var x_adjust=elWidth/2;var y_midpoint=(dimensions.height/2)+scroll.top;var y_adjust=elHeight/2+100;el.style.left=(x_midpoint-x_adjust)+'px';el.style.top=(y_midpoint-y_adjust)+'px';}
function buildTablesAndForms(){for(var label in JSGI.pageElements){JSGI.pageElements[label].build();}
if(typeof firstFound!='undefined'){setFocus(firstFound);}}
function parseFunctionName(func){var text=func.toString();return text.slice(0,text.indexOf('(')).replace('function ','');}
function clearForm(evt){try{var target=JSGI.getEventTarget(evt);var formElements=target.form.elements;}
catch(e){var evt=(evt)?evt:((event)?event:null);var target=(evt.target)?evt.target:((evt.srcElement)?evt.srcElement:null);var formElements=target.form.elements;}
jQuery(formElements).each(function(){try{if(isTextArea(item)||isTextbox(item)){item.value="";}}
catch(e){warn(e);}});}
function setFocus(node){if(node&&node.id){(jQuery.browser.msie)?window.setTimeout("try { document.getElementById('"+node.id+"').focus(); } catch(e) { error(e); }",1):node.focus();}}
function map(set,fn){for(var i=0,len=set.length;i<len;i++){fn.apply(arguments[2],[set[i]]);}}
function mapWithHost(set,host,fn){for(var i=0,len=set.length;i<len;i++){fn.apply(null,[set[i],host]);}}
function mapKeys(set,fn){for(var i=0,len=set.length;i<len;i++){fn.apply(arguments[2],[i]);}}
function asyncMap(set,fn,frequency){var q=new AsyncQueue(fn,frequency,arguments[3]);for(var i=0,len=set.length;i<len;i++){q.send(set[i]);}
q.end();}
function mapHash(set,fn){for(var i in set){fn.apply(arguments[2],[i,set[i]]);}}
function clone(orig){if(typeof orig!='object'||orig==null){return orig;}
var copy={};for(var i in orig){copy[i]=clone(orig[i]);}
return copy;}
function cloneArray(orig){var copy=[];for(var i=0,len=orig.length;i<len;i++){copy[i]=orig[i];}
return copy;}
function doNothing(){}
function warn(){}
function error(){}
var Profiler={timers:{},start:function(label){this.timers[label]={};this.timers[label].accumulates=false;this.timers[label].start=new Date().getTime();},accumulate:function(label){if(typeof this.timers[label]=='undefined'){this.timers[label]={};}
var timer=this.timers[label];timer.accumulates=true;if(typeof timer.iterations=='undefined'){timer.iterations=[];}
timer.latest={start:new Date().getTime()};},swap:function(stopLabel,startLabel){this.stop(stopLabel);this.start(startLabel);},stop:function(label){var timer=this.timers[label];if(timer.accumulates){timer.latest.stop=new Date().getTime();timer.iterations.push({start:timer.latest.start,stop:timer.latest.stop});}
else{timer.stop=new Date().getTime();}},summarize:function(){for(var label in this.timers){var timer=this.timers[label];if(timer.accumulates){var sum=0;var minimum=2000000000000;var maximum=0;for(var i=0,len=timer.iterations.length;i<len;i++){var iter=timer.iterations[i];var diff=iter.stop-iter.start;if(diff>maximum){maximum=diff;}
if(diff<minimum){minimum=diff;}
sum+=diff;}}
else{var diff=timer.stop-timer.start;}}},reset:function(){this.timers={};}};var setFieldValue=function(el,val){if(typeof el=='string'){el=document.getElementById(el);}
if(isTextbox(el)||isTextArea(el)){el.value=val;}
else if(isDropdown(el)){$(el).children('option[value='+val+']').attr('selected','selected');}
else if(isCheckbox(el)&&typeof val=='boolean'){el.checked=val;}
else if(isRadioButton(el)){el.checked=(el.value==val);}
else if(el.type=='submit'&&el.disabled==true){el.disabled=false;}};var applyTo=function(obj,config){if(obj&&config&&typeof config=='object'){for(var i in config){obj[i]=config[i];}}
return obj;};var applyIf=function(obj,config){if(obj&&config){for(var i in config){if(typeof obj[i]=="undefined"){obj[i]=config[i];}}}
return obj;};var ID=function(id){return document.getElementById(id);};applyTo(Array.prototype,{last:function(){return this[this.length-1];},erase:function(value){var newVersion=[];for(var i=0,len=this.length;i<len;i++){if(this[i]!=value){newVersion.push(this[i]);}}
return newVersion;},keyLookupHash:function(){var lookup={};for(var i=0,len=this.length;i<len;i++){lookup[this[i]]=i;}
return lookup;},merge:function(){var newArray=this;for(var i=0,len=arguments.length;i<len;i++){var arr=arguments[i];for(var i=0,len=arr.length;i<len;i++){newArray.push(arr[i]);}}
return newArray;},each:function(fn,scope){for(var i in this){if(fn.call(scope||this[i],this[i],i,this)===false){return i;}}},inArray:function(val,getIndex,all){var i_arr=[];for(var i in this){if(this[i]===val){if(getIndex===true&&all===true){i_arr.push(parseInt(i));}
else{return(getIndex===true)?parseInt(i):true;}}}
if(all===true){return i_arr;}
return(getIndex===true)?-1:false;},remove:function(val){if(typeof val=='string'){val=[val];}
for(var i=0,len=val.length;i<len;i++){var matches=this.inArray(val[i],true,true);for(var x=(matches.length-1);x>=0;x--){this.splice(matches[x],1);}}
return this;}});applyTo(String.prototype,{trim:function(){return this.replace(/^[\s\u00A0]+|[\s\u00A0]+$/g,'');},ltrim:function(){return this.replace(/^[\s\u00A0]+/g,'');},rtrim:function(){return this.replace(/[\s\u00A0]+$/g,'');},stripHTML:function(){return this.replace(/<(?:.|\s)*?>/g,'');}});String.trim=function(str){return str.replace(/^[\s\u00A0]+|[\s\u00A0]+$/g,'');};var formatMoney=function(val){var num=Math.round(parseFloat(val)*100)/100;return num.toFixed(2);};var isArray=function(o){return o&&typeof o=='object'&&typeof o.length!='undefined';};var hasClass=function(el,cls){return cls&&(' '+el.className+' ').indexOf(' '+cls+' ')!=-1;};var addClass=function(el,cls){if(isArray(cls)){for(var i=0,len=cls.length;i<len;i++){addClass(el,cls[i]);}}
else{if(cls&&!hasClass(el,cls)){el.className=el.className+' '+cls;}}
return el;};var removeClass=function(el,cls){if(!cls||!el.className){return el;}
if(isArray(cls)){for(var i=0,len=cls.length;i<len;i++){removeClass(el,cls[i]);}}
else{if(hasClass(el,cls)){var re=new RegExp('(?:^|\\s+)'+cls+'(?:\\s+|$)',"g");el.className=el.className.replace(re," ");}}
return el;};var replaceClass=function(el,oldCls,newCls){removeClass(el,oldCls);addClass(el,newCls);return el;};var getStyle=function(el,prop){var val;if(typeof el=='string'){el=document.getElementById(el);}
if(el.currentStyle){val=el.currentStyle[prop];}
else if(window.getComputedStyle){val=document.defaultView.getComputedStyle(el,null).getPropertyValue(prop);}
return val;};var addEvent=function(el,eType,fn,useCap){if(useCap==null){useCap=false;}
if(el.addEventListener){el.addEventListener(eType,fn,useCap);return true;}
else if(el.attachEvent){var r=el.attachEvent('on'+eType,fn);return r;}
else{el['on'+eType]=fn;}};var removeEvent=function(el,eType,fn,useCap){if(useCap==null){useCap=false;}
if(el.removeEventListener){el.removeEventListener(eType,fn,useCap);return true;}
else if(el.detachEvent){var r=el.detachEvent('on'+eType,fn);return r;}
else{el['on'+eType]=null;}};var stopEvent=function(e){if(e.stopPropagation){e.stopPropagation();}
else{e.cancelBubble=true;}
if(e.preventDefault){e.preventDefault();}
else{e.returnValue=false;}};function insertAfter(el,node){if(el.nextSibling){el.parentNode.insertBefore(node,el.nextSibling);}
else{el.parentNode.appendChild(node);}}
if(!jQuery.browser.msie){applyTo(Event.prototype,{BACKSPACE:8,TAB:9,RETURN:13,ENTER:13,SHIFT:16,CONTROL:17,ESC:27,SPACE:32,PAGEUP:33,PAGEDOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46,F5:116,isNavKey:function(){var k=this.keyCode;return(k>=33&&k<=40)||k==this.RETURN||k==this.TAB||k==this.ESC;},isSpecialKey:function(){var k=this.keyCode;return(this.type=='keypress'&&this.ctrlKey)||k==9||k==13||k==40||k==27||(k==16)||(k==17)||(k>=18&&k<=20)||(k>=33&&k<=35)||(k>=36&&k<=39)||(k>=44&&k<=45);},hasModifier:function(){return((this.ctrlKey||this.altKey)||this.shiftKey||this.metaKey)?true:false;},getTarget:function(){return this.target||this.srcElement;},getKey:function(){return this.keyCode||this.charCode;},getCharCode:function(){return this.charCode||this.keyCode||0;},getCharString:function(){return String.fromCharCode(this.getCharCode());},getTime:function(){if(!this.timeStamp){var t=new Date().getTime();try{this.timeStamp=t;}
catch(e){return t;}}
return this.timeStamp;},stopPropagation:function(){if(this.stopPropagation){this.stopPropagation();}
else{this.cancelBubble=true;}},preventDefault:function(){if(this.preventDefault){this.preventDefault();}
else{this.returnValue=false;}},stopEvent:function(){this.stopPropagation();this.preventDefault();}});}
var filterKeys=function(e){var k=e.keyCode;var key=e.getCharString();if(e.isNavKey()||k==e.BACKSPACE||k==e.DELETE){return;}
var el=e.getTarget();var maskRe=el.getAttribute('maskre');if(!maskRe){return;}
var re=RegExp(maskRe);if(!re.test(key)){e.stopEvent();}};var createElement=function(type,attr){if(attr&&typeof attr!='object'){return false;}
var el=document.createElement(type);for(var key in attr){var val=attr[key];if(key=='class'||key=='className'||key=='cls'){key=(jQuery.browser.msie)?'className':'class';}
el.setAttribute(key,val);}
return el;};var typeOf=function(o){if(o===null||o===undefined){return false;}
if(o.htmlElement){return'element';}
var t=typeof o;if(t=='object'&&o.nodeName){switch(o.nodeType){case 1:return'element';case 3:return(/\S/).test(o.nodeValue)?'textnode':'whitespace';}}
if(t=='object'||t=='function'){switch(o.constructor){case Array:return'array';case RegExp:return'regexp';}
if(typeof o.length=='number'&&typeof o.item=='function'){return'nodelist';}}
return t;};var emptyFn=function(){};Images={map:{},load:function(map){this.map=map;},set:function(label,file){this.map[label]=file;},url:function(label){return resourcePrefix+this.map[label];},get:function(label){return this.markup(this.map[label]);},markup:function(file){return HTML.image(resourcePrefix+file);}};function addToDOM(root,structure){lastNode=root;for(var i=0,item;item=structure[i];i++){if(typeof item.nodeName!="undefined"){root.appendChild(item);lastNode=item;}
else{addToDOM(lastNode,item);}}}
function isElement(item){return item.nodeType==1;}
function isImage(item){return isElement(item)&&item.nodeName=="IMG";}
function isInput(item){return isElement(item)&&item.nodeName=="INPUT";}
function isSubmitButton(item){return isInput(item)&&item.type=="submit";}
function isButton(item){return item.nodeName=="BUTTON"||isSubmitButton(item)||(isInput(item)&&item.type=="button");}
function isTextbox(item){return isInput(item)&&item.type=="text";}
function isSuggestBox(item){return isTextbox(item)&&item.getAttribute("suggest");}
function isDatebox(item){return isTextbox(item)&&item.getAttribute("date");}
function isTimebox(item){return isInput(item)&&item.getAttribute("time");}
function isTextArea(item){return isElement(item)&&item.nodeName=="TEXTAREA";}
function isTextEntry(item){return isTextbox(item)||isTextArea(item);}
function isCheckbox(item){return isInput(item)&&item.type=="checkbox";}
function isRadioButton(item){return isInput(item)&&item.type=="radio";}
function isChecked(item){return isCheckbox(item)&&item.checked==true;}
function isDropdown(item){return isElement(item)&&item.nodeName=="SELECT";}
function isFormItem(item){return isInput(item)||isTextArea(item)||isDropdown(item);}
function isHidden(item){return isInput(item)&&item.type=="hidden";}
function HTMLLib(){}
HTML={getBody:function(){return document.getElementsByTagName("BODY").item(0);},addToBody:function(item){this.getBody().appendChild(item);},textNode:function(text){return document.createTextNode(text);},tag:function(nodeName){return document.createElement(nodeName);},textBox:function(size){var textbox=this.tag("INPUT");textbox.type="text";textbox.setAttribute("size",size);return textbox;},button:function(value){var button=this.tag("INPUT");button.type="button";button.value=value;return button;},eventButton:function(value,eventId,data){var button=this.tag("INPUT");button.type="button";button.value=value;button.eventId=eventId;if(data){button.dataSet=data;}
return button;},blankButton:function(value){var button=this.tag("BUTTON");button.innerHTML=value;return button;},submit:function(value){var submit=this.tag("INPUT");submit.type="submit";submit.innerHTML=value;return submit;},reset:function(value){var reset=this.tag("INPUT");reset.type="reset";reset.value=value;return reset;},imageButton:function(src){var button=this.tag("INPUT");button.type="image";button.src=resourcePrefix+src;return button;},link:function(content){var link=this.tag("A");link.appendChild(HTML.textNode(content));return link;},div:function(cls,id){var div=this.tag("DIV");if(cls){div.setAttribute((jQuery.browser.msie?'className':'class'),cls);}
if(id){div.setAttribute('id',id);}
return div;},span:function(cls,id){var span=this.tag("SPAN");if(cls){span.className=cls;}
if(id){span.id=id;}
return span;},checkBox:function(state){var check=this.tag("INPUT");check.type="checkbox";if(state=="checked"){check.defaultChecked=true;}
return check;},image:function(src,cls){var image=this.tag("IMG");image.src=src;if(cls){image.setAttribute((jQuery.browser.msie?'className':'class'),cls);}
return image;},table:function(cls){var table=this.tag("TABLE");table.className=cls;table.cellSpacing=0;table.cellPadding=0;return table;},tableHead:function(){return this.tag("THEAD");},tableBody:function(){return this.tag("TBODY");},tableRow:function(){return this.tag("TR");},tableHeadCell:function(){return this.tag("TH");},tableCell:function(){var cell=this.tag('TD');var attr=(jQuery.browser.msie)?'vAlign':'valign';cell.setAttribute(attr,'top');return cell;},formLabel:function(text,itemId){var label=this.tag("LABEL");label.setAttribute("for",itemId);var labelText=this.textNode(text);label.appendChild(labelText);return label;},setWidth:function(item,width){item.style.width=width+"px";},setHeight:function(item,height){item.style.height=height+"px";},setLeft:function(item,left){item.style.left=left+"px";},setTop:function(item,top){item.style.top=top+"px";},replace:function(replacement,current){current.parentNode.replaceChild(replacement,current);},remove:function(node){var node=jQuery(node).get(0);if(node){node.parentNode.removeChild(node);}},fill:function(node,text){node.innerHTML=text;},drawScreen:function(screenId,zIndex){var windowScreen=jQuery("#"+screenId);info(windowScreen);if(windowScreen.noMatches()){info("need screen");windowScreen=jQuery('<div id="'+screenId+'"></div>').addClass("screen").hide().appendTo("body:eq(0)");}
windowScreen.css("zIndex",zIndex).show("fast");},closeScreen:function(screenId){jQuery("#"+screenId).hide("fast");}};var Grid=function(rows,cols,valign){this.numCols=cols;this.numRows=rows;this.cellMap={};this.verticalAlignment=valign||"top";this.ref=this.getFramework();};applyTo(Grid.prototype,{getFramework:function(){var table=HTML.table("grid");var body=HTML.tableBody();var attr=(jQuery.browser.msie)?'vAlign':'valign';for(var i=0,len=this.numRows;i<len;i++){var row=HTML.tableRow();row.setAttribute(attr,this.verticalAlignment);for(var j=0,len2=this.numCols;j<len2;j++){var cell=HTML.tableCell();cell.setAttribute(attr,this.verticalAlignment);this.cellMap[i+"."+j]=cell;row.appendChild(cell);}
body.appendChild(row);}
table.appendChild(body);return table;},setContents:function(row,col,node){var coord=(row-1)+"."+(col-1);this.cellMap[coord].appendChild(node);},getCell:function(row,col){var coord=(row-1)+"."+(col-1);return this.cellMap[coord];},getRef:function(){return this.ref;}});var DefinitionList=function(){this.ref=HTML.tag("DL");};applyTo(DefinitionList.prototype,{addTitle:function(text){var title=HTML.tag("DT");this.ref.appendChild(title);if(text){var node=(typeof text=="string")?HTML.textNode(text):node;title.appendChild(node);}
return title;},addItem:function(text){var item=HTML.tag("DD");this.ref.appendChild(item);if(text){var node=(typeof text=="string")?HTML.textNode(text):node;item.appendChild(node);}
return item;},markup:function(){return this.ref;}});JSGI.fastTable=function(header,data){var table=HTML.table("fast"),thead=HTML.tableHead(),tbody=HTML.tableBody(),thRow=HTML.tableRow();for(var i=0,len=header.length;i<len;i++){var headCell=HTML.tableHeadCell();headCell.appendChild(HTML.textNode(header[i]));thRow.appendChild(headCell);}
for(var i=0,len=data.length;i<len;i++){var row=HTML.tableRow();var dataRow=data[i];for(var j=0,len2=dataRow.length;j<len2;j++){var cell=HTML.tableCell();if(typeof dataRow[j]=="string"){cell.innerHTML=dataRow[j];}
else if(!dataRow[j]){cell.innerHTML="&nbsp;";}
else{cell.appendChild(dataRow[j]);}
row.appendChild(cell);}
tbody.appendChild(row);}
table.appendChild(thead);table.appendChild(tbody);thead.appendChild(thRow);table.style.width="100%";return table;};var TableStructure=function(cls){this.table=HTML.table();if(cls){this.table.className=cls;}
this.thead=HTML.tableHead();this.tbody=HTML.tableBody();this.theadRow=HTML.tableRow();this.table.appendChild(this.thead);this.thead.appendChild(this.theadRow);this.table.appendChild(this.tbody);};applyTo(TableStructure.prototype,{addHeaderCell:function(cell){this.theadRow.appendChild(cell);},newRow:function(){var row=HTML.tableRow();this.tbody.appendChild(row);this.currentRow=row;},addCell:function(cell){this.currentRow.appendChild(cell);}});var PageElementBox=function(){this.rootId=arguments[0]||JSGI.pageElementCounter++;this.buttons=[];this.label="POPUP LABEL";this.content="POPUP CONTENTS";this.formAction=null;};applyTo(PageElementBox.prototype,{setLabel:function(labelText){this.label=labelText;},addButton:function(button){this.buttons.push(button);},setContents:function(html){this.content=html;},setAction:function(action){this.formAction=action;},markup:function(){var box=HTML.div("item_box",this.rootId+".box");this.title=HTML.div("titlebar");var body=HTML.div("boxcontent",this.rootId+".content");var buttonBox=HTML.div("bottom_buttons");var form=HTML.tag("FORM");form.method="post";if(this.formAction){form.action=this.formAction;}
form.id=this.rootId+".form";form.setAttribute("onsubmit","return validateForm('"+form.id+"')");box.appendChild(this.title);this.title.innerHTML="<ul><li><p>"+this.label+"</p></li></ul>";box.appendChild(body);body.appendChild(form);form.innerHTML=this.content;form.appendChild(buttonBox);for(var i=0,len=this.buttons.length;i<len;i++){buttonBox.appendChild(this.buttons[i]);}
return box;}});JSGI.serverRequest=function(serverPage,method,params){this.serverPage=serverPage;this.method=method||"POST";this.params=params||{};};applyTo(JSGI.serverRequest.prototype,{add:function(name,value){this.params[name]=value;return this;},load:function(parms){this.params=parms;return this;},setHandler:function(func){this.jsonHandler=func;return this;},sendRequest:function(){var response=jQuery.ajax({url:this.serverPage,type:this.method,data:this.params,dataType:"json",async:false,success:this.jsonHandler,error:this.jsonErrorHandler});return response;},getJSON:function(func){jQuery.ajax({url:this.serverPage,type:"POST",data:this.params,dataType:"json",async:false,success:func||this.jsonHandler,error:this.jsonErrorHandler});},execute:function(returnJson){var response=this.sendRequest();return(returnJson===true)?eval('('+response.responseText+')'):response.responseText;},setTable:function(table){this.add("table",table);return this;},setJob:function(jobName){this.add("job",jobName);return this;},addUser:function(){this.add("user_id","*userid*");return this;},getDbData:function(){this.getJSON(function(json){warn(json);JSGI.jsonData=new DbData(json);});var dt=JSGI.jsonData;info(dt);return dt||{};},jsonHandler:function(json){info("Please write a json handler.");},jsonErrorHandler:function(json){JSGI.jsonData=null;}});JSGI.DebugConfig={relocations:true,infos:false,debugs:false,warnings:false,errors:false,toolbar:false,analysis:false,label:true,toggle:function(label){this.label=!this.label;(this.label)?document.getElementById('debug-'+label).className='enabled':document.getElementById('debug-'+label).className='';},enabled:function(){return this.label;},enableInfos:function(){this.infos=true;},enableDebugs:function(){this.debugs=true;},enableCritical:function(){this.errors=this.warnings=true;},enableDetails:function(){this.infos=true;},blockRelocation:function(){this.relocations=false;},enableToolbar:function(){this.toolbar=true;},enableAnalysis:function(){this.analysis=true;},showInfos:function(){return this.infos;},showDebugs:function(){return this.debugs;},showWarnings:function(){return this.warnings;},showErrors:function(){return this.errors;},showToolbar:function(){return this.toolbar;},relocationEnabled:function(){return this.relocations;},runAnalysis:function(){return this.analysis;}};if(typeof console=='undefined'){console={log:emptyFn,info:emptyFn,debug:emptyFn,warn:emptyFn,error:emptyFn};}
else{if(!console.info){console.info=function(msg){console.log(msg);};}
if(!console.debug){console.debug=function(msg){console.log(msg);};}
if(!console.warn){console.warn=function(msg){console.log(msg);};}
if(!console.error){console.error=function(msg){console.log(msg);};}}
function info(msg){if(JSGI.DebugConfig.showInfos()&&developing){console.log(msg);}}
function warn(msg){if(JSGI.DebugConfig.showWarnings()&&developing){console.warn(msg);}}
function error(msg){if(JSGI.DebugConfig.showErrors()&&developing){console.log(msg);}}
function debug(msg){if(JSGI.DebugConfig.showDebugs()&&developing){console.info(msg);}}
function loadDebugToolbar(){if(JSGI.DebugConfig.showToolbar()&&developing){var box=HTML.div('debugToolbar','debugToolbar');var list=HTML.tag('DL');var item=HTML.tag('DD');box.appendChild(list);list.style.display='inline';var button=HTML.button('Analyze');button.onclick=function(){ProblemAnalysis.displayMenu();};button.style.fontSize='.7em';box.appendChild(button);var eventWindow=HTML.span();eventWindow.className='eventDebug';box.appendChild(eventWindow);activateLens('eventdebug',eventWindow);HTML.addToBody(box);}}
applyTo(JSGI.click,{closeAnalysis:function(){ProblemAnalysis.removeReport();},debug:function(){JSGI.DebugConfig.toggle(this.target.kind);}});JSGI.SaveStack=function(){var that={},messages=[],fieldMessageLookup={},changes=null,xml='',response={status:0};function extractKey(item){return item.dataSet?item.dataSet.dbdata.getKey(item.getAttribute('dbtable'),item.rowNum):item.getAttribute('dbkeyvalue');}
function extractTableId(item){return item.dataSet?item.dataSet.tableId?item.dataSet.tableId:item.dataSet.formId:item.getAttribute('dbtable');}
function selectOldValue(item){try{var oldValue=item.dataSet.dbdata.getValue(item);}
catch(e){error(e);}
if(isCheckbox(item)){var oldValue='foo';}
return oldValue;}
that.addMessage=function(item){var table=item.getAttribute('dbtable'),field=item.getAttribute('dbfield'),rowNum=item.rowNum,tableid=extractTableId(item),key=extractKey(item),oldValue=selectOldValue(item),newValue=getFormItemValue(item);if(newValue!=oldValue){var message=new SaveMessage(tableid,table,field,rowNum,key,oldValue,newValue);this.groupMessage(message);var stackName=item.stackName?item.stackName:'default';this.toggleSaveButton(stackName);}};that.toggleSaveButton=function(stackName){if(typeof stackName=='undefined'||!stackName||stackName=='default'){var saveButton=document.getElementById('saveButton');if(saveButton){saveButton.src=Images.url('saveActive');}}};that.addSimpleMessage=function(table,field,key,value,row){var message=new SaveMessage('default',table,field,row||0,key,'NULL',value);this.groupMessage(message);};that.promoteMessages=function(){changes=messages;};that.hasMessages=function(){return(messages.length>0);};that.groupMessage=function(message){messages.push(message);if(typeof fieldMessageLookup[message.lookupId]=='undefined'){fieldMessageLookup[message.lookupId]=[];}
fieldMessageLookup[message.lookupId].push(messages.length-1);};that.dumpMessages=function(){return messages;};that.resolveMessages=function(){var changeStack=[],change=[];var x=0;for(var i in fieldMessageLookup){var lookupSet=fieldMessageLookup[i];if(lookupSet.length==1){var lastMessage=messages[lookupSet[0]];var summary=lastMessage;}
else{var originalValue=messages[lookupSet[0]].oldValue;var lastMessage=messages[lookupSet[lookupSet.length-1]];var finalValue=lastMessage.value;var summary=new SaveMessage(lastMessage.tableid,lastMessage.table,lastMessage.field,lastMessage.rowNum,lastMessage.key,originalValue,finalValue);}
var lastChange=(change.length>0)?change[change.length-1]:{};if(change.length>0&&lastChange.rowNum!=lastMessage.rowNum){x++;}
var els=$('*[name='+summary.field+']');var el=(els.length>0)?els[0]:null;if(el&&JSGI.ValidationErrors.invalidField(el)){return JSGI.ValidationErrors.getMessages(el)}
change=changeStack[x]=changeStack[x]||[];change.push(summary);var ensured={};for(var j=0,clen=change.length;j<clen;j++){var message=change[j];var dataSet=JSGI.pageElements[message.table];if(dataSet&&dataSet.setType){var fieldSet=(dataSet.setType=='table')?dataSet.rowSaveFields:dataSet.defaultFields;}
if(dataSet&&fieldSet){for(var k=0,flen=fieldSet.length;k<flen;k++){var field=fieldSet[k];if(ensured[lastMessage.rowNum+field]){continue;}
var liveValue=dataSet.dbdata.findValue(lastMessage.rowNum,field);var fieldMessage=new SaveMessage(lastMessage.tableid,lastMessage.table,field,lastMessage.rowNum,lastMessage.key,'',liveValue);ensured[lastMessage.rowNum+field]=true;change.push(fieldMessage);}}}}
if(changeStack){changes=changeStack;}};function extendTree(tree,message){}
that.buildTree=function(){var tree={};tree.tables={};for(var i=0,clen=changes.length;i<clen;i++){var record={},table;var messages=changes[i];for(var j=0,mlen=messages.length;j<mlen;j++){var message=messages[j];var key=message.key;var storeKey=(key=='_NEW_')?key+':'+(message.rowNum||0):key;if(typeof tree.tables[message.table]=='undefined'){table=tree.tables[message.table]={};}
if(typeof tree.tables[message.table].records=='undefined'){tree.tables[message.table].records=[];}
if(key=='_NEW_'||key==''||key==0){record.action='insert';}
else{if(message.value=='delete'){record.action='delete'}
else if(record.action!='delete'){record.action='update';}}
if(typeof record.data=='undefined'){record.data={};}
record.data[message.field]={};record.data[message.field].oldValue=message.oldValue;record.data[message.field].newValue=message.value;record.keyGroup=message.rowNum;record.key=key;}
table.records.push(record);}
this.tree=tree;};that.resolveSaveDefaults=function(){if(typeof saveDefaults!='undefined'){for(var table in this.tree.tables){if(typeof saveDefaults[table]=='undefined'){continue;}
var staticValues=saveDefaults[table];for(var i=0,len=this.tree.tables[table].records.length;i<len;i++){for(var field in staticValues){var record=this.tree.tables[table].records[i];record.data[field]={};record.data[field].oldValue=staticValues[field];record.data[field].newValue=staticValues[field];}}}}};that.serializeRequest=function(){var isDelete=(arguments[0])?1:0;if(this.tree.tables==null){return false;}
if(typeof dbmlRequestType=='undefined'){dbmlRequestType='std';}
var actions=[];for(var table in this.tree.tables){var currTable=this.tree.tables[table];for(var i=0,len=currTable.records.length;i<len;i++){var record=currTable.records[i];var keyString=record.key;var messages=JSGI.ValidationErrors.invalidRecord(table,keyString);if(this.displayValidationErrors(messages,isDelete)){continue;}
actions.push('<record table="'+table+'" action="'+record.action+'" tableid="'+table+'">');actions.push(this.serializeKey(table,keyString,record));actions.push(this.serializeFields(record.data));actions.push('</record>');delete currTable.records[i];}}
if(actions.length>0){xml=[];xml.push('<request type="'+dbmlRequestType+'">');xml.push(actions.join("\n"));xml.push('</request>\n');xml=xml.join('\n');return true;}
else{xml="";return false;}};that.serializeKey=function(table,keyString,record){var xml=[];var keyField=keyFieldPattern.replace("|tableName|",table);var keyValue=(record.action=='insert')?'_NEW_':keyString;var gidString=(record.keyGroup!=null)?' groupid="'+record.keyGroup+'" ':'';xml.push('<key name="'+keyField+'"'+gidString+' value="'+keyValue+'" />');return xml.join('\n');};that.serializeFields=function(dataSet){var xml=[];for(field in dataSet){var value=dataSet[field].newValue;var oldValue=dataSet[field].oldValue;xml.push('<field name="'+field+'"><![CDATA['+value+']]></field>');}
return xml.join('\n');};that.displayValidationErrors=function(messages,isDelete){if(messages.length>0&&!isDelete){postValidationInfo('Some of your changes could not be saved because of the following errors:');for(var i=0,len=messages.length;i<len;i++){if(messages[i]){postValidationMessage(messages[i]);}}
return true;}
return false;};function setResponse(jsonData,status){response=jsonData;}
function responseError(xhr,status){info('sendRequest error');info(arguments);}
that.sendRequest=function(){if(xml){jQuery.ajax({url:saveDataLocation,type:'POST',data:xml,contentType:'text/xml',dataType:'json',async:false,success:setResponse,error:responseError});}};that.getResponseStatus=function(){return(response.status==1);};that.manageResponse=function(){switch(response.status){case 1:postSuccessMessage(response.message);break;case 2:postInfoMessage(response.debug);break;case 0:postFailureMessage(response.message,response.debug);break;}
if(response.status==1&&typeof postSaveUrl!='undefined'&&JSGI.DebugConfig.relocationEnabled()){postInfoMessage('Please wait ...');window.setTimeout("window.location.href='"+postSaveUrl+"';",3000);return;}
if(response.status==1&&response.keys){var keyName=response.key;for(var setId in response.keys){if(!setId||!JSGI.pageElements[setId]){continue;}
var dataSet=JSGI.pageElements[setId];if(dataSet.setType=='form'){continue;}
var keySet=response.keys[setId];for(var j in keySet){var rowNum=parseInt(j,10);if(isNaN(rowNum)){continue;}
if(dataSet.setType=='table'){dataSet.setRowNum(j);dataSet.currentRow().reset();}
if(dataSet.addedRows&&dataSet.addedRows[rowNum]==1){dataSet.addedRows[rowNum]=0;}
var key=keySet[rowNum];for(var k in dataSet.dbdata.header){var headerFieldName=dataSet.dbdata.header[k];if(keyName==headerFieldName){var keyColNum=k;break;}}
dataSet.dbdata.body[rowNum][keyColNum]=key;for(var i=0,len=dataSet.dbdata.body[rowNum].length;i<len;i++){if(dataSet.dbdata.body[rowNum][i]=='_NEW_'){dataSet.dbdata.body[rowNum][i]='';}}}
if(dataSet.setType=='table'){dataSet.fillTable();dataSet.updateNavigation();}
else{dataSet.fillForm();}}}};that.cleanup=function(){xml='';this.tree=null;if(response.status==1){messages=[];fieldMessageLookup={};changes=null;}
response={status:0};allowSaves=true;var saveButton=document.getElementById('saveButton');if(saveButton){saveButton.src=Images.url('save');}};return that;};JSGI.saveStacks=function(){var that={},stacks={};function init(name){if(!stacks[name]){stacks[name]=JSGI.SaveStack();}}
init('default');that.addMessage=function(item){var stackName=item.stackName?item.stackName:'default';this.getStack(stackName).addMessage(item);};that.getStack=function(stackName){init(stackName);return stacks[stackName];};return that;}();function SaveMessage(tableid,table,field,rowNum,key,oldValue,newValue){this.tableid=tableid;this.table=table;this.field=field;this.value=newValue?newValue:"";this.key=key;this.rowNum=rowNum;this.oldValue=oldValue;this.lookupId=table+':'+field+':'+rowNum;}
SaveMessage.prototype.setPriority=function(priority){this.priority=priority}
applyTo(JSGI,{setSaveStack:function(item){var stackName=arguments[1]||"default";},removeDefaultText:function(evt){var target=JSGI.getEventTarget(evt);if(target.value!=null&&target.getAttribute("defaultvalue")!=null&&target.value==target.getAttribute("defaultvalue")){target.value="";target.style.color="black";}},restoreDefaultText:function(evt){var target=JSGI.getEventTarget(evt);if(isTextbox(target)&&target.getAttribute("defaultvalue")&&target.getAttribute("defaultvalue")!="_NEW_"&&target.value==""){target.value=target.getAttribute("defaultvalue");target.style.color="gray";}},markDirty:function(evt){var target=JSGI.getEventTarget(evt);if(isCheckbox(target)||isTextbox(target)){if(isCheckbox(target)){var checkVal=(isChecked(target))?target.getAttribute('truevalue'):target.getAttribute('falsevalue');target.setAttribute('value',checkVal);}
updateData(999,target);}
if(isDropdown(target)){JSGI.validateField(33,target);updateData(999,target);}}});applyTo(JSGI.click,{saveClick:function(){if(typeof allowSaves=="undefined"||allowSaves){pluckForm();}},instantCheckbox:function(){var table=this.target.getAttribute("table");var field=this.target.getAttribute("field");var key=this.target.getAttribute("keyvalue");var value=(this.target.checked)?"1":"0";JSGI.CRUD.update(table,field,key,value);},submitWithoutValidation:function(){var reqEls=$(this.target.form).find('*[required=1]');reqEls.each(function(i,el){el.setAttribute('required','0');});},clearCurrentForm:function(){var els=this.target.form.elements;for(var i=0,len=els.length;i<len;i++){var el=els[i];try{setFieldValue(el,'');if(!isValid(el)){markValid(el);}
if(JSGI.ValidationErrors.invalidField(el)){JSGI.validateField(null,el);}}
catch(e){warn(e);}}},resetCurrentForm:function(){var els=this.target.form.elements;for(var i=0,len=els.length;i<len;i++){var el=els[i];if(isTextbox(el)||isTextArea(el)||isDropdown(el)){if(!isValid(el)){markValid(el);}}};}});applyTo(JSGI.CRUD,{create:function(table,data){info(arguments);var stack=JSGI.SaveStack();stack.requestPage=saveDataLocation;for(var name in data){stack.addSimpleMessage(table,name,"_NEW_",data[name]);}
stack.promoteMessages();stack.buildTree();stack.serializeRequest();stack.sendRequest();return stack.getResponseStatus();},update:function(table,field,key,value){var stack=JSGI.SaveStack();stack.requestPage=saveDataLocation;stack.addSimpleMessage(table,field,key,value);stack.promoteMessages();stack.buildTree();stack.serializeRequest();stack.sendRequest();return stack.getResponseStatus();},spoof:function(table,fields){var req=JSGI.ajaxRequest(table);req.setJob("spoof");var data=req.getDbData();info(data);},destroy:function(table,key){var stack=JSGI.SaveStack();stack.requestPage=saveDataLocation;stack.addSimpleMessage(table,"delete",key,"delete");stack.promoteMessages();stack.buildTree();stack.serializeRequest();stack.sendRequest();return stack.getResponseStatus();}});function createHiddenForSubmit(e)
{var el=e.target||e.srcElement;var form=el.form;var hidID=form.id+'_hiddenSubmit';var hidEl=ID(hidID);if(hidEl){hidEl.disabled=false;}
else{hidEl=createElement('input',{type:'hidden',id:hidID,name:el.getAttribute('name'),value:el.getAttribute('value')});form.appendChild(hidEl);}}
function disableSubmit(form){$(form).find('input[type=submit]').each(function(i,el){el.disabled=true;});}
function enableSubmit(form){if(form){var hiddenSubmit=$('input[type=hidden][id='+form.id+'_hiddenSubmit]').get(0);if(hiddenSubmit){hiddenSubmit.disabled=true;}
$(form).find('input[type=submit]').each(function(i,el){el.disabled=false;});}}
function processChange(item){JSGI.checkForAjax(item);if(item.nodeType!=1||(item.nodeType==1&&!item.getAttribute("dbtable"))){return;}
JSGI.saveStacks.addMessage(item);if(item.dataSet&&item.dataSet.setType=="table"){item.dataSet.setRowNum(item.rowNum);if(item.dataSet.currentRow().isBuilt()){item.dataSet.currentRow().reset();}
item.dataSet.filterCache=null;var pattern=item.dataSet.dbdata.renderPattern(item.rowNum,item.dataSet.column(item.colNum).get("sortPattern"));if(!item.dataSet.sortCache){item.dataSet.buildSortCache();}
item.dataSet.sortCache[item.colNum][item.rowNum]=pattern;}}
function updateData(Key,target){var form=target.form;var formid=(form)?form.getAttribute('id'):null;if(form&&formid&&formid.match(/searchbar/i)){return;}
if(target.getAttribute('ignoresave')){return;}
if(isTextbox(target)&&target.getAttribute("format_map")){var formatted=formatValue(target);target.value=formatted;}
if(isTextbox(target)||isDropdown(target)||isTextArea(target)){if(target.value.match('"')){postInfoMessage("Double Quote characters are not permitted.");target.value=target.value.replace('"','');return true;}
if(target.value.match(/\\/)){postInfoMessage("Backslash characters are not permitted.");target.value=target.value.replace(/\\/g,'');return true;}
if(isDropdown(target)&&Key!=9&&Key!=13){processChange(target);}
if(!isDropdown(target)&&Key!=9&&Key!=13&&Key!=37&&Key!=38&&Key!=39&&Key!=40&&target.rowNum!=null){processChange(target);}
if((target.dataSet)&&target.getAttribute("dbfield")){target.dataSet.dbdata.setValue(target);}}
if(isCheckbox(target)&&target.dataSet){var rowNum=target.rowNum;try{target.dataSet.setRowNum(rowNum);}
catch(e){}
if(target.dataSet.dbdata.findValue(rowNum,"checked")){var newCheck=(isChecked(target))?1:0;var checkField=target.dataSet.dbdata.getFieldNum("checked");debug("Check box:"+target.dataSet.dbdata.findValue(rowNum,"checked")+" vs. "+newCheck);}
else{var newCheck=(isChecked(target))?target.getAttribute("truevalue"):target.getAttribute("falsevalue");var checkField=target.dataSet.dbdata.getFieldNum(target.getAttribute("dbfield"));debug("Check box:"+target.dataSet.dbdata.findValue(rowNum,target.getAttribute("dbfield"))+" vs. "+newCheck);}
target.dataSet.dbdata.body[rowNum][checkField]=newCheck;processChange(target,true);}}
function pluckForm(){var stackName=arguments[0]||"default";if(typeof globalSaveOverride!="undefined"&&globalSaveOverride){document.forms[0].submit();return;}
if(typeof lastFocused!="undefined"){updateData(999,lastFocused);try{lastFocused.dataSet.setRowNum(lastFocused.rowNum);lastFocused.dataSet.redrawRow();}
catch(e){warn(e);}}
var stack=JSGI.saveStacks.getStack(stackName);if(!stack.hasMessages()){postInfoMessage("No Changes to Save.");return;}
allowSaves=false;stack.requestPage=saveDataLocation;if(checkRequiredElements()){var msg=stack.resolveMessages();if(msg){postValidationMessage(msg);}
else{stack.buildTree();stack.resolveSaveDefaults();stack.serializeRequest();stack.sendRequest();stack.manageResponse();}}
else{postValidationMessage('Please fill in all required fields.');}
stack.cleanup();return false;}
function checkRequiredElements(){var allOK=true;var els=$('input[required=1], select[required=1], textarea[required=1]');for(var i=0,len=els.length;i<len;i++){if(!checkRequiredElement(els[i])){allOK=false;}}
return allOK;}
function getFormItemValue(item){if(!isFormItem(item)){return;}
else if(isTextEntry(item)){return item.value;}
else if(isCheckbox(item)||isRadioButton(item)){if(jQuery.browser.msie&&item.getAttribute("auto")){return(item.defaultChecked)?item.getAttribute("truevalue"):item.getAttribute("falsevalue");}
return(item.checked)?item.getAttribute("truevalue"):item.getAttribute("falsevalue");}
else if(isDropdown(item)){return(item.selectedIndex<0)?"":item.options[item.selectedIndex].value;}}
function setFormItemValue(item,value){if(isTextEntry(item)){item.value=value;}
else if(isDropdown(item)){for(var i=0,len=item.options.length;i<len;i++){if(options[i].value==value){item.selectedIndex=i;}}}}
function getFormItemDisplayText(item){if(isTextEntry(item)){return item.value;}
else if(isDropdown(item)){return item.options[item.selectedIndex].text;}}
function loadDateBoxes(){var inputs=document.getElementsByTagName("INPUT");for(var i=0,len=inputs.length;i<len;i++){var child=inputs[i];if(isDatebox(child)&&!child.calendarBuilt){var dbtable=child.getAttribute("dbtable");var dbfield=child.getAttribute("dbfield");if(!dbtable||!dbfield){child.setAttribute("dbtable","generic");child.setAttribute("dbfield","date");}
else{var t=child.getAttribute("dbtable");var f=child.getAttribute("dbfield");if(checkValidationMap(dbtable,dbfield,checkDate)){ValidationMap.register(t,f,checkDate);}}
if(!child.id){child.id="datebox"+i;}
var calImage=HTML.image("../artwork/calendar.png");calImage.eventId='calendar';calImage.setAttribute("align","absmiddle");calImage.setAttribute("refboxid",child.id);calImage.title="Use this calendar to select a date.";if(child.nextSibling){child.parentNode.insertBefore(calImage,child.nextSibling);}
else{child.parentNode.appendChild(calImage);}}}}
function formatValue(item){var sections=item.getAttribute("format_map").split('@');var characters=stripFormatting(item.getAttribute("format_map"),item.value);var output=[];for(var i=0,len=sections.length;i<len;i++){var section=sections[i];var wildcards=section.match(/\*/g).length;if(characters.length<=wildcards&&sections.length>1&&i<(len-1)){output.push(characters.join(""));return output.join("");}
for(var j=0;j<wildcards;j++){section=section.replace('*',characters.shift());}
output.push(section);}
return output.join("");}
function stripFormatting(format,value){var added_characters=format.replace(/\*|\@/g,'').split('');for(var i=0,len=added_characters.length;i<len;i++){value=value.replace(new RegExp('\\'+added_characters[i],'g'),'');}
return value.split('');}
function postSuccessMessage(message){postUserMessage('successMessage',message,2000);}
function postValidationInfo(message){postUserMessage('infoMessage',message,8000);}
function postValidationMessage(message){postUserMessage('errorMessage',message,10000);}
function postInfoMessage(message){postUserMessage('infoMessage',message,4000);}
function postFailureMessage(message,debug){postUserMessage('errorMessage',message,0,true);}
function postDismissableNotification(message){postUserMessage('infoMessage',message,0,true);}
function postErrorMessage(message){postUserMessage('errorMessage',message,5000);}
function postUserMessage(messageClass,message,duration,dismiss){if(dismiss){duration=0;}
var msgRibbon=$('div.messageRibbon').get(0);if(msgRibbon&&msgRibbon.innerHTML.match(message)){return;}
var messages=document.getElementById('messages');if(!messages){messages=HTML.div('message_box','messages');HTML.addToBody(messages);}
if(!message||!messageClass){return;}
var rect=$("<div class='messageRibbon'></div>").appendTo(messages).addClass(messageClass).html(message).attr('id','message'+JSGI.messageCounter).hide().fadeTo(0,0.8).slideDown('fast');if(dismiss){rect.append($("<div style='text-align: center;'><button>Try again</button></div>").click(function(event){rect.slideUp('fast',function(){rect.remove();});}));}
if(duration>0){window.setTimeout("clearUserMessage('message"+JSGI.messageCounter+"');",duration);}
JSGI.messageCounter++;}
function showDetails(messageNum){jQuery('#detail'+messageNum).show();}
function manualMessageClose(messageNum){jQuery('#message'+messageNum).remove();}
function clickMessage(){}
function clearUserMessage(messageId){var msg=$('#'+messageId);msg.slideUp('fast',function(){msg.remove();});}
function AsyncQueue(action,frequency,obj){this.obj=obj;this.fn=action;this.stack=[];this.frequency=frequency;this.itervalRef=null;}
applyTo(AsyncQueue.prototype,{setCleanup:function(cleanUpFn,host){this.cleanUp=cleanUpFn;this.cleanUpHost=host;},send:function(){this.stack.push(arguments);if(!this.intervalRef){this.intervalRef=window.setInterval(runAsyncQueue,this.frequency,this);}},end:function(){this.stack.push("ASYNC_TERM");}});var runAsyncQueue=function(queueObj){var firstValue=queueObj.stack.shift();if(firstValue){if(firstValue=="ASYNC_TERM"){window.clearInterval(queueObj.intervalRef);queueObj.intervalRef=null;if(queueObj.cleanUp){queueObj.cleanUp.apply(queueObj.cleanUpHost);}}
else{queueObj.fn.apply(queueObj.obj,firstValue);}}};applyTo(JSGI.click,{usePouchItem:function(){var pouch=lensRef("pouch");var len=this.evtRef.shiftKey?pouch.itemCount(this.target.pouchtype):1;for(var i=0;i<len;i++){info("We're going to unpouch something");var item=pouch.grabFirst(this.target.pouchtype);info(item.unpouch);item.unpouch(this.target);}},pouch:function(){var pouch=(lensActive("pouch"))?lensRef("pouch"):new Pouch();pouch.position(this.evtRef);var realItem=this.target.pouchRef?this.target.pouchRef:this.target;if(realItem.pouchTransform){realItem=realItem.pouchTransform(realItem);}
realItem.style.display="none";pouch.add(realItem);}});function PouchIcon(pouchReferrer,pouchType){var grab=(arguments[2]=="dark")?Images.get("grabDark"):Images.get("grabLight");grab.eventId="pouch";grab.style.cursor="move";grab.setAttribute("height","15");grab.setAttribute("width","15");grab.pouchRef=pouchReferrer;grab.pouchRef.pouchType=pouchType;return grab;}
function Pouch(evtRef){this.items=[];this.typeMap={};this.pouch=HTML.div("pouch");this.pouch.style.display="none";HTML.addToBody(this.pouch);activateLens("pouch",this);}
applyTo(Pouch.prototype,{add:function(item){item=this.cleanItem(item);if(item.onpouch){item.onpouch();}
if(this.pouch.style.display=="none"){jQuery(this.pouch).show("fast");}
if(!item.pouchtype){return;}
if(!this.typeMap[item.pouchtype]){this.typeMap[item.pouchtype]=[];}
this.typeMap[item.pouchtype].unshift(item);this.items.unshift(item);item.pouch=this;item.style.display="none";this.pouch.appendChild(item);jQuery(item).show("fast");},cleanItem:function(item){item.style.top="";item.style.left="";item.style.margin="";item.style.width="";item.style.height="";item.style.position="";return item;},itemCount:function(){return arguments[0]?this.typeMap[arguments[0]].length:this.items.length;},firstItem:function(){return arguments[0]?this.typeMap[arguments[0]][0]:this.items[0]},typedItem:function(type,num){return this.typeMap[type][num];},grabFirst:function(){var first=this.items.pop();this.typeMap[arguments[0]].pop();if(this.isEmpty()){this.cleanUp();}
return first;},position:function(evtRef){info("Where Am I?");info(evtRef);info(JSGI.getCoordinates(evtRef));jQuery(this.pouch).moveTo(JSGI.getCoordinates(evtRef),10,10);},highlightValid:function(target){info("Marking valid pouch items.");for(var i=0,len=this.itemCount();i<len;i++){var item=this.items[i];info(item);}},clearHightlights:function(target){},validTarget:function(target){if(!target.pouchtype){return false;}
for(var type in this.typeMap){info(type);if(type==target.pouchtype){return true;}}
return false;},cleanUp:function(){deactivateLens("pouch");jQuery(this.pouch).hide("fast");},isEmpty:function(){return this.items.length==0;}});function pickModeLetters(Key,target){if(Picker.active&&((Key>=65&&Key<=90)||Key==JSGI.KEY_BACKSPACE)){if(Picker.typedLetters.value.match(Picker.defaultText))
Picker.typedLetters.value=Picker.typedLetters.value.replace(Picker.defaultText,"");Picker.typedLetters.focus();Picker.update();return false;}}
var Picker={active:false,letterCountCache:{},currentPickValue:null,defaultText:"Find Pages By Name - Type to Begin",show:function(){this.active=true;this.picker=HTML.div("","picker");var tbWrapper=HTML.div("tbWrapper");this.typedLetters=HTML.textBox();this.typedLetters.value=this.defaultText;this.optionList=HTML.tag("select");HTML.addToBody(this.picker);addToDOM(this.picker,[tbWrapper,[this.typedLetters],this.optionList]);this.getLetterCountCache();this.update(1);this.typedLetters.focus();},focus:function(){if(this.active){this.optionList.focus();return false;}
return true;},select:function(){if(this.active){var currOption=getFormItemValue(this.optionList);if(currOption)
window.location.href=currOption;else
window.location.href=this.currentPickValue;return false;}
return true;},getLetterCount:function(string){var letters=string.toLowerCase().split("");var letterHash={};var letterSet=[];for(var i=0,len=letters.length;i<len;i++){var letter=letters[i];if(typeof letterHash[letter]=="undefined"){letterHash[letter]=0;letterSet.push(letter);}
letterHash[letter]+=1;}
return{count:letterHash,list:letterSet};},getLetterCountCache:function(){for(var i=0,len=userMenuOptions.length;i<len;i++){var option=userMenuOptions[i];this.letterCountCache[option.label]={};this.letterCountCache[option.label].action=option.action;this.letterCountCache[option.label].letters=this.getLetterCount(option.label);}},update:function(){var optionList=HTML.tag("select");var searchText=this.typedLetters.value.toUpperCase();var searchLetterCount=this.getLetterCount(searchText);var goal=searchLetterCount.list.length;var strongMatches=[];var weakMatches=[];for(var entry in this.letterCountCache){var matches=0;var itemCache=this.letterCountCache[entry];for(var i=0,len=searchLetterCount.list.length;i<len;i++){var letter=searchLetterCount.list[i];var itemLetter=itemCache.letters.count[letter];var searchLetter=searchLetterCount.count[letter];if(typeof itemLetter=="undefined"||isNaN(itemLetter))
continue;if(itemLetter>=searchLetter)
matches+=1;}
if(matches==goal||arguments[0]==1){var option=HTML.tag("OPTION");option.value=itemCache.action;option.appendChild(HTML.textNode(entry));if(entry.match(new RegExp(searchText,"i")))
strongMatches.push(option);else
weakMatches.push(option);}}
for(var i=0,len=strongMatches.length;i<len;i++){optionList.appendChild(strongMatches[i]);}
for(var i=0,len=weakMatches.length;i<len;i++){optionList.appendChild(weakMatches[i]);}
optionList.size=9;this.optionList.parentNode.replaceChild(optionList,this.optionList);this.optionList=optionList;this.typedLetters.focus();if(this.optionList.options.length>0)
this.currentPickValue=this.optionList.options[0].value;},hide:function(){if(this.active){this.active=false;HTML.remove(this.picker);return false;}
return true;}}
var CalendarWidget={init:function(formItem){this.months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];this.formItem=formItem;this.formItemEl=$('input[id='+formItem+']');this.today=(this.formItemEl.val().length<10)?new Date():new Date(this.formItemEl.val().replace(/\-/g,'/'));this.build();},build:function(){var daysGrid=this.makeGrid();this.attach(daysGrid);},rebuild:function(){this.build();this.positionCal();},getDays:function(month,year){daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];if(1==month){return((0==year%4)&&(0!=(year%100)))||(0==year%400)?29:28;}
else{return daysInMonth[month];}},attach:function(contents){var holder=document.getElementById("dhtml_calendar");if(!holder){var holder=HTML.div();holder.id="dhtml_calendar";holder.style.visibility="hidden";holder.style.position='absolute';holder.style.zIndex="20000";HTML.addToBody(holder);}
holder.innerHTML=contents;},incMonth:function(delta){var currMonth=this.today.getMonth();debug("curr month:"+currMonth);currMonth+=delta;debug("now: "+currMonth);if(currMonth>=12){currMonth=0;this.incYear(1);}
else if(currMonth==-1){currMonth=11;this.incYear(-1);}
var daysInNewMonth=this.getDays(currMonth,this.today.getYear());debug("Days in new Month:"+daysInNewMonth);debug("Curr Date:"+this.today.getDate());if(this.today.getDate()>daysInNewMonth){this.today.setDate(daysInNewMonth);}
this.today.setMonth(currMonth);debug("Curr Date:"+this.today.getDate());this.rebuild();},incYear:function(delta){var currYear=this.today.getFullYear();currYear+=delta;this.today.setYear(currYear);this.rebuild();},makeGrid:function(){var newCal=new Date((this.today.getMonth()+1)+'/01/'+this.today.getFullYear());var startDay=newCal.getDay();var intDaysInMonth=this.getDays(newCal.getMonth(),newCal.getFullYear());var dayOfMonthOfFirstSunday=(7-startDay+1);var month=this.today.getMonth();var year=this.today.getFullYear();var daysGrid='<table class="dhtmlCalendar" cellspacing="0">';daysGrid+=this.header(month,year);daysGrid+='<tbody>';for(var intWeek=0;intWeek<6;intWeek++){daysGrid+='<tr>';var dayOfMonth;for(var intDay=0;intDay<7;intDay++){dayOfMonth=(intWeek*7)+intDay+dayOfMonthOfFirstSunday-7;daysGrid+=(dayOfMonth<=0||dayOfMonth>this.getDays(month,year))?"<td>&nbsp;&nbsp;</td>":this.dayLink(dayOfMonth,month,year);}
daysGrid+='</tr>';}
daysGrid+='</tbody>'
daysGrid+='</table>';return daysGrid;},dayLink:function(dayOfMonth,month,year){var link='';var color=(this.today.getDate()==dayOfMonth&&(month==new Date().getMonth()))?"red":"black";var dispMonth=month+1;var returnMonth=(dispMonth.toString().length==1)?'0'+dispMonth:dispMonth;var returnDay=(dayOfMonth.toString().length==1)?'0'+dayOfMonth:dayOfMonth;var returnString=year+'-'+returnMonth+'-'+returnDay;link+='<td><a href="javascript:setDay(\''+returnString+'\');" ';link+='style="color: '+color+'; background-color: white; text-decoration: none;">'+dayOfMonth+"</a></td>";return link;},header:function(month,year){return'<thead>'+'<tr class="controls">'+'<th colspan="3">'+this.monthControls(month)+'</th>'+'<th colspan="3">'+this.yearControls(year)+'</th>'+'<th><a href="javascript:destroyCalendar()">x</a></th>'+'</tr>'+'<tr class="weekdays"><th>Su</th><th>Mo</th><th>Tu</th><th>We</th><th>Th</th><th>Fr</th><th>Sa</th></tr>'+'</thead>';},monthControls:function(month){return'<a href="javascript:incMonth(-1)" class="arrows">&laquo; </a>'+'<strong>'+this.months[month]+'</strong>'+'<a href="javascript:incMonth(1)" class="arrows"> &raquo;</a>';},yearControls:function(year){return'<a href="javascript:incYear(-1)" class="arrows">&laquo; </a>'+'<strong>'+year+'</strong>'+'<a href="javascript:incYear(1)" class="arrows"> &raquo;</a>';},destroy:function(){jQuery('#dhtml_calendar, #cal_iframe').remove();},setPosition:function(positioner){currLeft=getAbsPos(positioner,"Left");currTop=getAbsPos(positioner,"Top");},positionCal:function(){elt=document.getElementById('dhtml_calendar');elt.style.left=currLeft+"px";elt.style.top=currTop+"px";elt.style.visibility="";if(jQuery.browser.msie&&parseInt(jQuery.browser.version)==6&&!document.getElementById("cal_iframe")){var width=elt.offsetWidth;var height=elt.offsetHeight;var frame=HTML.tag("IFRAME");frame.id="cal_iframe";frame.style.height=height;frame.style.width=width;frame.style.position="absolute";frame.frameBorder=0;frame.style.top=elt.offsetTop;frame.style.left=elt.offsetLeft;frame.style.zIndex=1999;HTML.addToBody(frame);}}};JSGI.click.calendar=function(){var formItemId=this.target.getAttribute("refboxid");CalendarWidget.destroy();CalendarWidget.init(formItemId);CalendarWidget.setPosition(this.target);CalendarWidget.positionCal();};function incMonth(delta){CalendarWidget.incMonth(delta);}
function incYear(delta){CalendarWidget.incYear(delta);}
function setDay(string){var calItem=document.getElementById(CalendarWidget.formItem);calItem.value=string;processChange(calItem);updateData(999,calItem);JSGI.validateField(999,calItem);CalendarWidget.destroy();}
function destroyCalendar(){CalendarWidget.destroy();}
function getAbsPos(elt,which){iPos=0;while(elt!=null){if(which=="Top"){iPos+=elt.offsetTop;}
else{iPos+=elt.offsetLeft;}
elt=elt.offsetParent;}
return iPos;}
function autoFocusAdvance(Key,target){if(target.nodeType==1&&target.nodeName=="INPUT"&&target.getAttribute("absize")&&Key!=JSGI.KEY_TAB){var absoluteLength=target.getAttribute("absize");var currLength=target.value.length;var seq=target.getAttribute("seq");var seqOrder=target.getAttribute("seqord");var sectionName=(target.rowNum)?target.dataSet.tableId+"-"+target.rowNum:"top";if(typeof JSGI.autoTabSequences[sectionName]=="undefined"){JSGI.autoTabSequences[sectionName]={};if(typeof JSGI.autoTabSequences[sectionName][seq]=="undefined"){JSGI.autoTabSequences[sectionName][seq]=[];}
var inputs=document.getElementsByTagName("INPUT");for(var i=0,len=inputs.length;i<len;i++){var input=inputs[i];if(!input.nodeName){continue;}
var currSeq=input.getAttribute("seq");var currSeqOrd=input.getAttribute("seqord");if(input.type=="text"&&currSeq&&currSeq==seq&&currSeqOrd){JSGI.autoTabSequences[sectionName][seq][currSeqOrd]=input;}}}
if(absoluteLength==currLength){var seqSet=JSGI.autoTabSequences[sectionName][seq];var nextItem=parseInt(seqOrder)+1;if(nextItem<seqSet.length){seqSet[nextItem].focus();}}}}
function activateMenu(){if(document.all&&document.getElementById){var navRoot=document.getElementById("systemMenu");for(var i=0,len=navRoot.firstChild.childNodes.length;i<len;i++){var node=navRoot.firstChild.childNodes[i];if(node.nodeName=="LI"){node.onmouseover=function(){jQuery(this).addClass("over");for(var j=0,len2=this.childNodes.length;j<len2;j++){var child=this.childNodes[j];if(child.nodeName=="UL"){var width=child.offsetWidth;var height=child.offsetHeight;var top=getAbsPos(child,"Top");var left=getAbsPos(child,"Left");var frame=document.createElement("IFRAME");frame.id="magic_iframe";frame.style.height=height;frame.style.width=width;frame.style.position="absolute";frame.style.top=top;frame.style.left=left;HTML.addToBody(frame);}}};node.onmouseout=function(){jQuery(this).removeClass("over");jQuery("#magic_iframe").remove();};}}}}
function loadSlidingMenu(){var menu=document.getElementById("sliding_menu");var headingTwos=document.getElementsByTagName("H2");for(var i in headingTwos){var heading=headingTwos[i];heading.eventId="slidingHeader";heading.innerHTML="+ "+heading.innerHTML;}}
function preventDblQuotes(){if(isTextEntry(target)){target.value=target.value.replace('"','');}
return true;}
function FCKeditor_OnComplete(ed){var form=ed.LinkedField.form;if(form.id=='helpForm'){form.onsubmit=function(){saveHelp(helpKey);return false;};}}
var helpKey='';function showhelp(hk){if(isHelpVisible()){hideHelp();return;}
helpKey=hk;if($('#helpLayer').length==0){var helpLayer=HTML.div('help_layer','helpLayer');var helpTitleBar=HTML.div('help_titlebar','helpTitleBar');var helpMain=HTML.div('help_main','helpMain');var helpCloseBox=HTML.image(Images.url('close'),'help_close');helpCloseBox.eventId='hideHelp';HTML.addToBody(helpLayer);helpLayer.appendChild(helpTitleBar);helpLayer.appendChild(helpMain);helpTitleBar.innerHTML='Help';helpTitleBar.appendChild(helpCloseBox);$.post(defaultHelpLocation,{p:hk},function(data){var edit=data.edit;var helpText=data.helpText;if(edit){var helpForm=createElement('form',{name:'helpForm',id:'helpForm',action:defaultHelpLocation,method:'post',submit:'return saveHelp("'+hk+'")'});helpMain.appendChild(helpForm);var helpTA=createElement('textarea',{name:'helpTA',id:'helpTA'});helpForm.appendChild(helpTA);helpTA.value=helpText;var fck=new FCKeditor('helpTA');fck.ToolbarSet='Help';fck.Height='400';fck.ReplaceTextarea();}
else{helpMain.style.padding='5px';helpMain.innerHTML=helpText;}},'json');centerOnScreen(helpLayer);helpLayer.style.visibility='visible';Drag.init(helpTitleBar,helpLayer);if(jQuery.browser.msie&&parseInt(jQuery.browser.version)==6){$('#help_iframe').remove();var frame=createElement('iframe',{cls:'help_iframe',id:'help_iframe'});frame.style.height=helpLayer.offsetHeight;frame.style.width=helpLayer.offsetWidth;frame.style.top=getAbsPos(helpLayer,'Top');frame.style.left=getAbsPos(helpLayer,'Left');frame.frameBorder=0;HTML.addToBody(frame);helpLayer.onDrag=function(x,y){var frame=document.getElementById('help_iframe');var helpLayer=document.getElementById('helpLayer');frame.style.top=getAbsPos(helpLayer,'Top');frame.style.left=getAbsPos(helpLayer,'Left');};}}
else{$('#helpLayer').show();}}
function hideHelp(){$('#help_iframe').hide();$('#helpLayer').hide();}
function isHelpVisible(){var help=$('#helpLayer').get(0);return(help&&(help.style.display!='none'&&help.style.visibility!='hidden'))?true:false;}
function saveHelp(helpKey){var helpText=FCKeditorAPI.GetInstance('helpTA').GetData();$.post(defaultHelpLocation,{p:helpKey,helpText:helpText},function(data){hideHelp();},'text');}
function helpLink(location){var helpFrame=document.getElementById('helpMain');var helpLocation=helpLocationPattern.replace("|helpKey|",location);var req=JSGI.serverRequest(helpLocation);var requestedData=req.execute();if(requestedData){helpFrame.innerHTML=requestedData;}
else{req=JSGI.serverRequest(defaultHelpLocation);helpFrame.innerHTML=req.execute();}}
function resolveFormatGuide(guide){return"<strong>e.g.</strong></br>"+guide.replace(/\^/g,"<br />");}
function showFormatGuide(evt){var target=JSGI.getEventTarget(evt);lastFocused=target;if(typeof target=="undefined"){return;}
if(target.getAttribute("formatguide")){var tip=HTML.div("formatguide");tip.innerHTML=resolveFormatGuide(target.getAttribute("formatguide"));target.parentNode.appendChild(tip);tip.style.position="absolute";tip.style.backgroundColor="white";tip.style.padding="5px;"
tip.style.border="1px solid black";HTML.setWidth(tip,target.offsetWidth);HTML.setTop(tip,getAbsPos(target,"Top")+target.offsetHeight);tip.zIndex="5000";target.formatGuide=tip;target.onblur=hideFormatGuide;}}
function hideFormatGuide(evt){var target=JSGI.getEventTarget(evt);target.parentNode.removeChild(target.formatGuide);}
function backButtonClick(evt){if(JSGI.getEventTarget(evt).getAttribute("action")=="dropPost"){window.location.href=window.location.href;}
else{history.back();}}
function expandSearchForm(tableId){try{document.getElementById(tableId+".boxcontent").style.display="block";jQuery("#"+tableId+".expander").remove();}
catch(e){error(e);}}
function toggleSearchForm(formId){try{var toggle=document.getElementById(formId+".expander");var content=document.getElementById(formId+".content");var state=content.style.display||"none";if(hasClass(content,'collapsed')){replaceClass(content,'collapsed','expanded');toggle.innerHTML="Hide Search";}
else{replaceClass(content,'expanded','collapsed');toggle.innerHTML="Show Search";}}
catch(e){error(e);}}
function urlExists(path){try{var req=JSGI.serverRequest(path);var result=req.execute();return(result.length>0);}
catch(e){return false;}}
function quickRequest(url,params){var req=JSGI.serverRequest(url);for(var name in params){req.add(name,params[name]);}
var result=req.execute();return result;}
function hoverDataTableRow(target){JSGI.hoveredTable=target.dataSet;if(evtRef.shiftKey){target.dataSet.previewRow(target.rowNum,evtRef);}}
applyTo(JSGI.click,{load_boilerplate:function(){document.getElementById('template.default.Subject.0').value=this.target.getAttribute("subject");document.getElementById('template.default.Message.0').value=this.target.getAttribute("message");},selfSubmit:function(){this.target.form.submit();},popupTitleBar:function(){if(this.target.popupSet){lastFocused=this.target;this.target.popupSet.focus();if(jQuery.browser.msie){var popup=this.target.popupSet;var top=getAbsPos(popup.body,"Top");var left=getAbsPos(popup.body,"Left");var frame=document.getElementById("magic_iframe-"+popup.popupId);frame.style.top=top;frame.style.left=left;}}},pageCancel:function(){window.location.href=this.target.destination;},slidingHeader:function(){var list=this.target.nextSibling.nextSibling;if(list.style.display=="block"){list.style.display="none"
this.target.innerHTML=this.target.innerHTML.replace("- ","+ ");}
else{list.style.display="block";this.target.innerHTML=this.target.innerHTML.replace("+ ","- ");}},hideHelp:hideHelp,paymentForm:function(){document.paymentsForm.save_payment.value='true';},refundForm:function(){document.paymentsForm.save_payment.value='true';}});function openSheet(url,argStr){info(argStr);var hash={};var pairs=argStr.split(";;;");info(pairs);for(var i=0,len=pairs.length;i<len;i++){var parts=pairs[i].split(":::");hash[parts[0]]=parts[1];}
info(hash);var sheet=new ModalSheet(url,hash);}
function ModalSheet(url,args){this.url=url;this.args=args;this.generateScreen();this.build();this.retrieve();this.fill();jQuery(this.sheet).slideDown("fast");activateLens("modalsheet",this);this.focus();}
applyTo(ModalSheet.prototype,{generateScreen:function(){HTML.drawScreen("modalscreen",400);},build:function(){this.sheet=HTML.div("modalsheet floater","ModalSheet");this.sheet.style.zIndex=401;HTML.addToBody(this.sheet);},retrieve:function(){var req=JSGI.serverRequest(this.url);for(var n in this.args){req.add(n,this.args[n]);}
this.form=req.execute();},fill:function(){this.sheet.innerHTML=this.form;var scripts=this.sheet.getElementsByTagName("SCRIPT");for(var i=0,len=scripts.length;i<len;i++){var script=scripts[i];try{eval(script.innerHTML);}
catch(e){error(e)}}},spoofEditForm:function(){info("I'm spoofing the buttons.");var buttons=HTML.div("bottom_buttons");var cancel=HTML.button();cancel.value="Cancel";cancel.eventId="dismissSheet";var save=HTML.button();save.value="Save";save.eventId="saveSheetEditForm";buttons.appendChild(cancel);buttons.appendChild(save);this.sheet.appendChild(buttons);},focus:function(){var inputs=this.sheet.getElementsByTagName("INPUT");for(var i=0,len=inputs.length;i<len;i++){var input=inputs[i];if(input.type=="text"){if(!input.id){input.id="sheetFirstResponder";}
window.setTimeout("document.getElementById('"+input.id+"').focus();",500);return;}}},close:function(){jQuery(this.sheet).slideUp("fast");HTML.closeScreen("modalscreen");deactivateLens("modalsheet");}});applyTo(JSGI.click,{openSheet:function(){openSheet(this.target.getAttribute("url"),this.target.getAttribute("attrs"))},dismissSheet:function(){lensRef("modalsheet").close()},saveSheetEditForm:function(){pluckForm();lensRef("modalsheet").close();if(lensActive("monthcalendar")){lensRef("monthcalendar").build();}
if(lensActive("daycalendar")){lensRef("daycalendar").build();}}});function infoWindow(ref,args){args=args||{};info('infoWindow()');debug("Button innerHTML:"+ref.parentNode.innerHTML);var url=ref.getAttribute("url");var tableId=ref.getAttribute("tableid");var popupId=ref.getAttribute("popupid");debug("popupId:"+popupId);var popup=HTML.div("popupForm");popup.className="popupForm immobile";popup.id=popupId;popup.style.width="800px";var mask=HTML.div('mask',popupId+'-mask');var infoRequest=new JSGI.serverRequest(url);for(var i in args){infoRequest.add(i,args[i]);}
var infoWindowIds=infoWindowIds||{};infoWindowIds[tableId]=popupId;var parentTable=parentTable||{};parentTable[popupId]=tableId;infoRequest.add("popupid",popupId);var reqResult=infoRequest.execute();info(reqResult);if(jQuery.browser.msie){HTML.addToBody(mask);HTML.addToBody(popup);popup.innerHTML=reqResult;}
else{popup.innerHTML=reqResult;HTML.addToBody(mask);HTML.addToBody(popup);}
popup.style.top="135px";popup.style.left="50%";popup.style.marginLeft="-400px";var handle=document.getElementById(tableId+".titlebar");var allInputs=document.getElementsByTagName("INPUT");for(var i=0,len=allInputs.length;i<len;i++){var input=allInputs[i];if(input.getAttribute("popupfocus")==1){input.focus();break;}}
info("done building");}
function cancelInfoWindow(tableId){var popupId=infoWindowIds[tableId];var popup=jQuery("#"+popupId+', #'+tableId+"-blank").remove();if(JSGI.pageElements[tableId]){delete JSGI.pageElements[tableId];}}
function popupWindow(ref){var popup=new PageElementBox();if(document.getElementById(popup.rootId+".popup")){return;}
var params=arguments[1];var req=JSGI.serverRequest(ref.getAttribute("url"));if(params){req.load(params);}
popup.setContents(req.execute());content+=req.execute();popup.setLabel(ref.getAttribute("popupLabel"));var cancel=HTML.button("Cancel");cancel.eventId="closePopupDialog";cancel.popupId=popup.rootId;popup.addButton(cancel);popup.addButton(HTML.submit("Save"));var wrapper=HTML.div("popupWindowWrapper",popup.rootId+".popup");wrapper.style.position="absolute";wrapper.style.top="100px";wrapper.style.left="200px";wrapper.style.zIndex="400";wrapper.appendChild(popup.markup());HTML.addToBody(wrapper);Drag.init(popup.title,wrapper);}
applyTo(JSGI.click,{cancelEditWindow:function(){var popupId=this.target.popupId;jQuery("div[id="+popupId+"], div[id="+popupId+"-blank], div[id="+popupId+"-mask]").remove();},saveInfoWindow:function(){info("Submit this form.");var form=(jQuery.browser.msie)?JSGI.util.seekParentForm(this.target):this.target.form;form.submit();},closePopupDialog:function(){jQuery('#'+this.target.popupId+".popup").remove();},tableClose:function(){cancelInfoWindow(this.target.dataSet.tableId);}});JSGI.util.seekParentForm=function(item){while(item=item.parentNode){if(item.nodeName=="FORM"){return item;}}};applyTo(JSGI,{ajaxRequest:function(table){var req=JSGI.serverRequest(ajaxLocation);if(table){req.setTable(table);}
return req;},ajaxJob:function(jobName){var req=JSGI.serverRequest(ajaxLocation);req.setJob(jobName);return req;},checkForAjax:function(input){if(input.getAttribute("ajaxid")&&input.getAttribute("requestid")){info("We's gots ajax.");JSGI.ajaxQuery.load(input,input.getAttribute("ajaxid"));JSGI.ajaxQuery.send();JSGI.ajaxQuery.apply();}}});JSGI.ajaxQuery={requesters:[],receivers:{},ajaxId:null,response:null,load:function(element,ajaxId){info("Loading AJAX");this.ajaxId=ajaxId;this.requesters=[];this.receivers={};var allInputs=document.getElementsByTagName("INPUT");var allDropDowns=document.getElementsByTagName("SELECT");for(var i=0,len=allInputs.length;i<len;i++){var input=allInputs[i];if(input.getAttribute("ajaxid")){if(input.getAttribute("requestid")){this.requesters.push(input);}
else if(input.getAttribute("responseid")){var label=input.getAttribute("responseid");if(typeof this.receivers[label]=="undefined"){this.receivers[label]=[];}
this.receivers[label].push(input);}}}
for(var i=0,len=allDropDowns.length;i<len;i++){var drop=allDropDowns[i];if(drop.getAttribute("ajaxid")){if(drop.getAttribute("requestid")){this.requesters.push(drop);}
else if(drop.getAttribute("responseid")){var label=drop.getAttribute("responseid");if(typeof this.receivers[label]=="undefined"){this.receivers[label]=[];}
this.receivers[label].push(drop);}}}},send:function(){info("Sending ajax request");var request=JSGI.serverRequest(ajaxQueryLocation);request.add("ajaxid",this.ajaxId);for(var i=0,len=this.requesters.length;i<len;i++){var requester=this.requesters[i];request.add(requester.getAttribute("requestid"),getFormItemValue(requester));}
this.response=request.execute();},apply:function(){info("Applying");try{JSGI.parseJSON(this.response);switch(AjaxResponse.status){case 0:error(AjaxResponse.debug);break;case 1:for(var name in AjaxResponse.values){var receiverSet=this.receivers[name];for(var i=0,len=receiverSet.length;i<len;i++){receiverSet[i].value=AjaxResponse.values[name];}}
break;default:warn("Something is wrong!");}}
catch(e){error(e);}}};var seed=0;function generateID(){return'id-gen'+seed++;}
function generateName(){return'name-gen'+seed++;}
function addID(el,id){if(!el.getAttribute('id')){id=id||el.getAttribute('name')||generateID();el.setAttribute(id);}}
function activateCellChildren(cell){var cellChildren=cell.childNodes;var foCounter=0;var childSet=[];for(var i=0,len=cellChildren.length;i<len;i++){childSet.push(cellChildren[i])}
for(var i=0,len=childSet.length;i<len;i++){var child=childSet[i];if(child.nodeName=="FORM"){for(var j=0,len2=child.childNodes.length;j<len2;j++){if(isDatebox(child.childNodes[j])){activateDatebox(child.childNodes[j]);}}}
if(isFormItem(child)||isImage(child)){this.activateChild(child,foCounter);cleanID(child);setDBAttributes(child);if(isSuggestBox(child)){activateSuggestBox(child);}
if(isTextbox(child)){activateTextbox(child);}
if(isDatebox(child)){activateDatebox(child);}
if(isCheckbox(child)){activateCheckbox(child);}
if(isDropdown(child)){activateDropdown(child);}
if(isTimebox(child)){activateTimebox(child);}
if(isTextArea(child)){activateTextarea(child);}
if(isTextbox(child)||isTextArea(child)||isDropdown(child)){checkRequiredColumn(child);}
if(!isButton(child)&&child.getAttribute('validation')){setValidation(child);}
this.loadNewChild(child);foCounter++;}}}
function checkRequiredColumn(el){var splitID=el.id.split('.');if(splitID.length>0){var col=splitID[2];var isRequired=(el.dataSet&&el.dataSet.columns&&!isNaN(parseInt(col))&&el.dataSet.columns[col])?el.dataSet.columns[col].required:false;if(isRequired&&el.getAttribute('required')!='1'){el.setAttribute('required','1');}}}
function cleanID(el){var id=el.getAttribute('id');id=id.replace(/[\(\)\'\"]/g,'');el.setAttribute('id',id);}
function setDBAttributes(el){var dbtable=el.getAttribute('dbtable');var dbfield=el.getAttribute('dbfield');if(!dbtable){var id=el.getAttribute('id');if(!id){id=(el.form)?el.form.getAttribute('id'):generateID();}
var idSplit=id.split('.');var table=idSplit[0];el.setAttribute('dbtable',table);}
if(!dbfield){var name=el.getAttribute('name')||generateName();el.setAttribute('dbfield',name);}}
function setValidation(el){var table=el.getAttribute('dbtable');var field=el.getAttribute('dbfield');var func=el.getAttribute('validation');if(table&&field&&func){ValidationMap.register(table,field,eval(func));}}
function hasIEBorder(el){return($(el).parent('span.ieBorder').get(0))?true:false;}
function activateDropdown(dropdown){var selectedValue=dropdown.getAttribute("selected");for(var i=0,len=dropdown.options.length;i<len;i++){var option=dropdown.options[i];if(option.value==selectedValue){dropdown.selectedIndex=i;}}
if(!dropdown.onchange){dropdown.onchange=JSGI.markDirty;}
if(jQuery.browser.msie){$(dropdown).wrap('<span class="ieBorder"></span>');}}
function activateSuggestBox(el){addID(el);var elName=el.getAttribute('name');var elName_r=elName.replace('_fmtval','');var selectFunc=(el.getAttribute('selectfunc'))?eval(el.getAttribute('selectfunc')):emptyFn;var params={method:el.getAttribute('method')};var elParams=eval('('+el.getAttribute('params')+')');applyTo(params,elParams);$(el).autocomplete(el.getAttribute('url'),{matchSubset:0,minChars:3,cacheLength:10,maxItemsToShow:25,extraParams:params,existingKeyField:elName_r,onItemSelect:function(t,k,li){el.focus();el.blur();selectFunc(t,k,li);},formatItem:function(data,row,num){var output=data[elName_r];var format=el.getAttribute('format');if(format!=null&&output!=null){output=format;var matches=output.match(/\{\w+\}/ig);for(var i=0,len=matches.length;i<len;i++){var m=matches[i];var val=eval(m.replace('{','data.').replace('}',''));output=output.replace(m,val);}}
return output;}});if(el.value){$(document).bind('pageloaded',function(e){var hidEl=$('input[type=hidden][name='+elName_r+']').get(0);if(el.getAttribute('selectfunc')){eval(el.getAttribute('selectfunc')+'(el, hidEl)');}});}
addEvent(el,'blur',function(e){var hidEl=$('input[type=hidden][name='+elName_r+']').get(0);if(!el.value){hidEl.value='';(el.getAttribute('required')=='1')?markInvalid(el):markValid(el);}
else{if(hidEl.value){markValid(el);markValid(hidEl);}
else{markInvalid(el);markInvalid(hidEl);}}});addEvent(el,'keypress',function(e){if(e.keyCode==13){stopEvent(e);}});}
function activateTextbox(textBox){addID(textBox);if(this.setType=="table"){if(this.lastAdded!=null&&this.lastAdded==this.rowNum&&!JSGI.firstNewRowBox){JSGI.firstNewRowBox=textBox;}
if(this.column(this.colNum).numericSort()){textBox.style.textAlign="right";}}
if(textBox.getAttribute("dbtable")!=null){textBox.onchange=JSGI.markDirty;var defaultAttribute=textBox.getAttribute("defaultvalue");if((textBox.value==""||textBox.value==null||textBox.value=="_NEW_")&&defaultAttribute){textBox.value=defaultAttribute;textBox.style.color="gray";textBox.onfocus=JSGI.removeDefaultText;textBox.onblur=JSGI.restoreDefaultText;}}
if(getFormItemValue(textBox)=="_NEW_"){textBox.value="";}
var disabled=textBox.getAttribute('disabled');if(jQuery.browser.msie&&parseInt(jQuery.browser.version)==6&&disabled!==false&&typeof disabled!='undefined'){textBox.style.backgroundColor='#E0E0E0';}
if(!jQuery.browser.msie&&textBox.getAttribute("maskre")){textBox.addEventListener('keypress',filterKeys,false);}
if(textBox.getAttribute("checklength")){addFieldIndicator(textBox);addEvent(textBox,'keyup',checkLength);}}
function activateDatebox(dateBox){var isDateBox=dateBox.getAttribute("date");if(isDateBox){if(!dateBox.id){dateBox.id=dateBox.name;}
dateBox.calendarBuilt=1;var calImage=Images.get("calendar");calImage.eventId='calendar';jQuery(calImage).attr("align","absmiddle").attr("refboxid",dateBox.id).css("cursor","pointer");var dbtable=dateBox.getAttribute("dbtable");var dbfield=dateBox.getAttribute("dbfield");if(dbtable&&dbfield){if(isDateBox=="1"&&checkValidationMap(dbtable,dbfield,checkDate)){ValidationMap.register(dbtable,dbfield,checkDate);}
if(dateBox.getAttribute('compareto')&&checkValidationMap(dbtable,dbfield,compareDate)){ValidationMap.register(dbtable,dbfield,compareDate);}}
else{dateBox.setAttribute("dbtable","generic");dateBox.setAttribute("dbfield","date");}
(dateBox.nextSibling)?dateBox.parentNode.insertBefore(calImage,dateBox.nextSibling):dateBox.parentNode.appendChild(calImage);}}
function activateTimebox(timeBox){timeBox.size=8;var dbtable=timeBox.getAttribute("dbtable");var dbfield=timeBox.getAttribute("dbfield");if(dbtable&&dbfield){ValidationMap.register(dbtable,dbfield,checkTime);}
else{timeBox.setAttribute("dbtable","generic");timeBox.setAttribute("dbfield","time");}
timeBox.onblur=function(e){this.value=formatTime(this.value);updateData(999,this);};}
function activateCheckbox(checkbox){addEvent(checkbox,'click',JSGI.markDirty);addEvent(checkbox,'click',function(e){JSGI.validateField(null,e.target||e.srcElement);});if(checkbox.getAttribute('value').toLowerCase()=='yes'){checkbox.setAttribute('value','1');checkbox.setAttribute('initvalue','1');checkbox.dataSet.dbdata.setValue(checkbox,'1');}
if(checkbox.getAttribute('value').toLowerCase()=='no'){checkbox.setAttribute('value','0');checkbox.setAttribute('initvalue','0');checkbox.dataSet.dbdata.setValue(checkbox,'0');}
var explicitChecked=checkbox.dataSet.dbdata.findValue(checkbox.rowNum,"checked");if(explicitChecked){if(explicitChecked==1){checkbox.defaultChecked=true;checkbox.setAttribute('checked','true');}}
else{var checkField=checkbox.dataSet.dbdata.findValue(checkbox.rowNum,checkbox.getAttribute("dbfield"));var trueValue=checkbox.getAttribute("truevalue");if(checkField&&((trueValue&&checkField==trueValue)||checkField=="true"||checkField=="t"||checkField=="1"||checkField.toLowerCase()=="yes")){checkbox.defaultChecked=true;checkbox.setAttribute('checked','true');}}
var val=(checkbox.defaultChecked==true)?'1':'0';if(!checkbox.getAttribute('value')||checkbox.getAttribute('value')=='on'){checkbox.setAttribute('value',val);}
if(!checkbox.getAttribute('initvalue')){checkbox.setAttribute('initvalue',val);}}
function activateTextarea(textArea){if(getFormItemValue(textArea)=="_NEW_"){textArea.value="";}
if(textArea.getAttribute("checklength")){addFieldIndicator(textArea);textArea.addEventListener('keyup',checkLength,false);}
textArea.onfocus=showFormatGuide;}
function getCurrentValue(field){switch(this.setType){case"table":var head=this.dbdata.header;var row=this.dbdata.body[this.rowNum];break;case"form":var head=this.dbdata.header;var row=this.dbdata.body[0];break;}
var fieldNum=null;for(var i=0,len=head.length;i<len;i++){if(head[i]==field){fieldNum=i;break;}}
if(fieldNum==null){return false;}
return row[fieldNum];}
function setCurrentValue(field,value){switch(this.setType){case"table":var head=this.dbdata.header;var row=this.dbdata.body[this.rowNum];this.rowCache[this.rowNum]=[];break;case"form":var head=this.dbdata.header;var row=this.dbdata.body[0];break;}
var fieldNum=null;for(var i=0,len=head.length;i<len;i++){if(head[i]==field){fieldNum=i;break;}}
row[fieldNum]=value;}
function addFieldIndicator(el){var id=el.getAttribute('id');var maxChars=el.getAttribute('checklength');var indicator=document.createElement('div');indicator.setAttribute('id',id+'_indicator');indicator.setAttribute('style','font-size: 8pt; float: left; padding-right: 5px;');var txt=document.createTextNode(' Max Characters: '+maxChars+' - Count: ');indicator.appendChild(txt);insertAfter(el,indicator);var count=document.createElement('div');count.setAttribute('id',id+'_indicator_count');count.setAttribute('style','font-size: 8pt;');count.innerHTML=el.value.length;insertAfter(indicator,count);}
var ActiveForm=function(formid,label){JSGI.pageElements[formid]=this;JSGI.pageElements[formid].init(formid,label);};applyTo(ActiveForm.prototype,{init:function(formid,label){this.titles=[];this.fields=[];this.tags=[];this.uniqueTags=[];this.tagDisplays={};this.tagLabels={};this.formDefaults={};this.defaultFields=[];this.clearButton=false;this.resetButton=false;this.submitButtonNames=[];this.submitButtonValues=[];this.submitButtonEvents=[];this.hasButtons=false;this.label=label;this.formId=formid;},set:function(name,value,tag){if(name=="tagdisplay"){this.tagDisplays[value]=tag;}
else if(name=="taglabel"){this.tagLabels[value]=tag;}
else if(name=="dbdata"){var data=new DbData(this.formId);data.setHeader(value.header);data.setBody(value.body);this.dbdata=data;}
else{this[name]=value;}},add:function(type,name,value,event){if(type=="submitButton"){this.submitButtonNames.push(name);this.submitButtonValues.push(value);this.submitButtonEvents.push(event);this.hasButtons=true;}
else if(type=="clearButton"){this.clearButton=true;this.hasButtons=true;}
else if(type=="resetButton"){this.resetButton=true;this.hasButtons=true;}
else if(type=="cancelButton"){this.cancelButton=name;}},get:function(name){return this[name];},addRow:function(title,field,tag){this.titles.push(title);this.fields.push(field);this.tags.push(tag);this.tagDisplays[tag]="horizontal";for(var i in this.uniqueTags){if(this.uniqueTags[i]==tag)return;}
this.uniqueTags.push(tag);},addDefault:function(table,field,value){if(typeof saveDefaults=="undefined"){saveDefaults={};}
if(typeof saveDefaults[table]=="undefined"){saveDefaults[table]={};}
saveDefaults[table][field]=value;},addDefaultField:function(field){this.defaultFields.push(field);},build:function(){JSGI.pageElements[this.formId]=this;this.setType="form";var holder=document.getElementById(this.formId+".box");if(this.structure=="complex"){holder.className="item_box";}
var tbar=HTML.div("titlebar");holder.appendChild(tbar);if(this.isComplex()){tbar.innerHTML='<ul><li><p>'+this.label+'</p></li></ul>';var content=HTML.div("boxcontent",this.formId+".content");if(this.collapsible){tbar.parentNode.innerHTML+="<a id=\""+this.formId+".expander\" href=\"javascript:toggleSearchForm('"+this.formId+"');\">Hide Search</a>";}}
else{var content=HTML.div();}
holder.appendChild(content);if(this.dbdata.body.length==0){var emptyRow=[];for(var i=0,leni=this.dbdata.header.length;i<leni;i++){emptyRow.push("");}
this.dbdata.body.push(emptyRow);}
this.box=holder;this.titlebar=tbar;this.content=content;this.rows=[];for(var i=0,leni=this.titles.length;i<leni;i++){this.rows.push([this.titles[i],this.fields[i],this.tags[i]]);}
this.fillForm();},fillForm:function(){this.buttonsAdded=false;this.swapContent();var rowGroups=this.getRowGroups();for(var tagName in rowGroups){this.setTag(tagName);this.getLabelBar(tagName);this.drawContents(tagName,rowGroups[tagName]);}
this.getBottomButtons();if(this.firstPageChild){setFocus(this.firstPageChild);}},drawContents:function(tagName,fieldSet){switch(this.tagDisplays[tagName]){case"horizontal":this.fillHorizontal(fieldSet);break;case"labeled":this.fillLabeled(fieldSet);break;case"vertical":this.fillVertical(fieldSet);break;case"doublevertical":this.fillDoubleVertical(fieldSet);break;}},getRowGroups:function(){var rowGroups={};for(var i=0,leni=this.uniqueTags.length;i<leni;i++){rowGroups[this.uniqueTags[i]]={};}
for(var i=0,leni=this.rows.length;i<leni;i++){var row=this.rows[i];var title=row[0];var field=row[1];var tag=row[2];rowGroups[tag][title]=field;}
return rowGroups;},fillHorizontal:function(fieldSet){var table=HTML.table("horizontal_data_form");var tbody=HTML.tableBody();table.appendChild(tbody);var titleRow=HTML.tableRow();var fieldRow=HTML.tableRow();for(var title in fieldSet){this.setFormRow(title);var titleCell=HTML.tableHeadCell();titleCell.innerHTML=this.isRequiredField(fieldSet[title],title);var fieldCell=HTML.tableCell();fieldCell.innerHTML=this.resolveFormField(fieldSet[title]);this.activateCellChildren(fieldCell);titleRow.appendChild(titleCell);fieldRow.appendChild(fieldCell);}
if(this.drawButtonsOnRight()){var buttonCollection=HTML.tableCell();buttonCollection.rowSpan=2;buttonCollection.style.textAlign="right";buttonCollection.width="40";if(this.clearButton){var clear=HTML.button("Clear");clear.eventId="clearCurrentForm";buttonCollection.appendChild(clear);buttonCollection.appendChild(HTML.tag("BR"));}
if(this.resetButton){var reset=HTML.reset("Reset");reset.eventId="resetCurrentForm";buttonCollection.appendChild(reset);buttonCollection.appendChild(HTML.tag("BR"));}
if(this.submitButtonNames){for(var i=0,len=this.submitButtonNames.length;i<len;i++){var submit=HTML.tag("input");submit.type='submit';submit.name=this.submitButtonNames[i];submit.value=this.submitButtonValues[i];if(this.submitButtonEvents[i]){submit.eventId=this.submitButtonEvents[i];}
addEvent(submit,'click',createHiddenForSubmit);buttonCollection.appendChild(submit);buttonCollection.appendChild(HTML.tag("BR"))}}
titleRow.appendChild(buttonCollection);this.buttonsAdded=true;}
tbody.appendChild(titleRow);tbody.appendChild(fieldRow);this.content.appendChild(table);},fillVertical:function(fieldSet){var table=HTML.table("data_form");tbody=HTML.tableBody();table.appendChild(tbody);for(var title in fieldSet){this.setFormRow(title);var row=HTML.tableRow();var titleCell=HTML.tableHeadCell();titleCell.innerHTML=this.isRequiredField(fieldSet[title],title);var fieldCell=HTML.tableCell();fieldCell.innerHTML=this.resolveFormField(fieldSet[title]);this.activateCellChildren(fieldCell);row.appendChild(titleCell);row.appendChild(fieldCell);tbody.appendChild(row);}
this.content.appendChild(table);},fillDoubleVertical:function(fieldSet){var uberTable=HTML.table();var uberTbody=HTML.tableBody();var uberRow=HTML.tableRow();var leftCell=HTML.tableCell();var rightCell=HTML.tableCell();var leftTable=HTML.table("data_form");var leftTbody=HTML.tableBody();var rightTable=HTML.table("data_form");var rightTbody=HTML.tableBody();uberTable.appendChild(uberTbody);uberTbody.appendChild(uberRow);uberRow.appendChild(leftCell);uberRow.appendChild(rightCell);leftCell.appendChild(leftTable);leftTable.appendChild(leftTbody);rightCell.appendChild(rightTable);rightTable.appendChild(rightTbody);var rowTotal=0;for(var j in fieldSet){rowTotal++;}
var rowCounter=0;if(rowTotal%2==0){var leftLimit=(rowTotal/2)-1;}
else{var remainder=rowTotal%2;var leftLimit=(rowTotal/2)-1+remainder;}
for(var title in fieldSet){this.setFormRow(title);var row=HTML.tableRow();var titleCell=HTML.tableHeadCell();titleCell.innerHTML=this.isRequiredField(fieldSet[title],title);var fieldCell=HTML.tableCell();fieldCell.innerHTML=this.resolveFormField(fieldSet[title]);this.activateCellChildren(fieldCell);row.appendChild(titleCell);row.appendChild(fieldCell);if(rowCounter<=leftLimit){leftTbody.appendChild(row);}
else{rightTbody.appendChild(row);}
rowCounter++;}
this.content.appendChild(uberTable);},fillLabeled:function(fieldSet){var table=HTML.table("label_form");tbody=HTML.tableBody();table.appendChild(tbody);var row=HTML.tableRow();for(var title in fieldSet){this.setFormRow(title);var titleCell=HTML.tableHeadCell();titleCell.innerHTML=this.isRequiredField(fieldSet[title],title);var fieldCell=HTML.tableCell();fieldCell.innerHTML=this.resolveFormField(fieldSet[title]);this.activateCellChildren(fieldCell);row.appendChild(titleCell);row.appendChild(fieldCell);tbody.appendChild(row);this.content.appendChild(table);}},getLabelBar:function(tagName){if(this.tagLabels[tagName]){var labelBar=HTML.div("basic-titlebar");labelBar.innerHTML=this.tagLabels[tagName];this.content.appendChild(labelBar);}},swapContent:function(){var holder=this.box;var newContent=this.isComplex()?HTML.div(this.collapsible?"boxcontent expanded":"boxcontent",this.formId+".content"):HTML.div();var content=this.content;holder.replaceChild(newContent,content);this.content=newContent;},getBottomButtons:function(){if(this.drawButtonsOnBottom()){this.buttonBar=HTML.div("bottom_buttons");this.content.appendChild(this.buttonBar);if(this.clearButton){this.getClearButton();}
if(this.resetButton){this.getResetButton();}
if(this.popupId){this.getPopupCancelButton();}
else if(this.cancelButton){this.getCancelButton();}
else if(this.jscancelButton){this.getJSCancelButton();}
if(this.submitButtonNames){this.getSubmitButtons();}}},getClearButton:function(){var clear=HTML.button("Clear");clear.eventId="clearCurrentForm";this.buttonBar.appendChild(clear);},getResetButton:function(){var reset=HTML.reset("Reset");reset.eventId="resetCurrentForm";this.buttonBar.appendChild(reset);},getPopupCancelButton:function(){var cancel=HTML.button();cancel.value="Cancel";cancel.eventId="cancelEditWindow";cancel.popupId=this.popupId;this.buttonBar.appendChild(cancel);},getCancelButton:function(){var cancel=HTML.button("Cancel");cancel.eventId="pageCancel";cancel.destination=this.cancelButton;this.buttonBar.appendChild(cancel);},getJSCancelButton:function(){var cancel=HTML.button("Cancel");cancel.setAttribute("onclick","window.location.href = '"+this.jscancelButton+"';");this.buttonBar.appendChild(cancel);},getSubmitButtons:function(){for(var i=0,len=this.submitButtonNames.length;i<len;i++){var submit=HTML.tag("input");submit.type='submit';submit.name=this.submitButtonNames[i];submit.value=this.submitButtonValues[i];if(this.submitButtonEvents[i]){submit.eventId=this.submitButtonEvents[i];}
addEvent(submit,'click',createHiddenForSubmit);this.buttonBar.appendChild(submit);}},resolveFormField:function(pattern){var fieldNames=this.dbdata.header;var body=this.dbdata.body[0];var output=pattern;return this.dbdata.renderPattern(0,pattern);},activateChild:function(child,foCounter){child.id=this.formId+"."+this.formTag+"."+this.formRow+"."+foCounter;child.dataSet=this;child.rowNum=0;child.fieldNum=this.dbdata.headerLookup[child.getAttribute("dbfield")];if(!isImage(child)&&this.firstPageChild==null){this.firstPageChild=child;firstFound=child;}},loadNewChild:function(child){if(child.dataSet.dbdata.getKey(child.getAttribute("dbtable"),child.rowNum)=="_NEW_"){processChange(child);}},setTag:function(argTag){this.formTag=argTag;},setFormRow:function(argRow){this.formRow=argRow;},isComplex:function(){return this.structure=="complex";},hasBottomButtons:function(){return this.buttonLocation=="bottom";},hasRightButtons:function(){return this.buttonLocation=="right";},drawButtonsOnRight:function(){return this.isComplex()&&this.hasRightButtons()&&!this.buttonsAdded&&(this.popupId||this.hasButtons);},drawButtonsOnBottom:function(){return this.isComplex()&&this.hasBottomButtons()&&(this.popupId||this.hasButtons);},isRequiredField:function(field,title){return(field.match('required="1"'))?title+'<span style="color: red;">*</span>':title;},activateCellChildren:activateCellChildren,setCurrentValue:setCurrentValue,getCurrentValue:getCurrentValue});var ActiveTable=function(tableId){tableId=tableId||JSGI.pageElementCounter++;JSGI.pageElements[tableId]=this;this.tableId=tableId;this.setType="table";this.columns=[];this.truncationLengths=[];this.filterPattern="";this.rows={};this.popups={};this.formItemSets={};this.rowLimit=4;this.keyField=tableId+"id";this.dbdata=new DbData(this.tableId);this.rowSaveFields=[];this.sortDirection='init';this.nextSortDirection='std';this.startRow=0;this.currentSort=-1;this.sortOrder=[];this.filterSettings=[];this.addedRows={};this.popupRows={};this.currentRows=[];this.incrementalMode=false;this.grabbableRows=false;this.privileges={};this.privileges['add']=false;this.privileges['edit']=false;this.privileges['delete']=false;this.helpActive=false;this.dataPath=null;this.requirements={};this.clearances={};this.filterCache=[];this.sortCache=[];this.allCols=[];this.structure="complex";};applyTo(ActiveTable.prototype,{set:function(name,value){if(name=="dbdata"){var data=new DbData(this.tableId);data.setHeader(value.header);data.setBody(value.body);this.dbdata=data;}
else{this[name]=value;}},add:function(name,value){if(name=="privilege"){this.privileges[value]=true;}},get:function(name){if(this[name]){return this[name];}},hasPriv:function(privName){return this.privileges[privName];},canAdd:function(){return this.hasPriv("add");},canEdit:function(){return this.hasPriv("edit");},canDelete:function(){return this.hasPriv("delete");},addColumn:function(column){this.columns.push(column);this.allCols.push(this.allCols.length);},column:function(colNum){return this.columns[colNum];},numColumns:function(){return this.columns.length;},columnValue:function(propName,colNum){return this.columns[colNum].get(propName);},columnValues:function(propName){var set=[];for(var i=0,len=this.columns.length;i<len;i++){set.push(this.columns[i].get(propName));}
return set;},addRowDefault:function(fieldName){this.rowSaveFields.push(fieldName);},setKeyField:function(keyFieldName){this.keyfield=keyFieldName;},prepare:function(){this.loadDynamicData();this.loadSavedData();this.buildTableStructure();this.setColumnOrder();this.initSortAndFilter();},loadDynamicData:function(){if(this.dbdataPath){var req=JSGI.serverRequest(this.dbdataPath);req.add("source_type","default");if(this.rootTable&&this.sourceTable&&this.linkTable){req.add("root",this.rootTable);req.add("source",this.sourceTable);req.add("link",this.linkTable);if(this.dataDelimiter){req.add("delimiter",this.dataDelimiter);}
if(this.dataJoins){req.add("joins",this.dataJoins);}}
req.getJSON(function(json){JSGI.jsonData=json;});this.dbdata=new DbData(JSGI.jsonData);this.tableId=JSGI.jsonData.table;}},build:function(){this.prepare();if(this.currentSort>-1){this.runSort();}
this.activateNavigation();this.determineWidths();this.fillHeader();this.fillTable();this.updateNavigation();this.triggerPrecache();activateLens("normalView:"+this.tableId,this);},triggerPrecache:function(){this.cacheCounter=0;if(this.dbdata.body.length>0&&JSGI.pageElements[this.tableId]){this.cacheIntervalId=window.setInterval("try { JSGI.pageElements['"+this.tableId+"'].precacheRow() } catch(e){ window.clearInterval("+this.cacheIntervalId+") }",30);}},triggerRecache:function(){this.cacheCounter=0;if(this.dbdata.body.length>0&&JSGI.pageElements[this.tableId]){this.cacheIntervalId=window.setInterval("try { JSGI.pageElements['"+this.tableId+"'].recacheRow() } catch(e){ window.clearInterval("+this.cacheIntervalId+") }",30);}},precacheRow:function(rowNum){this.getRow(rowNum);this.cacheCounter++;if(this.cacheCounter==this.dbdata.body.length){debug("Done pre-loading rows.");window.clearInterval(this.cacheIntervalId);}},recacherow:function(rowNum){this.setRowNum(rowNum);this.currentRow().reset();this.getRow(rowNum);this.cacheCounter++;if(this.cacheCounter==this.dbdata.body.length){debug("Done pre-loading rows.");window.clearInterval(this.cacheIntervalId);}},buildTableStructure:function(){this.table=HTML.table("data_table");this.thead=HTML.tableHead();this.tbody=HTML.tableBody();this.headerRow=HTML.tableRow();info(this.tableId);this.boxContent=document.getElementById(this.tableId+".box");this.boxContent.className="item_box";this.waitMessage=HTML.div("overlay");this.title=HTML.div("titlebar",this.tableId+".titlebar");info(this.title);var list=HTML.tag("ul");var item=HTML.tag("li");var para=HTML.tag("p");this.titlePara=para;addToDOM(this.title,[list,[item,[para]]]);this.titlePara.innerHTML=this.label;this.title.dataSet=this;this.title.eventId="titlebar";this.tableHolder=HTML.div("boxContent",this.tableId+".boxcontent");this.buildScrollBar();var grid=new Grid(1,3);grid.setContents(1,2,this.table);grid.setContents(1,3,this.scrollBar);grid.getCell(1,3).style.width="18px";this.sourceCell=grid.getCell(1,1);this.leftCell=grid.getCell(1,2);this.rightCell=grid.getCell(1,3);this.scrollGrid=grid.getRef();this.scrollGrid.className="scrollGrid";this.sourceCell.className="sourceCell";this.scrollGrid.style.clear="left";if(this.sourceLists){this.sourceCell.style.width=this.sourceLists[0].getWidth()+'px';for(var i=0,len=this.sourceLists.length;i<len;i++){var list=this.sourceLists[i].build();this.sourceCell.appendChild(list);}}
else{this.sourceCell.style.border=0;}
addToDOM(this.table,[this.thead,[this.headerRow],this.tbody]);addToDOM(this.boxContent,[this.title,this.tableHolder,[this.waitMessage,this.scrollGrid]]);},activateNavigation:function(){this.getEditToggles();this.getColumnToggle();this.getNewButton();this.getDeleteButton();this.getPrintButton();this.getFilter();this.getClearButton();this.getCloseButton();},setPopupSettings:function(url,formId,keyField){this.clickUrl=url;this.formId=formId;this.keyField=keyField;},setIsClosable:function(){this.closability=1;},getTitleBarButtonBox:function(){if(this.tbarButtonBox){return this.tbarButtonBox;}
else{var tbarBox=HTML.div("tbarButtons");var tBar=this.getBoxTitleBar();var list=HTML.tag("UL");var listItem=HTML.tag("LI");var para=HTML.tag("P");tBar.appendChild(tbarBox);tbarBox.appendChild(list);list.appendChild(listItem);listItem.appendChild(para);this.tbarButtonBox=para;return para;}},getBoxTitleBar:function(){return jQuery("#"+this.tableId+".titlebar").get(0);},getCloseButton:function(){if(!this.closable){return;}
if(this.closeButton){return this.closeButton;}
else{this.closeButton=Images.get("close");this.closeButton.dataSet=this;this.closeButton.title="Close this table";this.closeButton.eventId="tableClose";this.titlePara.appendChild(this.closeButton);this.closeButton.helpId="closeButton";return this.closeButton;}},getButtonBox:function(){if(this.buttons){return this.buttons;}
else{this.buttons=HTML.div("buttons");var buttonsGrid=new Grid(1,2,"center");buttonsGrid.getRef().style.width="100%";this.leftButtonCell=buttonsGrid.getCell(1,1);this.rightButtonCell=buttonsGrid.getCell(1,2);this.rightButtonCell.style.textAlign="right";this.buttonList=HTML.tag("ul");this.buttons.appendChild(buttonsGrid.getRef());this.leftButtonCell.appendChild(this.buttonList);this.tableHolder.parentNode.insertBefore(this.buttons,this.tableHolder);return this.buttons;}},getNavigationBox:function(){if(this.nav){return this.nav;}
else{this.nav=HTML.div("tableNavigation");var navGrid=new Grid(1,5);navGrid.getCell(1,1).width="20";navGrid.getCell(1,2).width="20";navGrid.getCell(1,3).width="20";navGrid.getCell(1,5).width="20";this.inlineCell=navGrid.getCell(1,1);this.popupCell=navGrid.getCell(1,2);this.helpCell=navGrid.getCell(1,3);this.navDescriptionCell=navGrid.getCell(1,4);this.navDescriptionCell.style.textAlign="right";this.navDescriptionCell.style.color="#555";this.navDescriptionCell.style.fontSize=".8em";this.resizeCell=navGrid.getCell(1,5);this.resizeCell.dataSet=this;this.resizeCell.eventId="resize";this.resizeCell.helpId="resize";this.resizeCell.className="resizeWidget";navGrid.getRef().style.width="100%";this.nav.appendChild(navGrid.getRef());this.nav.dataSet=this;this.tableHolder.appendChild(this.nav);return this.nav;}},addButton:function(buttonSrc,label,eventId){var button=$('<li></li>').appendTo(this.buttonList).text(label).css("background","url("+buttonSrc+") no-repeat left center").get(0);button.dataSet=this;button.eventId=eventId;return button;},getNewButton:function(){if(!this.hasPriv("add")){return;}
this.getButtonBox();this.newButton=this.addButton(Images.url("newRecord"),"Add Item","newRecord");if(this.newOverrideUrl){this.newButton.newUrl=this.newOverrideUrl;}
return this.newButton;},getDeleteButton:function(){if(!this.hasPriv("delete")){return;}
this.getButtonBox();this.deleteButton=this.addButton(Images.url("deleteRecords"),"Delete Rows","deleteRows");return this.deleteButton;},getTrashButton:function(){if(!this.hasPriv("delete")){return;}
this.getButtonBox();this.trashButton=this.addButton(Images.url("showTrash"),"View Trash","showTableTrash");return this.trashButton;},getSubtotalsButton:function(){var numericCount=0;for(var i=0,len=this.numColumns();i<len;i++){var column=this.column(i);if(column.get("sortType")=="num"){numericCount++;}}
if(numericCount==0){return;}
this.getButtonBox();this.subtotalsButton=this.addButton(Images.url("subtotals"),"Subtotals","showSubtotalsViewer");return this.subtotalsButton;},getPrintButton:function(){this.getButtonBox();this.printButton=this.addButton(Images.url("print"),"Print","printPage");return this.printButton;},getCSVButton:function(){this.getButtonBox();this.csvButton=this.addButton(Images.url("csv"),"Spread Sheet","csvPage");return this.csvButton;}});function addSaveDefault(table,field,value){if(typeof saveDefaults=="undefined"){saveDefaults={};}
if(!saveDefaults[table]){saveDefaults[table]={};}
if(!saveDefaults[table][field]){saveDefaults[table][field]=value;}}
function DbData(dataSet){this.header=[];this.headerLookup={};this.body={};if(isUndefined(dataSet)){return;}
if(typeof dataSet=='string'){this.table=dataSet;}
else{if(dataSet.header){this.setHeader(dataSet.header);}
if(dataSet.body){this.body=dataSet.body;}}}
applyTo(DbData.prototype,{setHeader:function(head){this.header=head;this.headerLookup={};for(var i=0,len=head.length;i<len;i++){this.headerLookup[head[i]]=i;}},setBody:function(body){this.body=body;},getKey:function(table,rowNum){var keyPattern=keyFieldPattern.replace("|tableName|",this.table);return this.body[rowNum][this.headerLookup[keyPattern]];},getFieldNum:function(fieldName){for(var i=0,len=this.header.length;i<len;i++){if(fieldName==this.header[i]){return i;}}},findValue:function(rowNum,field){return this.body[rowNum][this.headerLookup[field]];},getValue:function(item){return this.body[item.rowNum][item.fieldNum];},setValue:function(item,val){this.body[item.rowNum][item.fieldNum]=val||getFormItemValue(item);},revertValue:function(item){this.body[item.rowNum][item.fieldNum]=item.getAttribute('initvalue');},getRowHash:function(rowNum){var hash={};var rowSet=this.body[rowNum];for(var i=0,len=this.header.length;i<len;i++){try{var field=this.header[i];var value=rowSet[i];hash[field]=value;}
catch(e){}}
return hash;},setValueForField:function(fieldName,rowNum,value){var colNum=this.getFieldNum(fieldName);this.body[rowNum][colNum]=value;},resolveExceptions:function(rowNum,exception,original){if(!exception){return original;}
var data=this.getRowHash(rowNum);for(var fieldName in exception){var patternOpts=exception[fieldName];for(var neededValue in patternOpts){if(data[fieldName]==neededValue){return patternOpts[neededValue];}}}
return original;},numRows:function(){return this.body.length;},renderPattern:function(rowNum,pattern){var data=this.getRowHash(rowNum);var re=/\|(\w+)\|/g;var newPattern=pattern;while(result=re.exec(pattern)){var replacement=data[result[1]]?data[result[1]]:'';newPattern=newPattern.replace(result[0],replacement);}
return newPattern;},hasPrevRow:function(rowNum){return this.body[rowNum-1];},hasNextRow:function(rowNum){return this.body[rowNum+1];}});ActiveTable.prototype.swapData=function(data){this.dbdata=data;this.rows={};this.initSortAndFilter();this.runSort();this.setPaginationPool();this.fillTable();this.updateNavigation();this.triggerRecache();};JSGI.DataMap=function(){var that={},map={};return that;};applyTo(JSGI.click,{restoreRecord:function(){var req=JSGI.ajaxRequest('trash_items');req.setJob('restore');req.add('id',this.target.trashId);req.send();if(lensActive('monthcalendar')){var cal=lensRef('monthcalendar');cal.build();cal.getTrashPalette();}},switchTableSource:emptyFn});JSGI.controls.deleteRowButton=function(dataSet,rowNum){var button=Images.get("clearButton");button.eventId=dataSet.pouchtype?"deleteWithSourcelist+subView:"+dataSet.tableId+",deleteRow+normalView:"+dataSet.tableId:"deleteRow";button.dataSet=dataSet;button.rowNum=rowNum;button.style.cursor="pointer";return button;};ActiveTable.prototype.selectRow=function(rowNum){if(Mouse.clickGuard==rowNum){window.setTimeout("JSGI.pageElements['"+this.tableId+"'].openSelectedRows();",100);return;}
this.setRowNum(rowNum);var row=this.currentRow();if(row.isSelected()){row.unselect();}
else{row.select();Mouse.clickGuard=rowNum;window.setTimeout("Mouse.clickGuard = -1;",1000);}
row.setClass();return true;};function ActiveTableRow(table){this.table=table;this.ref=HTML.tableRow();this.inlineRef=HTML.tableRow();this.popupRef=HTML.tableRow();this.inlineCache=[];this.popupCache=[];this.rowNum=table.rowNum;this.colNum=null;this.ref.id=table.tableId+"."+table.rowNum;this.selected=false;this.opened=false;this.newRow=false;this.built=false;this.columns_set=false;}
applyTo(ActiveTableRow.prototype,{getMarkup:function(){if(!this.built){this.buildCaches();this.built=true;}
if(!this.columns_set){this.inlineRef=HTML.tableRow();this.popupRef=HTML.tableRow();if(this.table.pouchtype){var inlinePouchCell=HTML.tableCell();var popupPouchCell=HTML.tableCell();var inlinePouchButton=PouchIcon(inlinePouchCell,this.table.pouchtype,"dark");var popupPouchButton=PouchIcon(popupPouchCell,this.table.pouchtype,"dark");var pouchRow=function(){var preview=new ActiveTablePreview(this.rowNum,this.dataSet);var container=HTML.div("boundPreview");container.style.position="";container.appendChild(preview.formTable);HTML.addToBody(container);container.dataSet=this.dataSet;container.rowNum=this.rowNum;container.pouchtype=this.dataSet.pouchtype;var unpouchRow=function(target){var row=this.dataSet.dbdata.getRowHash(this.rowNum);var list=target.list;var hash={};hash[list.getJoinSource()]=target.data.id;hash[list.getJoinRow()]=row.id;JSGI.CRUD.create(list.getJoinTable(),hash);};container.unpouch=unpouchRow;return container;};inlinePouchCell.pouchTransform=pouchRow;popupPouchCell.pouchTransform=pouchRow;inlinePouchCell.rowNum=this.rowNum;popupPouchCell.rowNum=this.rowNum;inlinePouchCell.dataSet=this.table;popupPouchCell.dataSet=this.table;inlinePouchCell.appendChild(inlinePouchButton);popupPouchCell.appendChild(popupPouchButton);this.inlineRef.appendChild(inlinePouchCell);this.popupRef.appendChild(popupPouchCell);}
for(var colNum=0,len=this.table.numColumns();colNum<len;colNum++){this.colNum=colNum;var column=this.table.column(colNum);if(column.isHidden()){continue;}
var iCell=HTML.tableCell();var apCell=HTML.tableCell();apCell.innerHTML=this.popupCache[colNum];iCell.innerHTML=this.inlineCache[colNum];this.bindCell(iCell);this.bindCell(apCell);this.inlineRef.appendChild(iCell);this.popupRef.appendChild(apCell);}
this.columns_set=true;}
return this.selectRef();},buildTruncateDiv:function(apCell){var truncateDiv=HTML.div("truncate");truncateDiv.innerHTML="&nbsp;"+this.popupCache[this.colNum];apCell.style.padding="0";truncateDiv.style.paddingTop="5px";truncateDiv.style.paddingBottom="5px";truncateDiv.eventId="row";this.bindCell(truncateDiv);return truncateDiv;},selectRef:function(){if(!(this.table.hasPriv('edit')||(this.table.hasPriv('add')&&this.table.addedRows[this.table.rowNum]==1))||this.table.displayFormat=="autoPopup"){this.inlineRef.id="";this.popupRef.id=this.table.tableId+"."+this.rowNum;return this.popupRef;}
else{this.popupRef.id="";this.inlineRef.id=this.table.tableId+"."+this.rowNum;return this.inlineRef;}},buildSingleColumn:function(colNum){var row=HTML.tableRow();var cell=HTML.tableCell();this.colNum=colNum;if(this.table.truncation==1){var truncateDiv=this.buildTruncateDiv(cell);truncateDiv.style.width="100%";if(jQuery.browser.msie)truncateDiv.style.height="25px";cell.appendChild(truncateDiv);}
else{cell.innerHTML=this.popupCache[colNum];}
row.appendChild(cell);row.className=this.getClassName();return row;},buildCaches:function(){this.inlineCache=this.resolvePatterns("inline");this.popupCache=this.resolvePatterns("autoPopup");},bindCell:function(cell){var col=this.table.column(this.colNum);if(col.unsortable()||col.sortType=='num'){cell.style.textAlign="right";}
cell.dataSet=this.table;cell.rowNum=this.rowNum;cell.colNum=this.colNum;cell.eventId="row";this.activateCellChildren(cell);},getText:function(){var columns=this.resolvePatterns("autoPopup");var visibleColumns=[];for(var i=0,len=columns.length;i<len;i++){var column=this.table.column(i);if(column.isVisible()&&!column.isMeta()){visibleColumns.push(columns[i]);}}
info(columns.length+" vs. "+visibleColumns.length);return"<tr><td>"+visibleColumns.join("</td><td>")+"</td></tr>";},getRaw:function(){var columns=this.resolvePatterns("autoPopup");var visibleColumns=[];for(var i=0,len=columns.length;i<len;i++){var column=this.table.column(i);if(column.isVisible()&&!column.isMeta()){visibleColumns.push(columns[i].replace(",","\,"));}}
return visibleColumns;},resolvePatterns:function(type){var patternType=(type=="inline")?"columnPattern":"textPattern";var patterns=this.table.columnValues(patternType);var colPats=[];for(var colNum=0,len=this.table.numColumns();colNum<len;colNum++){colPats.push(this.table.dbdata.resolveExceptions(this.rowNum,clone(this.table.columnValue("exception",colNum)),patterns[colNum]));}
var pattern=colPats.join("*!*");var results=this.table.dbdata.renderPattern(this.rowNum,pattern).split("*!*");for(var colNum=0,len=this.table.numColumns();colNum<len;colNum++){var column=this.table.column(colNum);var altOutput=column.get("outputMap")[results[colNum]];if(altOutput){results[colNum]=altOutput;}}
return results;},resolvePattern:function(colNum,type){var column=this.table.column(colNum);var pattern=(type=="autoPopup")?column.get("filterPattern"):column.get("columnPattern");pattern=this.table.dbdata.resolveExceptions(this.rowNum,clone(column.get("exception")),pattern);return this.table.dbdata.renderPattern(this.rowNum,pattern);},getClassName:function(){var className=(this.table.paginationLookup[this.rowNum]%2)?"alt":"std";if(this.isSelected()){className="clickSelect";}
if(this.isOpened()){className="openPopup";}
return className;},setClass:function(){this.getMarkup().className=this.getClassName();},reset:function(){this.built=false;this.cellCache=[];this.ref=HTML.tableRow();this.resetColumns();},setData:function(name,value){var head=this.table.dbdata.header;var body=this.table.dbdata.body[this.rowNum];for(var i=0,len=head.length;i<len;i++){if(head[i]==name){this.table.dbdata.body[this.rowNum][i]=value;this.reset();return;}}},activateCellChildren:activateCellChildren,activateChild:function(child,foCounter){child.dataSet=this.table;child.rowNum=this.rowNum;child.colNum=this.colNum;child.fieldNum=this.table.dbdata.headerLookup[child.getAttribute("dbfield")];child.id=this.table.tableId+"."+this.rowNum+"."+this.colNum+"."+foCounter;var column=this.table.column(child.colNum);if(column.get("poolFormItems")){var poolName=ccolumn.get("poolFormItems");if(typeof formItemSets=="undefined"){formItemSets={};}
if(typeof formItemSets[poolName]=="undefined"){formItemSets[poolName]=[];}
formItemSets[poolName].push(child);}
if(!isImage(child)&&this.table.firstPageChild==null){this.table.firstPageChild=child;}
if(this.isNew()&&!JSGI.firstNewRowBox&&isTextbox(child)){JSGI.firstNewRowBox=child;}},loadNewChild:function(child){if(this.isNew()||child.getAttribute("auto")){updateData(999,child);}},resetColumns:function(){this.columns_set=false;},markNew:function(){this.newRow=true;},markOld:function(){this.newRow=false;},isNew:function(){return this.newRow;},select:function(){this.selected=true;},unselect:function(){this.selected=false;},isSelected:function(){return this.selected;},markOpened:function(){this.opened=true;},markClosed:function(){this.opened=false;},isOpened:function(){return this.opened;},isVisible:function(){return this.table.visibleRows[this.rowNum];},isBuilt:function(){return this.built;}});JSGI.click.row=function(){this.target.dataSet.selectRow(this.target.rowNum);};JSGI.mouseover.row=function(){hoverDataTableRow(this.target);};JSGI.mouseout.row=function(){JSGI.hoveredTable=null;this.target.dataSet.clearPreview()};JSGI.mousemove.row=function(){this.target.dataSet.positionPreview(this.target.rowNum,this.evtRef)};var ColumnDef=function(){var settings={columnPattern:"",sortPattern:"",filterPattern:"",label:"",sortType:"alpha",visibility:"show",inPopup:true,meta:false,required:false,width:"*",initWidth:"*",exception:{},outputMap:{}};applyTo(this,settings);};applyTo(ColumnDef.prototype,{set:function(name,value1,value2,value3,value4){switch(name){case"patterns":this.columnPattern=value1;this.sortPattern=value2;this.filterPattern=value3;this.textPattern=value3;break;case"labels":this.label=value1;this.shortLabel=value2;break;case"settings":this.sortType=value1;this.visibility=value2;this.width=value3;this.initWidth=value3;this.inPopup=value4;break;case"width":this.initWidth=value1;this.width=value1;break;default:this[name]=value1;}},add:function(name,value1,value2){switch(name){case"outputMap":this.outputMap[value1]=value2;break;}},get:function(name){return this[name];},setException:function(field,matchValue,cpattern){if(typeof this.exception[field]=="undefined"){this.exception[field]={};}
this.exception[field][matchValue]=cpattern;},hasFieldConfig:function(){return this.dbtable&&this.dbfield;},fieldConfigData:function(){return{table:this.dbtable,field:this.dbfield};},show:function(){this.visibility="show";},hide:function(){this.visibility="hide";},numericSort:function(){this.sortType=="num";},moneySort:function(){this.sortType=="money";},unsortable:function(){this.sortType=="nosort";},isVisible:function(){return this.visibility=="show";},isHidden:function(){return this.visibility=="hide";},isRequired:function(){return this.required;},isMeta:function(){return this.meta;}});applyTo(ActiveTable.prototype,{openSelectedRows:function(){info("openSelectedRows");var buffer=this.getPopupBufferLength();var ord=1;for(var rowNum in this.rows){var row=this.rows[rowNum];if(!row.isSelected()){continue;}
info("Building:"+rowNum);this.setRowNum(rowNum);var coords=this.getPopupCoordinates(ord,buffer);var popup=new Popup(this,rowNum);popup.build();var node=document.getElementById(popup.popupId);this.setRowNum(rowNum);if(jQuery.browser.msie){node.style.width="400px";}
var actualTop=getOnScreenTop(node,coords.top);HTML.setTop(node,actualTop);HTML.setLeft(node,coords.left);if(jQuery.browser.msie){if(document.getElementById("magic_iframe-"+popup.popupId)){HTML.remove(document.getElementById("magic_iframe-"+popup.popupId));}
var width=popup.body.offsetWidth;var height=popup.body.offsetHeight;var top=getAbsPos(popup.body,"Top");var left=getAbsPos(popup.body,"Left");var frame=HTML.tag("IFRAME");frame.id="magic_iframe-"+popup.popupId;this.title.popupId=popup.popupId;frame.style.height=height;frame.style.width=width;frame.style.position="absolute";frame.frameBorder=0;frame.style.top=top;frame.style.left=left;frame.style.background="blue";HTML.addToBody(frame);}
if(typeof this.popupOrder=="undefined"){this.popupOrder=[];}
this.popupOrder.push(rowNum);row.unselect();row.markOpened();this.redrawRow();ord++;}
if(!this.popupOrder){return;}
this.sortPopups();},getPopupBufferLength:function(){return(this.popupOrder)?(this.popupOrder.length*30):0;},getPopupCoordinates:function(multiple,buffer){var coords={top:getAbsPos(this.table,"Top")+buffer+(multiple*30),left:getAbsPos(this.table,"Left")+buffer+(multiple*30)};return coords;},sortPopups:function(){var z_index=400;for(var i=0,len=this.popupOrder.length;i<len;i++){var rowNum=this.popupOrder[i];var popupId="popup."+this.tableId+"."+rowNum;var popup=this.popups[popupId];popup.style.zIndex=z_index;z_index++;}},canShowFormItems:function(rowNum){return this.hasPriv('edit')||(this.hasPriv('add')&&this.addedRows[rowNum]==1)}});var Popup=function(dataSet,rowNum){this.table=dataSet;this.tableId=dataSet.tableId;this.rowNum=rowNum;this.popupId="popup."+dataSet.tableId+"."+rowNum;this.initFocus=null;this.markup=null;this.formItems=[];JSGI.saveStacks[this.popupId]=JSGI.SaveStack();dataSet.popupRows[rowNum]=1;if(typeof popupRowMap=="undefined"){popupRowMap={};}
popupRowMap[this.popupId]=rowNum;};applyTo(Popup.prototype,{parentRow:function(){this.table.setRowNum(this.rowNum);return this.table.currentRow();},redrawParent:function(){this.table.setRowNum(this.rowNum);this.table.redrawRow();},build:function(){if(document.getElementById(this.popupId)){return;}
this.markup=HTML.div("popupForm",this.popupId);HTML.addToBody(this.markup);this.table.popups[this.popupId]=this.markup;this.getStructure();this.addRows();Drag.init(this.title,this.markup);if(this.initFocus){this.initFocus.focus();}
this.redrawParent();this.parentRow().markOpened();this.parentRow().setClass();return this.markup;},addRows:function(){for(var i=0,len=this.table.numColumns();i<len;i++){var column=this.table.column(i);if(column.inPopup){this.formBody.appendChild(this.buildRow(i));}}},buildRow:function(colNum){this.colNum=colNum;var column=this.table.column(colNum);var row=HTML.tableRow();var head=HTML.tableHeadCell();var cell=HTML.tableCell();head.innerHTML=column.get("label");if(this.table.columns[colNum].isRequired()){head.innerHTML+="<span style='color:red'>*</span>";}
head.eventId="popupTitleBar";head.dataSet=this.table;head.popupId=this.popupId;var pattern=this.selectPattern(colNum);cell.eventId="popupTitleBar";cell.dataSet=this;cell.popupId=this.popupId;if(pattern=="_NEW_"){pattern="";}
cell.innerHTML=pattern;for(var i=0,len=cell.childNodes.length;i<len;i++){this.activateCell(cell.childNodes[i]);}
addToDOM(row,[head,cell]);return row;},selectPattern:function(colNum){var column=this.table.column(colNum);var pattern=this.table.canShowFormItems(this.rowNum)?column.get("columnPattern"):column.get("filterPattern");pattern=this.table.dbdata.resolveExceptions(this.rowNum,column.get("exception"),pattern);pattern=this.table.dbdata.renderPattern(this.rowNum,pattern);return pattern;},getStructure:function(){this.box=HTML.div("item_box");this.title=this.getPopupTitlebar();this.title.eventId="popupTitlebar";this.body=HTML.div("boxcontent");var formTable=HTML.table("data_form");this.formBody=HTML.tableBody();var butonBar=this.getPopupButtonBar();addToDOM(this.markup,[this.box,[this.title,this.body,[formTable,[this.formBody],butonBar]]]);},activateCell:function(child){if(isTextbox(child)||isTextArea(child)){if(!this.initFocus){this.initFocus=child;}
if(getFormItemValue(child)=="_NEW_"){child.value="";}}
if(isDropdown(child)){activateDropdown(child);}
if(isFormItem(child)){child.stackName=this.popupId;child.popup=1;child.dataSet=this.table;child.rowNum=this.rowNum;child.colNum=this.colNum;child.fieldNum=this.table.dbdata.headerLookup[child.getAttribute("dbfield")];child.popupId=this.popupId;child.popupSet=this;child.eventId="popupTitleBar";child.onblur=function(e){var target=JSGI.getEventTarget(e);info("Time to redraw the source row.");target.dataSet.redrawRow();}
this.formItems.push(child);}
if(isCheckbox(child)){activateCheckbox(child);}
if(isDatebox(child)){child.id=child.dataSet.dbdata.getKey(child.getAttribute("dbtable"),child.rowNum)+child.getAttribute("dbfield")+"calField";activateDatebox(child);}
if(isTimebox(child)){activateTimebox(child);}},getPopupTitlebar:function(){var title=HTML.div("titlebar");title.dataSet=this.table;title.popupSet=this;title.popupId=this.popupId;var labelPattern=this.table.dbdata.renderPattern(this.rowNum,this.table.popupLabel);if(labelPattern.match("_NEW_")){labelPattern="New "+this.rowUnit;}
title.appendChild(this.wrapPopupTitlebarText(labelPattern));return title;},wrapPopupTitlebarText:function(textString){var list=HTML.tag("UL");var item=HTML.tag("LI");var para=HTML.tag("P");list.appendChild(item);item.appendChild(para);para.eventId="popupTitleBar";para.dataSet=this.table;para.popupId=this.popupId;para.popupSet=this;para.innerHTML=textString;return list;},getPopupButtonBar:function(){var bottom=HTML.div("bottom_buttons");bottom.eventId="popupTitleBar";bottom.dataSet=this.table;bottom.popupId=this.popupId;if(this.table.hasPriv('edit')||(this.table.hasPriv('add')&&this.table.addedRows[this.rowNum]==1)){bottom.appendChild(this.popupButton("Cancel",this.popupId,"cancelPopup"));bottom.appendChild(this.popupButton("Save",this.popupId,"savePopup"));}
else{bottom.appendChild(this.popupButton("Close",this.popupId,"cancelPopup"));}
return bottom;},popupButton:function(label,popupId,eventId){var button=HTML.button(label);button.popupId=this.popupId;button.popupSet=this;button.dataSet=this.table;button.eventId=eventId;return button;},rollback:function(){for(var i=0,len=this.formItems.length;i<len;i++){var input=this.formItems[i];var startValue=input.getAttribute("initvalue");if(isTextbox(input)&&startValue!=input.value){this.table.setRowNum(input.rowNum);if(this.parentRow().isNew()){info("is new");this.table.deleteRow();this.table.updateNavigation();break;}
else{info("not new: "+startValue+" vs "+input.value);input.value=startValue;this.parentRow().setData(input.getAttribute("dbfield"),startValue);processChange(input);}}}
this.close();},close:function(){var returnNode=(arguments[2]&&arguments[2]==1);this.table.setRowNum(this.rowNum);delete this.table.popupRows[this.rowNum];try{this.parentRow().unselect();this.parentRow().markClosed();this.parentRow().reset();this.redrawParent();}
catch(e){}
this.table.popupOrder=this.table.popupOrder.erase(this.rowNum);if(!returnNode){HTML.remove(this.markup);}
this.table.fillTable();this.table.updateNavigation();this.table.sortPopups();if(jQuery.browser.msie){HTML.remove(document.getElementById("magic_iframe-"+this.popupId));}
if(returnNode){return this.markup;}},focus:function(){info("focusPopup()");var popupParts=this.popupId.split(".");this.table.setRowNum(popupParts[2]);var newPopupOrder=[];var currLast=this.table.popupOrder.last();for(var i=0,len=this.table.popupOrder.length;i<len;i++){if(this.table.popupOrder[i]!=this.rowNum){newPopupOrder.push(this.table.popupOrder[i]);}}
newPopupOrder.push(this.rowNum);this.table.popupOrder=newPopupOrder;this.table.sortPopups();if(this.rowNum!=currLast){this.initPopup.focus();}},save:function(){if(typeof lastFocused!="undefined"&&lastFocused.stackName){updateData(999,lastFocused);lastFocused.dataSet.setRowNum(lastFocused.rowNum);lastFocused.dataSet.redrawRow();}
var stack=JSGI.saveStacks.getStack(this.popupId);stack.requestPage=saveDataLocation;stack.resolveMessages();stack.buildTree();stack.resolveSaveDefaults();stack.serializeRequest();stack.sendRequest();stack.manageResponse();stack.cleanup();var record=this.table.dbdata.body[this.rowNum];for(var i=0,len=record.length;i<len;i++){if(record[i]=="_NEW_"){record[i]="";}}
this.redrawParent();if(!stack.changes){this.close();}
return true;}});applyTo(JSGI.click,{savePopup:function(){this.target.popupSet.save();},cancelPopup:function(){this.target.popupSet.rollback();}});JSGI.dblclick.row=function(){this.target.dataSet.openSelectedRows();};function popupChildFocus(evt){return;info("popupChildFocus");var target=JSGI.getEventTarget(evt);target.dataSet.setRowNum(target.rowNum);if(target.dataSet.currentPage!=target.dataSet.paginationLookup[this.rowNum]){target.dataSet.currentPage=target.dataSet.paginationLookup[this.rowNum];target.dataSet.fillTable();target.dataSet.updateNavigation();}}
function openRows(evtRef){var target=JSGI.getEventTarget(evtRef);target.dataSet.openSelectedRows();}
ActiveTable.prototype.addRow=function(){info("Add Row.");this.clearFilter();JSGI.firstNewRowBox=null;if(!this.hasPriv("add")){return;}
info('Can Add');var dataLength=this.dbdata.body.length;var lastRowNum=dataLength-1;var newRowNum=(dataLength>0)?dataLength:0;info("newRowNum:"+newRowNum);if(isNaN(newRowNum)){var newRowNum=0;}
info("Fill Data Set");this.setRowNum(newRowNum);var newRow=[];for(var i in this.dbdata.header){newRow.push('_NEW_');}
this.dbdata.body.push(newRow);this.sortOrder.push(newRowNum);this.rows[newRowNum]=new ActiveTableRow(this);this.addedRows[newRowNum]=1;this.lastAdded=newRowNum;this.rows[newRowNum].markNew();this.buildSortCache();this.buildFilterCache();this.filterSettings[newRowNum]=1;this.setPaginationPool();if(this.getPaginationPool().length>this.getRowLimit()){this.startRow=this.getPaginationPool().length-this.getRowLimit();}
else{this.startRow=0;}
info("StartRow:"+this.startRow);info("fillTable:");this.fillTable();info("Update Navigation!");this.updateNavigation();this.newKeyCounter++;if(this.displayFormat=="autoPopup"){var buffer=this.getPopupBufferLength();var coords=this.getPopupCoordinates(1,buffer);var popup=new Popup(this,newRowNum);popup.build();this.setRowNum(newRowNum);var actualTop=getOnScreenTop(document.getElementById(popup.popupId),coords.top);HTML.setTop(document.getElementById(popup.popupId),actualTop);HTML.setLeft(document.getElementById(popup.popupId),coords.left);if(typeof this.popupOrder=="undefined"){this.popupOrder=[];}
this.popupOrder.push(newRowNum);this.sortPopups();}
this.runFilter();this.updateNavigation();if(JSGI.firstNewRowBox){if(jQuery.browser.msie){window.setTimeout("document.getElementById('"+JSGI.firstNewRowBox.id+"').focus();",100);}
else{JSGI.firstNewRowBox.focus();}}
return false;};JSGI.click.newRecord=function(){if(this.target.newUrl){window.location.href=this.target.newUrl;}
else{this.target.dataSet.addRow();}};function applyAdjustments(evtRef,target){if(target.adjustmentId){AutoAdjust.loadInput(target);AutoAdjust.cleanup();}}
var AutoAdjust={tableId:null,rowNum:null,adjustmentId:null,results:{},loadInput:function(input){this.tableId=input.tableId;this.rowNum=input.rowNum;},setResult:function(name,value){this.results[name]=value;},apply:function(){this[this.adjustmentId]();},cleanup:function(){this.tableId=null;this.rowNum=null;this.adjustmentId=null;this.results={};}};applyTo(ActiveTable.prototype,{removeRow:function(){this.getRow().parentNode.removeChild(this.getRow());},getStartRow:function(){if(this.startRow+this.getRowLimit()>this.getPaginationPool().length){this.startRow=this.getPaginationPool().length-this.getRowLimit();}
if(this.startRow>this.getPaginationPool().length||this.startRow<0){this.startRow=0;}
if(typeof this.startRow=='undefined'){this.startRow=0;}},getLength:function(){return(this.getRowLimit()>=this.getPaginationPool().length)?this.getPaginationPool().length:this.getRowLimit();},totalRefill:function(){var len=this.getLength();var newTbody=HTML.tableBody();this.visibleRows={};this.currentRows=[];for(var i=0;i<len;i++){this.pagePosition=i;this.setRowNum(this.getPaginationPool()[this.startRow+i]);this.visibleRows[this.rowNum]=1;this.currentRows.push(this.rowNum);newTbody.appendChild(this.getRow());}
if(this.getPaginationPool().length<this.getRowLimit()){var leftoverRows=this.getRowLimit()-this.getPaginationPool().length;if(leftoverRows>0){for(var i=0;i<leftoverRows;i++){newTbody.appendChild(this.buildBlankRow());}}}
this.tbody.parentNode.replaceChild(newTbody,this.tbody);this.tbody=newTbody;},fillTable:function(){this.getStartRow();(this.incrementalMode)?this.fillIncrementally():this.totalRefill();this.displayBlankMessage();this.sourceCell.style.height=this.table.offsetHeight+'px';},getRowCommon:function(rowNum){if(rowNum){this.setRowNum(rowNum);}
if(typeof this.currentRow()!='undefined'){var row=this.currentRow();}
else{var row=new ActiveTableRow(this);this.rows[this.rowNum]=row;}
return row;},getRow:function(rowNum){var row=this.getRowCommon(rowNum);row.setClass();return row.getMarkup();},getTextRow:function(rowNum){var row=this.getRowCommon(rowNum);return row.getText();},getRawContent:function(rowNum){var row=this.getRowCommon(rowNum);return row.getRaw();},redrawRow:function(){var oldRow=document.getElementById(this.tableId+'.'+this.rowNum);if(oldRow){var newRow=this.getRow();oldRow.parentNode.replaceChild(newRow,oldRow);}},buildBlankRow:function(){var row=HTML.tableRow();for(var i=0,len=this.numColumns();i<len;i++){var column=this.column(i);var cell=HTML.tableCell();cell.innerHTML="&nbsp;";if(column.isHidden()){cell.style.display='none';}
row.appendChild(cell);}
return row;},displayBlankMessage:function(){if(this.dbdata.body.length==0){var tb=this.tbody;var row=$(tb).find('tr').get(0);if(row)
tb.removeChild(row);var newRow=createElement('tr');var blankRow=createElement('td',{colSpan:this.colOrder.length,cls:'empty_row'});blankRow.innerHTML='There are no results to display.';newRow.appendChild(blankRow);tb.insertBefore(newRow,$(tb).find('tr').get(0));}}});applyTo(ActiveTable.prototype,{deleteRow:function(){var newOrder=[];var newBody=[];for(var i=0,len=this.sortOrder.length;i<len;i++){if(this.sortOrder[i]!=this.rowNum){newOrder.push(this.sortOrder[i]);newBody.push(this.dbdata.body[i]);}}
this.sortOrder=newOrder;this.dbdata.body=newBody;delete this.rows[this.rowNum];this.buildSortCache();this.filterCache=null;},removeRowRef:function(rowNum){this.setRowNum(rowNum);this.deleteRow();},deleteRowData:function(rowNum){if(!this.hasPriv("delete")){return;}
this.rowNum=rowNum;var key=this.dbdata.getKey(this.tableId,rowNum);if(!key.match("_NEW_")){if(JSGI.CRUD.destroy(this.tableId,key)){this.removeRowRef(rowNum);}}
this.cleanupDelete();},deleteRowsData:function(){if(!this.hasPriv("delete")){return;}
var deleteQueue=[];for(var rowNum in this.rows){if(this.rows[rowNum].isSelected()){deleteQueue.push(rowNum);}}
if(deleteQueue.length<1){return true;}
var msg="Are you sure you want to delete "+deleteQueue.length+" row(s)?\n\nNOTE: Clicking 'OK' will immediately delete the items.";if(confirm(msg)){var stack=JSGI.SaveStack();stack.requestPage=saveDataLocation;for(var i=0,len=deleteQueue.length;i<len;i++){var rowNum=deleteQueue[i];var key=this.dbdata.getKey(this.tableId,rowNum);if(!key.match("_NEW_")){stack.addSimpleMessage(this.tableId,"delete",key,"delete",rowNum);}}
stack.resolveMessages();stack.buildTree();stack.resolveSaveDefaults();stack.serializeRequest();stack.sendRequest();stack.manageResponse();if(stack.getResponseStatus()===true){for(var i=0,len=deleteQueue.length;i<len;i++){this.removeRowRef(deleteQueue[i]);}}
stack.cleanup();this.cleanupDelete();}},cleanupDelete:function(){this.runSort();this.runFilter();this.setPaginationPool();this.fillTable();this.updateNavigation();},deleteWithSourceList:function(rowNum){row=this.dbdata.getRowHash(rowNum);if(JSGI.CRUD.destroy(this.sourceListTableName,row[this.sourceListKeyName])){this.removeRowRef(rowNum);}
this.cleanupDelete();},showTrashedItems:function(){var req=JSGI.ajaxRequest("trash_items");req.add("original_table",this.tableId);info(req);var data=req.getDbData();if(!data){postInfoMessage("There are no deleted items for this table.");warn("No Messages to delete.");return;}
this.trashPalette=HTML.div("trashPalette");var paletteTitle=HTML.tag("h3");paletteTitle.innerHTML="Deleted Items from "+this.label+":";var top=(getAbsPos(this.buttons,"Top")+this.buttons.offsetHeight);var left=(Math.round(this.buttons.offsetWidth*0.1)+getAbsPos(this.buttons,"Left"));this.trashPalette.appendChild(paletteTitle);this.trashPalette.style.top=top+"px";this.trashPalette.style.width=Math.round(this.buttons.offsetWidth*0.8)+"px";this.trashPalette.style.left=left+"px";var headers=[""],rows=[];for(var i=0,len=data.numRows();i<len;i++){var row=data.getRowHash(i);JSGI.parseJSON("trash_item="+row.json_dump.replace(/(\w)(\')(\w)/g,"$1\\'$3"));var check=HTML.checkBox();check.eventId="selectTrashRow";check.className="restore";check.dbid=row.id;var dataRow=[check];for(var name in trash_item.attributes){if(!name.match(/\_at|id|created\_by/g)){if(i==0){headers.push(name);}
dataRow.push(trash_item.attributes[name]);}}
rows.push(dataRow);}
info(headers);var table=JSGI.fastTable(headers,rows);this.trashPalette.appendChild(table);this.trashPalette.style.display="none";var bottomRibbon=HTML.div("bottom_buttons");var restoreButton=HTML.eventButton("Restore","applyRestore",this);var cancelButton=HTML.eventButton("Cancel","cancelRestore",this);bottomRibbon.appendChild(cancelButton);bottomRibbon.appendChild(restoreButton);this.trashPalette.appendChild(bottomRibbon);HTML.addToBody(this.trashPalette);jQuery(this.trashPalette).show().css("opacity","0.9");},hideTrashedItems:function(){jQuery(this.trashPalette).slideUp();}});applyTo(JSGI.click,{deleteWithSourcelist:function(){this.target.dataSet.deleteWithSourceList(this.target.rowNum);},selectTrashRow:function(){info(this.target.parentNode.parentNode);var cells=this.target.parentNode.parentNode.childNodes;for(var i=0,len=cells.length;i<len;i++){var cell=cells[i];cell.style.backgroundColor=(cell.style.backgroundColor)?'':'#80FF00';}},applyRestore:function(){var checks=jQuery("input.restore").each(function(){if(this.checked){var req=JSGI.ajaxRequest("trash_items");req.setJob("restore");req.add("id",this.dbid);req.send();location.reload();}});return true;},cancelRestore:function(){this.target.dataSet.hideTrashedItems();},deleteRow:function(){this.target.dataSet.deleteRowData(this.target.rowNum);},deleteRows:function(){this.target.dataSet.deleteRowsData();},showTableTrash:function(){this.target.dataSet.showTrashedItems();},cancelTrashPalette:function(){this.target.dataSet.hideTrashedItems();},restoreTableRecord:function(){var req=JSGI.ajaxRequest("trash_items");req.setJob("restore");req.add("id",this.target.trashId);req.send();this.cleanupDelete();this.target.dataSet.showTrashedItems();}});applyTo(ActiveTable.prototype,{getFilter:function(){if(this.filter){return this.filter;}
else{this.filter=HTML.textBox(20);this.filter.dataSet=this;this.filter.eventId="filter";this.filter.id=this.tableId+'.filter';this.filter.title="Display rows matching your supplied search";this.filter.value=this.filterPattern||"Filter Search";this.filter.className="dtFilter";this.filter.onkeyup=function(evt){var dataSet=this.dataSet;var clearFilter=dataSet.getClearButton();clearFilter.style.visibility=(this.value&&this.value!="")?"visible":"hidden";if(!dataSet.filterInterval){dataSet.oldFilterPattern=this.value;dataSet.filterPattern=this.value;dataSet.filterInterval=window.setInterval("JSGI.pageElements['"+dataSet.tableId+"'].monitorFilter();",800);}
else{dataSet.oldFilterPattern=dataSet.filterPattern;dataSet.filterPattern=this.value;}};this.filter.onblur=function(evt){if(this.value==""){this.value="Filter Search";}};this.filter.onfocus=function(evt){if(this.value=="Filter Search"){this.value="";}};this.rightButtonCell.appendChild(this.filter);this.getClearButton();return this.filter;}},getClearButton:function(){if(this.clear){return this.clear;}
else{this.clear=Images.get("clearButton");this.clear.dataSet=this;this.clear.title="Clear the seach box";this.clear.className="clearButton";this.clear.eventId="filterClear";this.clear.style.visibility=(this.filter.value!="Filter Search")?"visible":"hidden";this.filter.parentNode.appendChild(this.clear);return this.clear;}},monitorFilter:function(){info("Monitor the filter");info("Filter Pattern: "+this.filterPattern);info("Old Filter: "+this.oldFilterPattern);if(this.filterPattern==this.oldFilterPattern){window.clearInterval(this.filterInterval);this.filterInterval=null;this.applyFilterResults();}
else{this.oldFilterPattern=this.filterPattern;}},applyFilterResults:function(){this.startRow=0;this.freezeOldRows();this.runFilter();this.setPaginationPool();this.fillTable();this.updateNavigation();},clearFilter:function(){this.filter.value="Filter Search";this.filterPattern="";this.getClearButton().style.visibility="hidden";this.runFilter();this.setPaginationPool();this.fillTable();this.updateNavigation();},buildFilterCache:function(){var dataHeader=this.dbdata.header;var data=this.dbdata.body;var dataPatterns=this.columnValues("filterPattern");this.filterCache=[];for(var i=0,len=data.length;i<len;i++){this.filterCache[i]=[];var dataRow=data[i];for(var j=0,len2=this.numColumns();j<len2;j++){var column=this.column(j);this.filterCache[i][j]=(column.unsortable())?"":this.dbdata.renderPattern(i,dataPatterns[j]);}}},runFilter:function(){info("ActiveTable.runFilter",arguments);if(!this.filterPattern||this.filterPattern=="Filter Search"){for(var i=0,len=this.dbdata.numRows();i<len;i++){this.filterSettings[i]=1;}
this.filteredRows=this.dbdata.numRows();return;}
info("Filter to run");var patternParts=this.filterPattern.split(' ');if(!this.filterCache){this.buildFilterCache();}
info(this.filterCache)
this.filteredRows=0;for(var i=0,len=this.filterCache.length;i<len;i++){if(this.filterCache[i]){var rowText=this.filterCache[i].join(' ');}
else{continue;}
var patternMatches=0;for(var j=0,len2=patternParts.length;j<len2;j++){var searchRow=rowText.toUpperCase();var searchPattern=patternParts[j].toUpperCase();if(searchRow.indexOf(searchPattern)!=-1){patternMatches++;}}
if(patternParts.length!=patternMatches){this.filterSettings[i]=0;}
else{this.filterSettings[i]=1;this.filteredRows++;}}
for(var i in this.addedRows){if(this.rows[i].isNew()){this.filteredRows++;}}
info("filter run");}});JSGI.click.filterClear=function(){this.target.dataSet.clearFilter();};applyTo(ActiveTable.prototype,{addSourceList:function(list){if(typeof this.sourceLists=="undefined"){this.sourceLists=[];}
this.sourceLists.push(list);list.setDataSet(this);},retrieveRemoteData:function(setType,params){params=params||{};var req=JSGI.serverRequest(this.dbdataPath);req.add("source_type",setType);req.add("root",this.rootTable);req.add("source",this.sourceTable);req.add("link",this.linkTable);if(this.dataDelimiter){req.add("delimiter",this.dataDelimiter);}
if(this.dataJoins){req.add("joins",this.dataJoins);}
for(name in params){req.add(name,params[name]);}
req.getJSON(function(json){JSGI.jsonData=json;});return new DbData(JSGI.jsonData);},switchToSubSource:function(target){var data=this.retrieveRemoteData("subset",target.data);this.swapData(data);deactivateLens("normalView:"+this.tableId);activateLens("subView:"+this.tableId,this);this.sourceListKeyName=target.keyname;this.sourceListTableName=target.tablename;this.addCell.style.display="none";this.trashCell.style.display="none";},switchToMainSource:function(){var data=this.retrieveRemoteData("default");this.swapData(data);deactivateLens("subView:"+this.tableId);activateLens("normalView:"+this.tableId,this);this.addCell.style.display="";this.trashCell.style.display="";}});var SourceList=function(){this.sourceLabel="Items";this.listWidth='200';this.keyName='sourcelistid';this.allItems=[];};applyTo(SourceList.prototype,{build:function(){var list=new DefinitionList();var title=list.addTitle(this.sourceLabel);if(this.manageUrl){var editIcon=Images.get("editRoot");editIcon.eventId="editSourceListRoot";editIcon.url=this.manageUrl;editIcon.list=this;editIcon.style.display="inline";editIcon.style.marginLeft="5px";editIcon.style.cursor="pointer";title.appendChild(editIcon);}
if(this.defaultItemName){var defaultItem=list.addItem();defaultItem.className='selectedSource';defaultItem.appendChild(HTML.textNode(this.defaultItemName));defaultItem.isDefault=true;defaultItem.eventId="selectTableDataSource-pouch";defaultItem.dataSet=this.dataSet;defaultItem.tablename=this.tableName;defaultItem.list=this;this.allItems.push(defaultItem);}
if(this.data!==null){var dbdata=new DbData(this.data);for(var i=0,len=dbdata.numRows();i<len;i++){var row=dbdata.getRowHash(i);var item=list.addItem();var content=dbdata.renderPattern(i,this.itemPattern);item.appendChild(HTML.textNode(content));item.data=row;item.pouchtype=this.dataSet.pouchtype;item.eventId="usePouchItem+pouch,selectTableDataSource-pouch";item.isDefault=false;item.dataSet=this.dataSet;item.keyname=this.keyName;item.tablename=this.tableName;item.list=this;this.allItems.push(item);}}
this.root=HTML.div("sourceList");this.root.style.width=this.listWidth+'px';this.root.appendChild(list.markup());return this.root;},setSourceLabel:function(label){this.sourceLabel=label;},setData:function(dbdata){this.data=dbdata;},setItemPattern:function(pattern){this.itemPattern=pattern;},setDataSet:function(set){this.dataSet=set;},setDefaultItem:function(itemName){this.defaultItemName=itemName;},setPouchType:function(pt){this.pouchType=pt;},setKeyName:function(name){this.keyName=name;},setTableName:function(name){this.tableName=name;},setWidth:function(w){this.listWidth=w;},getWidth:function(){return this.listWidth;},setManageUrl:function(url){this.manageUrl=url;},joinSettings:function(table,source,row){this.joinTable=table;this.joinSource=source;this.joinRow=row;},getJoinTable:function(){return this.joinTable;},getJoinSource:function(){return this.joinSource;},getJoinRow:function(){return this.joinRow;},clearItems:function(){for(var i=0,len=allItems.length;i<len;i++){allItems[i].className="";}}});applyTo(JSGI.click,{selectTableDataSource:function(){this.target.list.clearItems();this.target.className="selectedSource";if(this.target.isDefault){this.target.dataSet.switchToMainSource();}
else{this.target.dataSet.switchToSubSource(this.target);}},editSourceListRoot:function(){window.location.href=this.target.url;}});JSGI.mouseover.editSourceListRoot=function(){this.target.src=Images.url("editRootHover");};JSGI.mouseout.editSourceListRoot=function(){this.target.src=Images.url("editRoot");};applyTo(ActiveTable.prototype,{buildScrollBar:function(){var scrollBar=this.getScrollbarContainer();var gutter=this.getScrollbarGutter();var topPad=this.getTopPad();var slider=this.getScrollbarSlider();var upArrow=this.getScrollbarUpButton();var downArrow=this.getScrollbarDownButton();scrollBar.appendChild(upArrow);scrollBar.appendChild(downArrow);scrollBar.appendChild(gutter);gutter.appendChild(topPad);gutter.appendChild(slider);return scrollBar;},positionScrollbar:function(){var scrollBar=this.scrollBar;var up=this.scrollUpButton;var down=this.scrollDownButton;var gutter=this.scrollGutter;var col=this.columnToggle;HTML.setHeight(scrollBar,this.table.offsetHeight-1-15);HTML.setHeight(gutter,(this.table.offsetHeight-up.offsetHeight-down.offsetHeight-15));this.positionScrollSlider();},positionScrollSlider:function(){var gutter=this.scrollGutter;var pad=this.topPad;var slider=this.scrollSlider;if(this.getPaginationPool().length<=this.getRowLimit()){slider.style.display="none";return;}
else{slider.style.display="";}
var total=this.getPaginationPool().length;var percent=(this.getRowLimit()/total);HTML.setHeight(slider,(percent*gutter.offsetHeight))
var actualHeight=slider.offsetHeight;if(actualHeight<18){slider.style.height="18px";}
var topPercent=(this.startRow==0)?0:(this.startRow/total);var offset=topPercent*gutter.offsetHeight;var bottom=offset+slider.offsetHeight;var scrollFloor=gutter.offsetHeight;var overflow=bottom-scrollFloor;if(overflow>0){offset-=overflow;}
if(offset>0){try{var tween=new Tween(pad.style,"height",Tween.regularEaseIn,pad.offsetHeight,offset,0.5);tween.start();}
catch(e){HTML.setHeight(pad,offset);}}
else{pad.style.height="";}},getScrollbarContainer:function(){this.scrollBar=HTML.div("scrollBar",this.tableId+".scrollBar");this.scrollBar.style.borderLeft="1px solid silver";this.scrollBar.style.borderTop="1px solid silver";return this.scrollBar;},getScrollbarUpButton:function(){var up=Images.get("scrollUp");up.className="upButton";up.style.width="18px";up.style.height="18px";up.style.margin="0";up.style.padding="0";up.eventId="scrollUp";up.helpId="scrollUp";up.dataSet=this;this.scrollUpButton=up;return up;},getScrollbarDownButton:function(){var down=Images.get("scrollDown");down.className="downButton";down.style.width="18px";down.style.height="18px";down.style.margin="0";down.style.padding="0";down.eventId="scrollDown";down.helpId="scrollDown";down.dataSet=this;this.scrollDownButton=down;return down;},getScrollbarGutter:function(){var gutter=HTML.div("scrollGutter");gutter.eventId="nextPage";gutter.helpId="nextPage";gutter.dataSet=this;gutter.style.width="18px";this.scrollGutter=gutter;return gutter;},getTopPad:function(){var pad=HTML.div();pad.eventId="prevPage";pad.helpId="prevPage";pad.dataSet=this;this.topPad=pad;return pad;},getScrollbarSlider:function(){var slider=HTML.div("scrollbarslider");slider.style.width="18px";slider.eventId='scrollSlider';slider.helpId="scrollSlider";slider.dataSet=this;this.scrollSlider=slider;return slider;},scrollDown:function(){var newStart=this.startRow+1;this.startRow=(newStart+this.getRowLimit()>this.getPaginationPool().length)?this.getPaginationPool().length-this.getRowLimit():newStart;this.finishTableNav();if(lensActive("scrollDown")){window.setTimeout("JSGI.pageElements['"+this.tableId+"'].scrollDown();",100);}},scrollUp:function(){var newStart=this.startRow-1;this.startRow=(newStart<0)?0:this.startRow-1;this.finishTableNav();if(lensActive("scrollUp")){window.setTimeout("JSGI.pageElements['"+this.tableId+"'].scrollUp();",100);}},nextPage:function(){var newStart=this.startRow+this.getRowLimit();this.startRow=(newStart+this.getRowLimit()>this.getPaginationPool().length)?this.getPaginationPool().length-this.getRowLimit():newStart;this.finishTableNav();},lastPage:function(){this.startRow=this.getPaginationPool().length-this.getRowLimit();this.finishTableNav();},prevPage:function(){if(this.startRow-this.getRowLimit()<0){this.startRow=0;}
else{this.startRow-=this.getRowLimit();}
this.finishTableNav();},firstPage:function(){this.startRow=0;this.finishTableNav();},finishTableNav:function(){this.fillTable();this.updateNavigation();var attr=(jQuery.browser.msie)?'className':'class';var query='table.'+this.table.getAttribute(attr)+' input';var firstInput=$(query)[0];firstInput.focus();},keyboardLastPage:function(){this.currentPage=this.pagination.length-1;this.fillTable();this.updateNavigation();this.focusFirstFormObject();},moveDownOneRow:function(targetId){info("Move Down One Row");var idParts=targetId.split('.');var tableId=idParts[0];var row=parseInt(idParts[1]);var cell=idParts[2];var foNum=idParts[3];this.setRowNum(row);if(this.hasNextRow()){var nextId=tableId+"."+this.nextRow().rowNum+"."+cell+"."+foNum;if(!this.nextRow().isVisible()){this.scrollDown();}
setFocus(document.getElementById(nextId));}
else{this.addRow();}
return true;},moveUpOneRow:function(targetId){var idParts=targetId.split('.');var tableId=idParts[0];var row=parseInt(idParts[1]);var cell=idParts[2];var foNum=idParts[3];this.setRowNum(row);if(this.hasPrevRow()){var nextId=tableId+"."+this.prevRow().rowNum+"."+cell+"."+foNum;if(!this.prevRow().isVisible()){this.scrollUp();}
setFocus(document.getElementById(nextId));}
return true;},keyboardFirstPage:function(){this.currentPage=0;this.fillTable();this.updateNavigation();this.focusFirstFormObject();return true;}});applyTo(JSGI.click,{nextPage:function(){(this.evtRef.shiftKey)?this.target.dataSet.lastPage():this.target.dataSet.nextPage();},prevPage:function(){(this.evtRef.shiftKey)?this.target.dataSet.firstPage():this.target.dataSet.prevPage();}});applyTo(JSGI.mousedown,{scrollDown:function(){info("Mouse Down scrollDown!");info("I can see my target?");info(this.target);info(this);activateLens("scrollDown",this.target.dataSet);window.setTimeout("JSGI.pageElements['"+this.target.dataSet.tableId+"'].scrollDown();",300);},scrollUp:function(){activateLens("scrollUp",this.target.dataSet);window.setTimeout("JSGI.pageElements['"+this.target.dataSet.tableId+"'].scrollUp();",300);},scrollSlider:function(){var coords=JSGI.getCoordinates(this.evtRef);this.target.dataSet.grabScrollSlider(coords.top);}});applyTo(JSGI.mouseup,{scrollDown:function(){deactivateLens("scrollDown");},scrollUp:function(){deactivateLens("scrollUp");}});applyTo(ActiveTable.prototype,{freezeOldRows:function(){this.oldCurrentRows=cloneArray(this.currentRows);},filterTransition:function(){var filterQueue=new AsyncQueue(this.swapFilterTransitionRow,150,JSGI.pageElements[this.tableId]);filterQueue.setCleanup(this.completeFilterTransition,JSGI.pageElements[this.tableId]);for(var i=0,len=this.oldCurrentRows.length;i<len;i++){var rowNum=this.oldCurrentRows[i];if(!this.paginationLookup[rowNum]){filterQueue.send(rowNum);}}
filterQueue.end();},swapFilterTransitionRow:function(rowNum){this.setRowNum(rowNum);},completeFilterTransition:function(){this.fillTable();this.updateNavigation();this.clearMessage();},sortTransition:emptyFn});JSGI.click.printPage=function(){this.target.dataSet.printCurrentPage();};ActiveTable.prototype.printCurrentPage=function(){var header=this.dbdata.header,body=this.dbdata.body,filterSettings=this.filterSettings;var printWindow=window.open("","print_window","width=800, height=600, menubar=yes, resizable=yes, scrollbars=yes");printWindow.focus();printWindow.document.write("<html><head><title>Print "+this.label+"</title><link type='text/css' rel='stylesheet' href='"+appName+"/jsgi/css/print.css'></head>");printWindow.document.write("<body>");printWindow.document.write("<div style='font-family: Helvetica, sans-serif; padding: 10px; border: 1px solid #ccc; background-color: white;'>");printWindow.document.write("<h3>"+this.label+"</h3>");var table=['<table class="print_table" cellpadding="10" cellspacing="0">'];table.push("<tr>");for(var i=0,len=this.numColumns();i<len;i++){var column=this.column(i);if(column.isVisible()&&!column.isMeta()){table.push('<th style="text-align: left; padding: 5px; border-bottom: 3px double black">'+column.get("label")+'</th>');}}
table.push("</tr>");var pool=this.getPaginationPool();for(var i=0,len=pool.length;i<len;i++){this.rowNum=pool[i];info("Print row num:"+this.rowNum);table.push(this.getTextRow(this.rowNum));}
table.push("</table>");info(table.join("\n"));printWindow.document.write(table.join("\n"));if(this.subTotal&&this.subTotal.css("display")=="block"){printWindow.document.write("<h3>Sub Totals</h3>");printWindow.document.write('<table class="print_table" cellpadding="10" cellspacing="0">');printWindow.document.write('<tr><th style="text-align: left; padding: 5px; border-bottom: 3px double black">'+this.descriptorColumnName+'</th><th style="text-align: left; padding: 5px; border-bottom: 3px double black">'+this.counterColumnName+"</th></tr>");for(var name in this.subTotalMap){var count=this.subTotalMap[name];printWindow.document.write('<tr><td>'+name+'</td><td>'+count+'</td></tr>');}
printWindow.document.write("</table>");}
printWindow.document.write("</div>");printWindow.document.write("</body></html>");printWindow.document.close();};JSGI.click.csvPage=function(){this.target.dataSet.csvCurrentPage();};ActiveTable.prototype.csvCurrentPage=function(){var header=this.dbdata.header,body=this.dbdata.body,filterSettings=this.filterSettings;var rows=[];var header=[];for(var i=0,len=this.numColumns();i<len;i++){var column=this.column(i);if(column.isVisible()&&!column.isMeta()){header.push(column.get("label"));}}
rows.push(header);var pool=this.getPaginationPool();for(var i=0,len=pool.length;i<len;i++){var rowToBuild=pool[i];this.rowNum=rowToBuild;rows.push(this.getRawContent(pool[i]));}
xml=["<csv>"];for(var i=0,len=rows.length;i<len;i++){var row=rows[i];var rowString=row.join("]]></cell><cell><![CDATA[");rowString=rowString.replace('"','').replace(',','\'');xml.push("<row><cell><![CDATA["+rowString+"]]></cell></row>");}
if(this.subTotal&&this.subTotal.css("display")=="block"){xml.push("<row><cell>Sub Totals</cell></row>");xml.push('<row><cell>'+this.descriptorColumnName+'</cell><cell>'+this.counterColumnName+"</cell></row>");for(var name in this.subTotalMap){var count=this.subTotalMap[name];xml.push('<row><cell>'+name+'</cell><cell>'+count+'</cell></row>');}}
xml.push("</csv>");var submitFrame=HTML.tag("iframe");submitFrame.name="csvsubmit";submitFrame.style.visibility="hidden";var form=$('<form target="csvsubmit" action="'+csvLocation+'"></form>');var ta=$('<textarea rows="1" cols="1" name="xml">'+xml.join("")+'</textarea>').hide();var body=$("body:eq(0)");$(form).append(ta);body.append(submitFrame);body.append(form);form.submit();};applyTo(JSGI.click,{showSubtotalsViewer:function(){if(!this.target.dataSet.subTotal){this.target.dataSet.generateSubtotalsInterface();}
else{this.target.dataSet.toggleSubtotalsInterface();}},runSubtotal:function(){this.target.dataSet.generateSubtotalsReport();}});applyTo(ActiveTable.prototype,{generateSubtotalsInterface:function(){var subTotal=jQuery("<div class='subtotals'></div>"),descriptorSelect=jQuery("<select></select>").property("dataSet",this).change(function(event){event.target.dataSet.subtotalDescriptor=$(event.target).val();event.target.dataSet.generateSubtotalsReport();info("changed descriptor to "+event.target.dataSet.column(event.target.dataSet.subtotalDescriptor));}),counterSelect=jQuery("<select></select>").property("dataSet",this).change(function(event){event.target.dataSet.subtotalCounter=$(event.target).val();event.target.dataSet.generateSubtotalsReport();info("changed counter to "+event.target.dataSet.column(event.target.dataSet.subtotalCounter));});counterSelect.append("<option value='' selected></option>");descriptorSelect.append("<option value='' selected></option>");for(var i=0,len=this.numColumns();i<len;i++){var column=this.column(i);if(!column.isMeta()){var optionText="<option value="+i+">"+column.get("label")+"</option>";if(column.get("sortType")=="num"){if(!this.subtotalCounter){this.subtotalCounter=i;}
counterSelect.append(optionText);}
else{if(!this.subtotalDescriptor){this.subtotalDescriptor=i;}
descriptorSelect.append(optionText);}}}
this.subTotal=subTotal;this.subtotalDescripterSelect=descriptorSelect;this.subtotalCounterSelect=counterSelect;this.subTotal.hide();this.subTotal.append("Get Subtotal of ").append(counterSelect).append("Grouped By ").append(descriptorSelect).insertAfter(jQuery(this.buttons)).show("fast");this.generateSubtotalsReport();},generateSubtotalsReport:function(){var row,descriptor,counter;this.counterColumnName=this.column(this.subtotalCounter).get("label"),this.descriptorColumnName=this.column(this.subtotalDescriptor).get("label");if(!this.subtotalReport){this.subtotalReport=jQuery("<div class='subtotalReport'></div>").appendTo(this.subTotal);}
this.subTotalMap={};for(var i=0,len=this.dbdata.numRows();i<len;i++){this.getRow(i);row=this.rows[i];descriptor=row.popupCache[this.subtotalDescriptor];counter=row.popupCache[this.subtotalCounter];if(typeof this.subTotalMap[descriptor]=="undefined"){this.subTotalMap[descriptor]=0;}
this.subTotalMap[descriptor]+=parseInt(counter,10);}
var table=jQuery('<table class="data_table"></table>');table.append("<tr><th>"+this.descriptorColumnName+"</th><th>"+this.counterColumnName+"</th></tr>");for(var name in this.subTotalMap){var count=this.subTotalMap[name];table.append('<tr><td>'+name+'</td><td>'+count+'</td></tr>');}
this.subtotalReport.html("").append(table);},toggleSubtotalsInterface:function(){if(this.subTotal.css("display")=="none"){this.subTotal.show("fast");}
else{this.subTotal.hide("fast");}}});applyTo(ActiveTable.prototype,{helpTree:{tableHelp:"Click to turn this interactive help system on or off.",closeButton:"Close this table.",printButton:"Open a new window containing a simplified view of this table, suitable for printing.",deleteButton:"Delete selected rows. To select a row for deletion, click on it once.",addButton:"Add a new row to this table.",filterClear:"Clear the currently selected help text.",filter:"Type in search criteria. Only rows matching the criteria will be displayed.",scrollUp:"Scroll up through the rows. Click-and-hold to continue scrolling automatically.",scrollDown:"Scroll down through the rows. Click-and-hold to continue scrolling automatically.",nextPage:"Jump down one whole page. Shift-click to jump to the end.",prevPage:"Jump up one whole page. Shift-cilck to jump to the beginning.",scrollSlider:"Click-and-drag to rapidly scroll through visible rows.",columnToggle:"Click to access a menu containing a list of available columns which can then be switched on and off.",popupEditType:"Edit data in popup windows.",inlineEditType:"Edit data directly in the table itself.",resize:"Click and drag to increase or decrease the number of visible rows. Double click to display all rows at once. Double click again to collapse to four rows."},showHelp:function(){this.helpActive=true;this.helpBox=HTML.div("helpBox");HTML.setHeight(this.helpBox,this.table.offsetHeight);HTML.setWidth(this.helpBox,this.table.offsetWidth);this.helpBox.style.textAlign="center";this.helpBox.innerHTML="Mouse over any item to view a description of what it does.";this.table.parentNode.replaceChild(this.helpBox,this.table);},switchHelp:function(helpId){this.helpBox.innerHTML=this.helpTree[helpId];},hideHelp:function(){this.helpActive=false;this.helpBox.parentNode.replaceChild(this.table,this.helpBox);}});function serializeTableData(){serialData=[];for(var tableId in JSGI.pageElements){tableData=[];tableData.push(tableId);var tableSet=JSGI.pageElements[tableId];if(tableSet.setType!="table"){continue;}
tableData.push(tableSet.rowLimit);var numVer=tableSet.columnValues("visibility").join("");numVer=numVer.replace(/show/g,'2');numVer=numVer.replace(/hide/g,'1');tableData.push(numVer);if(tableSet.displayFormat){var abbrET=(tableSet.displayFormat!="autoPopup")?'i':'a'
tableData.push(abbrET);}
else{tableData.push("a");}
var updated=false;for(var i=0,len=serialData.length;i<len;i++){if(serialData[i].match(new RegExp('$'+tableId))){serialData[i]=tableData.join("_");updated=true;break;}}
if(!updated){serialData.push(tableData.join("_"));}}
var cookieString=escape(serialData.join('*'));var cookieName="sd."+getSectionName();if(cookieString){var expiration_date=new Date();expiration_date.setMonth(expiration_date.getMonth()+1);expiration_date=expiration_date.toGMTString();document.cookie=cookieName+"="+cookieString+"; expires="+expiration_date;}}
ActiveTable.prototype.loadSavedData=function(){var labelName="sd."+getSectionName();var cookieString=getCookieValue(labelName);if(typeof cookieString=="undefined"){return;}
var cookieSegments=cookieString.split("*");var correctSettigs=null;for(var i=0,len=cookieSegments.length;i<len;i++){if(cookieSegments[i].match(new RegExp(this.tableId))){correctSettings=cookieSegments[i];}}
if(typeof correctSettings=="undefined"){return;}
var settings=correctSettings.split('_');var tableId=settings[0];var newSet=JSGI.pageElements[tableId];if(typeof newSet=="undefined"){return;}
this.rowLimit=parseInt(settings[1],10);if(settings[3]=="a"){newSet.displayFormat="autoPopup";}
else if(settings[3]=="i"){newSet.displayFormat="inline";}
var currVis=settings[2].toString();currVis=currVis.split("");for(var j=0,len=currVis.length;j<this.numColumns();j++){var column=newSet.column(j);(currVis[j]==2)?column.show():column.hide();}};window.onunload=serializeTableData;function getCookieValue(labelName){var allCookies=document.cookie.split("; ");for(var i=0,len=allCookies.length;i<len;i++){var currCookie=allCookies[i];var cookieParts=currCookie.split("=");var cookieName=cookieParts[0];var cookieValue=cookieParts[1].trim();if(cookieName==labelName){return unescape(cookieValue);}}}
applyTo(ActiveTable.prototype,{toggleDisplayFormat:function(){this.displayFormat=(this.displayFormat=="autoPopup")?"inline":"autoPopup";this.fillTable();this.updateNavigation();},toggleColumnForm:function(){if(!document.getElementById("columnList")){this.buildColumnToggleForm();}
else{this.destroyColumnToggleForm();}},toggleColumn:function(colNum){var column=this.column(colNum);column.isVisible()?column.hide():column.show();this.manualWidths={};this.resetAllColumns();this.clearWidths();this.setColumnOrder();this.determineWidths();this.fillHeader();this.fillTable();this.buildColumnToggleForm();},getEditToggles:function(){if(this.spreadsheetToggle){return;}
else{this.getNavigationBox();this.spreadsheetToggle=Images.get("spreadsheetOff");this.spreadsheetToggle.eventId="toggleEditType";this.spreadsheetToggle.dataSet=this;this.setToggleImages();this.inlineCell.style.padding="3px";this.spreadsheetToggle.style.cursor="pointer";if(!this.hasPriv("edit")&&!this.hasPriv("add")){this.spreadsheetToggle.style.visibility='hidden';}
this.inlineCell.appendChild(this.spreadsheetToggle);}},getColumnToggle:function(){if(this.columnToggle){return this.columnToggle;}
else{this.columnToggle=Images.get("colToggle");this.columnToggle.className="columnToggle";this.columnToggle.title="Toggle visibility of columns.";this.columnToggle.dataSet=this;this.columnToggle.eventId="columnToggleMenu";this.rightCell.insertBefore(this.columnToggle,this.scrollBar);return this.columnToggle;}},buildColumnToggleForm:function(){info("buildColumnToggleForm");this.columnToggle.src=Images.url("colToggleActive");var columnList=document.getElementById("columnList");if(columnList){var newList=false;}
else{var columnList=HTML.div("columnList","columnList");var newList=true;columnList.style.position="absolute";if(jQuery.browser.msie){var closeLink=HTML.button("X");closeLink.eventId="columnMenuClose";closeLink.dataSet=this;columnList.appendChild(closeLink);}
var opList=HTML.tag("ul");columnList.appendChild(opList);this.toggleItems=[];}
info(columnList);for(var i=0,len=this.numColumns();i<len;i++){var column=this.column(i);if(newList){var item=HTML.tag("li");item.dataSet=this;item.colNum=i;item.eventId="columnToggle";item.style.cursor="pointer";item.innerHTML=column.get("label");if(developing&&column.hasFieldConfig()){var button=HTML.button();var fcData=column.fieldConfigData();button.eventId="fieldconfig";button.table=fcData.table;button.field=fcData.field;button.value="Edit";button.style.border="1px solid gray";button.style.padding="2px";button.style.fontSize="9px";item.appendChild(button);}
opList.appendChild(item);this.toggleItems[i]=item;}
else{var item=this.toggleItems[i];}
item.style.color=(column.isHidden())?"gray":"";}
if(newList){jQuery(columnList).appendTo("body:eq(0)").css("visibility",'hidden');jQuery(columnList).css("top",getAbsPos(this.columnToggle,"Top")+this.columnToggle.offsetHeight).css("left",(getAbsPos(this.columnToggle,"Left")+this.columnToggle.offsetWidth-columnList.offsetWidth));if(jQuery.browser.msie){jQuery("#column_iframe-"+this.tableId).remove();var width=columnList.offsetWidth;var height=columnList.offsetHeight;var top=getAbsPos(columnList,"Top");var left=getAbsPos(columnList,"Left");var frame=HTML.tag("IFRAME");frame.id="column_iframe-"+this.tableId
frame.style.height=height;frame.style.width=width;frame.style.position="absolute";frame.frameBorder=0;frame.style.top=top;frame.style.left=left;frame.style.background="blue";frame.style.zIndex="20";columnList.style.zIndex="200";HTML.addToBody(frame);}
jQuery(columnList).css('visibility','visible');columnList.style.height=columnList.offsetHeight;}},destroyColumnToggleForm:function(){info("destroyColumnToggleForm");this.columnToggle.src=Images.url("colToggle");jQuery("#columnList").slideUp().remove();jQuery("#column_iframe-"+this.tableId).remove();},prepareResize:function(initY){activateLens("resize",this);this.dragInitY=initY;this.boxInitHeight=this.scrollGrid.offsetHeight;if(typeof this.filler=="undefined"){this.filler=HTML.div("tableFiller");}
HTML.setHeight(this.filler,this.scrollGrid.offsetHeight);HTML.setWidth(this.filler,this.scrollGrid.offsetWidth);HTML.fill(this.filler,"Show "+this.rowLimit+" rows at a time");HTML.replace(this.filler,this.scrollGrid);},dragResize:function(evtRef){var pos=JSGI.getCoordinates(evtRef);var pagePosition=pos.top;var currentY=parseInt(pagePosition,10);deltaY=currentY-this.dragInitY;var rowsNeeded=parseInt(deltaY/20,10);var newRowLimit=this.getRowLimit()+rowsNeeded;if(newRowLimit<=1&&deltaY<0){HTML.fill(this.filler,"Show 1 Row at a time");return;}
else if(isNaN(newRowLimit)){newRowLimit=this.getRowLimit();}
HTML.fill(this.filler,"Show "+newRowLimit+" rows at a time");HTML.setHeight(this.filler,this.boxInitHeight+deltaY);},releaseResize:function(evtRef){try{var pos=JSGI.getCoordinates(evtRef);var currentY=pos.top;deltaY=currentY-this.dragInitY;var rowsNeeded=parseInt(deltaY/20,10);var newRowLimit=this.getRowLimit()+rowsNeeded;if(newRowLimit<=1){newRowLimit=1;}
else if(isNaN(newRowLimit)){newRowLimit=this.getRowLimit();}
this.rowLimit=newRowLimit;this.dragInitY=null;HTML.replace(this.scrollGrid,this.filler);deactivateLens("resize");this.fillTable();this.updateNavigation();}
catch(e){info("Doh!");error(e);HTML.replace(AppLens.dataSet.scrollGrid,AppLens.dataSet.filler);deactivateLens("resize");}},autoSizeTable:function(){this.rowLimit=(this.rowLimit==0||this.rowLimit==this.getPaginationPool().length)?4:0;this.fillTable();this.updateNavigation();}});applyTo(JSGI.click,{fieldconfig:function(){var shell=jQuery('#fieldConfigFloater').get(0);if(!shell){shell=HTML.div("fieldConfigFloater","fieldConfigFloater");shell.style.visibility="hidden";HTML.addToBody(shell);}
var req=JSGI.serverRequest(fieldConfigLocation.replace("|table|",this.target.table).replace("|field|",this.target.field));var result=req.execute();shell.innerHTML=result;centerOnScreen(shell);shell.style.visibility="";Drag.init(document.getElementById('fcfloater'),shell);},cancelfc:function(){jQuery("#fieldConfigFloater").remove();},columnToggleMenu:function(){this.target.dataSet.toggleColumnForm();},columnMenuClose:function(){this.target.dataSet.destroyColumnToggleForm();},toggleEditType:function(){this.target.dataSet.toggleDisplayFormat();},columnToggle:function(){this.target.dataSet.toggleColumn(this.target.colNum);},cancelpageroles:function(){jQuery('#permissionsScreen').hide().empty();HTML.closeScreen('infoScreen');}});applyTo(JSGI.mousedown,{resize:function(){var pos=JSGI.getCoordinates(this.evtRef);this.target.dataSet.prepareResize(pos.top);},columnResize:function(){var pos=JSGI.getCoordinates(this.evtRef);this.target.dataSet.initResize(pos.left,this.target.colNum);}});JSGI.dblclick.resize=function(){this.target.dataSet.autoSizeTable();};applyTo(ActiveTable.prototype,{setupHeader:function(headerCell,colNum){var column=this.column(colNum);var sort=column.get("sortType");var sortMap={alpha:"Alphabetical",num:"Numeric",flname:"Last name",date:"Date"};headerCell.title=(column.get("tooltip"))?column.get("tooltip"):"Sort table ("+sortMap[sort]+")";if(sort=="num"){headerCell.style.textAlign="right";}},buildHeaderCell:function(colNum){var column=this.column(colNum);var width=column.get("width");var headerCell=HTML.tableHeadCell();headerCell.dataSet=this;headerCell.colNum=colNum;headerCell.eventId="tableHeading";headerCell.appendChild(this.buildColumnResizeWidget(colNum));var headerLabel=HTML.textNode(column.get("shortLabel"));if(colNum==this.currentSort){headerCell.className="active";}
if(column.isRequired()){headerCell.className="required";}
headerCell.appendChild(headerLabel);this.setupHeader(headerCell,colNum);return headerCell;},fillHeader:function(){var head=this.headerRow;var newHead=HTML.tableRow();if(this.pouchtype){pouchHeadCell=HTML.tableHeadCell();pouchHeadCell.innerHTML="&nbsp;";newHead.appendChild(pouchHeadCell);newHead.style.width="20px";}
this.headerCells={};for(var i=0,len=this.colOrder.length;i<len;i++){var colNum=this.colOrder[i];var headerCell=this.buildHeaderCell(colNum);this.headerCells[colNum]=headerCell;newHead.appendChild(headerCell);}
this.headerRow=newHead;HTML.replace(newHead,head);}});applyTo(ActiveTable.prototype,{updateNavigation:function(){this.navDescriptionCell.innerHTML=this.getNavDescriptionText();this.positionScrollbar();this.setToggleImages();},setToggleImages:function(){if(this.displayFormat=="inline"){this.spreadsheetToggle.src=Images.url("spreadsheetOn");this.spreadsheetToggle.title="Turn OFF Spreadsheet Mode"}
else{this.spreadsheetToggle.src=Images.url("spreadsheetOff");this.spreadsheetToggle.title="Turn ON Spreadsheet Mode"}},getNavDescriptionText:function(){var total=this.dbdata.numRows();var filtered=this.filteredRows;var numPages=this.getPaginationPool().length;if(isNaN(filtered)){filtered=0;}
if(isNaN(total)){total=0;}
var recsDesc=(total==filtered)?filtered:filtered+" of "+total;var first=(this.getPaginationPool().length>0)?this.startRow+1:0;var last=(numPages<this.getRowLimit())?numPages:parseInt(this.startRow)+parseInt(this.getRowLimit());var itemUnit=(total>1||total==0)?"Items":"Item";var description="Items "+first+" - "+last+" of "+filtered;return description;},sendMessage:function(message){this.messageCell.innerHTML=message;},clearMessage:function(){this.messageCell.innerHTML="&nbsp;";}});applyTo(ActiveTable.prototype,{setPaginationPool:function(){this.paginationPool=[];this.paginationLookup={};for(var i=0,len=this.sortOrder.length;i<len;i++){var rowNum=this.sortOrder[i];if(this.filterSettings[rowNum]==1){this.paginationPool.push(rowNum);this.paginationLookup[rowNum]=this.paginationPool.length-1}}},getPaginationPool:function(){if(typeof this.paginationPool=="undefined"){this.setPaginationPool();}
return this.paginationPool;},initSortAndFilter:function(){this.filterCache=[];this.sortCache=[];this.filteredRows=this.dbdata.numRows();var rawFilterRow=this.columnValues("filterPattern").join("*!*");var rawSortRow=this.columnValues("sortPattern").join("*!*");var allPatterns=[rawFilterRow,rawSortRow].join("!!!**!!!");for(var i=0,len=this.dbdata.numRows();i<len;i++){this.sortOrder[i]=i;this.filterSettings[i]=1;var swapped=this.dbdata.renderPattern(i,allPatterns).split("!!!**!!!");this.filterCache[i]=swapped[0].split("*!*");for(var j=0,len2=this.numColumns();j<len2;j++){if(this.column(j).unsortable()){this.filterCache[i][j]="";}}
var sortPatterns=swapped[1].split("*!*");for(var j=0,len2=sortPatterns.length;j<len2;j++){var column=this.column(j);var pattern=sortPatterns[j];if(typeof this.sortCache[j]=="undefined"){this.sortCache[j]=[];}
if(column.unsortable()){pattern='';}
else if(column.moneySort()){pattern=parseFloat(pattern)*100;if(isNaN(pattern)){pattern=0;}
pattern=''+pattern;}
else if(column.numericSort()&&pattern==''){pattern=0;}
this.sortCache[j][i]=pattern;}}},setColumnOrder:function(){this.colOrder=[];this.colOrderLookup={};this.relaventFilterPatterns=[];this.relaventColumnPatterns=[];map(this.allCols,this.manageColumn,this);},manageColumn:function(colNum){var column=this.column(colNum);if(column.isVisible()){this.colOrder.push(colNum);this.colOrderLookup[colNum]=this.colOrder.length-1;this.relaventColumnPatterns.push(column.get("columnPattern"));this.relaventFilterPatterns.push(column.get("filterPattern"));}},getRowLimit:function(){return(this.rowLimit=="*"||this.rowLimit==0)?parseInt(this.dbdata.body.length):parseInt(this.rowLimit);},setRowNum:function(rowNum){this.rowNum=rowNum;},currentRow:function(){return this.rows[this.rowNum];},nextRow:function(){var rowRef=this.rows[this.paginationLookup[this.rowNum]+1];if(rowRef){return rowRef;}
else{var currRow=this.rowNum;this.setRowNum(this.paginationLookup[this.rowNum]+1);this.getRow();rowRef=this.currentRow();this.setRowNum(currRow);return rowRef;}},hasNextRow:function(){return this.dbdata.hasNextRow(this.paginationLookup[this.rowNum]);},prevRow:function(){var rowRef=this.rows[this.paginationLookup[this.rowNum]-1];if(rowRef){return rowRef;}
else{var currRow=this.rowNum;this.setRowNum(this.paginationLookup[this.rowNum]-1);this.getRow();rowRef=this.currentRow();this.setRowNum(currRow);return rowRef;}},hasPrevRow:function(){return this.dbdata.hasPrevRow(this.paginationLookup[this.rowNum]);},nextRowNum:function(){debug("Current Row:"+this.rowNum);debug("Row Location:"+this.paginationLookup[this.rowNum]);debug("Next Row Location:"+(this.paginationLookup[this.rowNum]+1));var nextRow=this.paginationPool[this.paginationLookup[this.rowNum]+1];debug("Next Row Num:"+nextRow);return(this.rows[nextRow])?nextRow:null;},prevRowNum:function(){var prevRow=this.paginationPool[this.paginationLookup[this.rowNum]-1];return(this.rows[prevRow])?prevRow:null;},resetAllRows:function(){for(var i in this.rows){this.rows[i].reset();}},resetAllColumns:function(){for(var i in this.rows){this.rows[i].resetColumns();}},determineMinimumWidths:function(){var table=HTML.table("data_table");table.style.tableLayout="auto";var head=HTML.tableHead();var row=HTML.tableRow();addToDOM(HTML.getBody(),[table,[head,[row]]]);table.style.width="auto";this.columnFloors={};this.setColumnOrder();var tempCells={};for(var i=0,len=this.numColumns();i<len;i++){var headerCell=this.buildHeaderCell(i);row.appendChild(headerCell);tempCells[i]=headerCell;}
for(var i in tempCells){this.columnFloors[i]=tempCells[i].offsetWidth+3;}
HTML.getBody().removeChild(table);},determineWidths:function(){var pool=this.getButtonBox().offsetWidth-18;var needDetermined=[];var percentageBased=[];var totalPercentage=0;this.percentageWidths={};for(var i=0,len=this.colOrder.length;i<len;i++){var colNum=this.colOrder[i];var column=this.column(colNum);var setWidth=(this.manualWidths&&this.manualWidths[colNum])?this.manualWidths[colNum]:column.get("initWidth");if(setWidth=="*"){needDetermined.push(colNum);}
else{if(setWidth.match("%")){percentageBased.push(colNum);}
else{var percentage=Math.round((setWidth/pool)*100);this.percentageWidths[colNum]=percentage;totalPercentage+=percentage;}}}
for(var i=0,len=percentageBased.length;i<len;i++){var colNum=percentageBased[i];var column=this.column(colNum);var parsedPercentage=parseInt(column.get("initWidth").replace("%",""));this.percentageWidths[colNum]=parsedPercentage;totalPercentage+=parsedPercentage;}
var remainingPercentage=100-totalPercentage;var perColPercent=Math.floor(remainingPercentage/needDetermined.length);var leftOver=remainingPercentage-(perColPercent*needDetermined.length);for(var i=0,len=needDetermined.length;i<len;i++){var colNum=needDetermined[i];this.percentageWidths[colNum]=perColPercent;}
this.percentageWidths[this.colOrder.last()]+=leftOver;colGroup=HTML.tag("colgroup");colGroup.dataSet=this;this.renderedWidths={};this.colSet={};if(this.pouchtype){var pouchColumnCol=HTML.tag("col");pouchColumnCol.setAttribute("width","20px");colGroup.appendChild(pouchColumnCol);}
for(var i=0,len=this.colOrder.length;i<len;i++){var colNum=this.colOrder[i];var colTag=HTML.tag("col");this.colSet[colNum]=colTag;colTag.setAttribute("width",this.percentageWidths[colNum]+"%");colGroup.appendChild(colTag);}
this.colGroup=colGroup;this.table.insertBefore(this.colGroup,this.table.firstChild);},clearWidths:function(){info("Clear Widths");try{HTML.remove(this.colGroup);}
catch(e){warn("Error resetting widths:"+e);}}});applyTo(ActiveTable.prototype,{buildColumnResizeWidget:function(colNum){var resizeRegion=HTML.div("columnResize");resizeRegion.dataSet=this;resizeRegion.colNum=colNum;resizeRegion.eventId="columnResize";resizeRegion.innerHTML="&nbsp;";resizeRegion.style.width="3px";return resizeRegion;},initResize:function(initX,colNum){this.determineMinimumWidths();this.dragCol=colNum;this.dragColBaseWidth=this.headerCells[colNum].offsetWidth;var start=this.colOrderLookup[colNum]+1;this.affectedResizeColumns=this.colOrder.slice(start);activateLens("colResize",this);this.initX=initX;this.buildColumnTool();},buildColumnTool:function(){this.holder=HTML.div();HTML.setHeight(this.holder,this.table.offsetHeight);HTML.setWidth(this.holder,this.table.offsetWidth);this.fauxColumns={};this.fauxColumnInitWidths={};var colors=["red","blue","green","yellow"];for(var i=0,len=this.colOrder.length;i<len;i++){var colNum=this.colOrder[i];var column=HTML.div("fauxColumn");this.fauxColumns[colNum]=column;this.fauxColumnInitWidths[colNum]=this.headerCells[colNum].offsetWidth;HTML.setWidth(column,this.headerCells[colNum].offsetWidth);this.holder.appendChild(column);column.style.height="100%";var table=HTML.table("data_table");var thead=HTML.tableHead();var tbody=HTML.tableBody();var headerRow=HTML.tableRow();var header=HTML.tableHeadCell();addToDOM(column,[table,[thead,[headerRow,[header]],tbody]]);header.innerHTML=this.column(colNum).get("shortLabel");var len2=(this.getRowLimit()>=this.getPaginationPool().length)?this.getPaginationPool().length:this.getRowLimit();for(var j=0;j<len2;j++){this.setRowNum(this.getPaginationPool()[this.startRow+j]);var row=this.currentRow().buildSingleColumn(colNum);if(jQuery.browser.msie){row.style.height="1em";}
tbody.appendChild(row);}}
this.table.parentNode.replaceChild(this.holder,this.table);},dragColResize:function(evtRef){var pos=JSGI.getCoordinates(evtRef);var currentX=pos.left;var shift=currentX-this.initX;var rightColAction=(this.lastShift-shift>=0)?"grow":"shrink";this.lastShift=shift;if(this.dragColBaseWidth+shift<this.columnFloors[this.dragCol]){return;}
if(rightColAction=="shrink"){var minCount=0;for(var i=0,len=this.affectedResizeColumns.length;i<len;i++){var colNum=this.affectedResizeColumns[i];if(this.fauxColumns[colNum].offsetWidth<=this.columnFloors[colNum]){minCount++;}}
if(minCount==this.affectedResizeColumns.length){return;}}
switch(rightColAction){case"shrink":this.resizeFollowingColumns(shift,rightColAction);this.resizeCurrentColumn(shift);break;case"grow":this.resizeCurrentColumn(shift);this.resizeFollowingColumns(shift,rightColAction);break;}
var lastFaux=this.fauxColumns[this.affectedResizeColumns.last()];var usedTotal=0;for(var colNum in this.fauxColumns){if(colNum!=this.affectedResizeColumns.last()){usedTotal+=this.fauxColumns[colNum].offsetWidth;}}
HTML.setWidth(lastFaux,this.holder.offsetWidth-usedTotal);},resizeCurrentColumn:function(shift){var newWidth=this.dragColBaseWidth+shift;HTML.setWidth(this.fauxColumns[this.dragCol],newWidth);},resizeFollowingColumns:function(shift,action){var colCount=this.affectedResizeColumns.length;if(colCount<shift&&shift>0){var perColumn=parseInt(shift/colCount,10);var overflow=shift%colCount;for(var i=0;i<colCount;i++){var colNum=this.affectedResizeColumns[i];var fauxCol=this.fauxColumns[colNum];var neededWidth=this.fauxColumnInitWidths[colNum]-perColumn;if(colNum==this.affectedResizeColumns.last()){continue;}
if(action=="shrink"&&fauxCol.offsetWidth<=this.columnFloors[colNum]){overflow+=perColumn;continue;}
HTML.setWidth(fauxCol,neededWidth);}}},releaseColResize:function(){this.manualWidths={};for(var i=0,len=this.colOrder.length;i<len;i++){var colNum=this.colOrder[i];var column=this.column(colNum);var fauxColumn=this.fauxColumns[colNum];var initWidth=column.get("initWidth");this.manualWidths[colNum]=fauxColumn.offsetWidth.toString();}
this.resetAllColumns();this.clearWidths();this.determineWidths();this.fillHeader();this.fillTable();this.holder.parentNode.replaceChild(this.table,this.holder);deactivateLens("colResize");}});applyTo(ActiveTable.prototype,{resort:function(colNum){var column=this.column(colNum);this.colNum=colNum;if(column.unsortable()){return;}
this.sortDirection=(this.sortDirection!="init")?this.nextSortDirection:"std";if(colNum!=this.currentSort){this.sortDirection="std";this.nextSortDirection="rev";}
this.currentSort=colNum;this.runSort();this.setPaginationPool();this.startRow=0;this.fillHeader();this.fillTable();this.updateNavigation();this.incSortDirection();this.clearMessage();},buildSortCache:function(){this.sortCache=[];for(var i=0,len=this.numColumns();i<len;i++){this.sortCache[i]=[];}
for(var i=0,len=this.dbdata.numRows();i<len;i++){var dataRow=this.dbdata.body[i];for(var j=0,len2=this.numColumns();j<len2;j++){var column=this.column(j);if(column.unsortable()){this.sortCache[j][i]='';continue;}
var pattern=this.dbdata.renderPattern(i,column.get("sortPattern"));if(column.moneySort()){pattern=parseFloat(pattern,10)*100;if(isNaN(pattern)){pattern=0;}
pattern=''+pattern;}
if(column.numericSort()&&pattern==''){pattern=0;}
this.sortCache[j][i]=pattern;}}},sortColumn:function(){return this.columns[this.currentSort];},runSort:function(){var sortColumn=this.sortColumn();var sortDirection=this.sortDirection;this.sortOrder=[];if(!sortColumn||this.sortCache[this.currentSort]=="undefined"){var len=this.dbdata.numRows();if(len==0){return;}
for(var i=0,len=this.dbdata.numRows();i<len;i++){this.sortOrder[i]=i;}
return;}
info("Build sort array");info("currSort: "+this.currentSort);var sortArray=[];var valueSet=this.sortCache[this.currentSort];for(var i=0,len=valueSet.length;i<len;i++){var cellText=valueSet[i];if(isNaN(cellText)){cellText=cellText.toUpperCase();}
sortArray.push(cellText+'.'+i);}
info("Organize Sort");var sortTypes={num:"num",date:"num",percent:"num",money:"num",alpha:"alpha",flname:"alpha",fmlname:"alpha"};var mappedSort=sortTypes[sortColumn.get("sortType")];info("Run actual Sort");(mappedSort=="num")?sortArray.sort(sortNumbers):sortArray.sort();info("Reverse sort if needed");if(sortDirection=='rev'){sortArray.reverse();}
info("Render sort order from sort results.");if(this.sortDirection=='init'||this.sortDirection=="none"){for(var i=0,len=this.dbdata.numRows();i<len;i++){this.sortOrder[i]=i;}
this.currentSort=null;}
else{for(var i=0,len=sortArray.length;i<len;i++){var valOrderPair=sortArray[i].split('.');var valOrderPairOrder=valOrderPair[valOrderPair.length-1];this.sortOrder.push(valOrderPairOrder);}}},incSortDirection:function(){var sortDirection=this.sortDirection;if(sortDirection=='init'||sortDirection=="none"){this.nextSortDirection='std';}
else if(sortDirection=='std'){this.nextSortDirection='rev';}
else if(sortDirection=='rev'){this.nextSortDirection='none';}}});function sortNumbers(a,b){aSplit=a.replace(/,/g,'').split('.');bSplit=b.replace(/,/g,'').split('.');aSplit.pop();bSplit.pop();a=aSplit.join('.');b=bSplit.join('.');return parseFloat(a)-parseFloat(b);}
JSGI.click.tableHeading=function(){var colNum=this.target.colNum;var column=this.target.dataSet.columns[colNum];var sortType=column.get('sortType');if(sortType!='nosort'){this.target.dataSet.resort(colNum);}};var Drag={obj:null,init:function(o,oRoot,minX,maxX,minY,maxY,bSwapHorzRef,bSwapVertRef,fXMapper,fYMapper)
{o.onmousedown=Drag.start;o.hmode=bSwapHorzRef?false:true;o.vmode=bSwapVertRef?false:true;o.root=oRoot&&oRoot!=null?oRoot:o;if(o.hmode&&isNaN(parseInt(o.root.style.left)))o.root.style.left="0px";if(o.vmode&&isNaN(parseInt(o.root.style.top)))o.root.style.top="0px";if(!o.hmode&&isNaN(parseInt(o.root.style.right)))o.root.style.right="0px";if(!o.vmode&&isNaN(parseInt(o.root.style.bottom)))o.root.style.bottom="0px";o.minX=typeof minX!='undefined'?minX:null;o.minY=typeof minY!='undefined'?minY:null;o.maxX=typeof maxX!='undefined'?maxX:null;o.maxY=typeof maxY!='undefined'?maxY:null;o.xMapper=fXMapper?fXMapper:null;o.yMapper=fYMapper?fYMapper:null;o.root.onDragStart=new Function();o.root.onDragEnd=new Function();o.root.onDrag=new Function();},start:function(e)
{var o=Drag.obj=this;e=Drag.fixE(e);var y=parseInt(o.vmode?o.root.style.top:o.root.style.bottom);var x=parseInt(o.hmode?o.root.style.left:o.root.style.right);o.root.onDragStart(x,y);o.lastMouseX=e.clientX;o.lastMouseY=e.clientY;if(o.hmode){if(o.minX!=null)o.minMouseX=e.clientX-x+o.minX;if(o.maxX!=null)o.maxMouseX=o.minMouseX+o.maxX-o.minX;}else{if(o.minX!=null)o.maxMouseX=-o.minX+e.clientX+x;if(o.maxX!=null)o.minMouseX=-o.maxX+e.clientX+x;}
if(o.vmode){if(o.minY!=null)o.minMouseY=e.clientY-y+o.minY;if(o.maxY!=null)o.maxMouseY=o.minMouseY+o.maxY-o.minY;}else{if(o.minY!=null)o.maxMouseY=-o.minY+e.clientY+y;if(o.maxY!=null)o.minMouseY=-o.maxY+e.clientY+y;}
document.onmousemove=Drag.drag;document.onmouseup=Drag.end;return false;},drag:function(e)
{e=Drag.fixE(e);var o=Drag.obj;var ey=e.clientY;var ex=e.clientX;var y=parseInt(o.vmode?o.root.style.top:o.root.style.bottom);var x=parseInt(o.hmode?o.root.style.left:o.root.style.right);var nx,ny;if(o.minX!=null)ex=o.hmode?Math.max(ex,o.minMouseX):Math.min(ex,o.maxMouseX);if(o.maxX!=null)ex=o.hmode?Math.min(ex,o.maxMouseX):Math.max(ex,o.minMouseX);if(o.minY!=null)ey=o.vmode?Math.max(ey,o.minMouseY):Math.min(ey,o.maxMouseY);if(o.maxY!=null)ey=o.vmode?Math.min(ey,o.maxMouseY):Math.max(ey,o.minMouseY);nx=x+((ex-o.lastMouseX)*(o.hmode?1:-1));ny=y+((ey-o.lastMouseY)*(o.vmode?1:-1));if(o.xMapper)nx=o.xMapper(y)
else if(o.yMapper)ny=o.yMapper(x)
Drag.obj.root.style[o.hmode?"left":"right"]=nx+"px";Drag.obj.root.style[o.vmode?"top":"bottom"]=ny+"px";Drag.obj.lastMouseX=ex;Drag.obj.lastMouseY=ey;Drag.obj.root.onDrag(nx,ny);return false;},end:function()
{document.onmousemove=JSGI.handleMouseEvents;document.onmouseup=JSGI.handleMouseEvents;Drag.obj.root.onDragEnd(parseInt(Drag.obj.root.style[Drag.obj.hmode?"left":"right"]),parseInt(Drag.obj.root.style[Drag.obj.vmode?"top":"bottom"]));Drag.obj=null;},fixE:function(e)
{if(typeof e=='undefined')e=window.event;if(typeof e.layerX=='undefined')e.layerX=e.offsetX;if(typeof e.layerY=='undefined')e.layerY=e.offsetY;return e;}};if(!window.SI){var SI={};};SI.Files={htmlClass:'SI-FILES-STYLIZED',fileClass:'file',wrapClass:'cabinet',fini:false,able:false,init:function()
{this.fini=true;var ie=0
if(window.opera||(ie&&ie<5.5)||!document.getElementsByTagName){return;}
this.able=true;var html=document.getElementsByTagName('html')[0];html.className+=(html.className!=''?' ':'')+this.htmlClass;},stylize:function(elem)
{if(!this.fini){this.init();};if(!this.able){return;};elem.parentNode.file=elem;elem.parentNode.onmousemove=function(e)
{if(typeof e=='undefined')e=window.event;if(typeof e.pageY=='undefined'&&typeof e.clientX=='number'&&document.documentElement)
{e.pageX=e.clientX+document.documentElement.scrollLeft;e.pageY=e.clientY+document.documentElement.scrollTop;};var ox=oy=0;var elem=this;if(elem.offsetParent)
{ox=elem.offsetLeft;oy=elem.offsetTop;while(elem=elem.offsetParent)
{ox+=elem.offsetLeft;oy+=elem.offsetTop;};};var x=e.pageX-ox;var y=e.pageY-oy;var w=this.file.offsetWidth;var h=this.file.offsetHeight;this.file.style.top=y-(h/2)+'px';this.file.style.left=x-(w-30)+'px';};},stylizeById:function(id)
{this.stylize(document.getElementById(id));},stylizeAll:function()
{if(!this.fini){this.init();};if(!this.able){return;};var inputs=document.getElementsByTagName('input');for(var i=0;i<inputs.length;i++)
{var input=inputs[i];if(input.type=='file'&&input.className.indexOf(this.fileClass)!=-1&&input.parentNode.className.indexOf(this.wrapClass)!=-1)
{this.stylize(input);};};}};function buildColorMenu(){var colors={Aqua:'#00FFFF',Black:'#000000',Blue:'#0000FF',BlueViolet:'#8A2BE2',Brown:'#A52A2A',BurlyWood:'#DEB887',CadetBlue:'#5F9EA0',Chartreuse:'#7FFF00',Chocolate:'#D2691E',Coral:'#FF7F50',CornflowerBlue:'#6495ED',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',DarkSlateGrey:'#2F4F4F',DarkTurquoise:'#00CED1',DarkViolet:'#9400D3',DeepPink:'#FF1493',DeepSkyBlue:'#00BFFF',DimGray:'#696969',DodgerBlue:'#1E90FF',FireBrick:'#B22222',ForestGreen:'#228B22',Fuchsia:'#FF00FF',Gold:'#FFD700',GoldenRod:'#DAA520',Gray:'#808080',Green:'#008000',GreenYellow:'#ADFF2F',HotPink:'#FF69B4',IndianRed:'#CD5C5C',Indigo:'#4B0082',LawnGreen:'#7CFC00',LightBlue:'#ADD8E6',LightCoral:'#F08080',LightGreen:'#90EE90',LightSalmon:'#FFA07A',LightSeaGreen:'#20B2AA',LightSkyBlue:'#87CEFA',LightSlateGray:'#778899',Lime:'#00FF00',LimeGreen:'#32CD32',Magenta:'#FF00FF',Maroon:'#800000',MediumAquaMarine:'#66CDAA',MediumBlue:'#0000CD',MediumOrchid:'#BA55D3',MediumPurple:'#9370D8',MediumSeaGreen:'#3CB371',MediumSlateBlue:'#7B68EE',MediumSpringGreen:'#00FA9A',MediumTurquoise:'#48D1CC',MediumVioletRed:'#C71585',MidnightBlue:'#191970',Navy:'#000080',Olive:'#808000',OliveDrab:'#6B8E23',Orange:'#FFA500',OrangeRed:'#FF4500',Orchid:'#DA70D6',PaleVioletRed:'#D87093',Peru:'#CD853F',Plum:'#DDA0DD',Purple:'#800080',Red:'#FF0000',RosyBrown:'#BC8F8F',RoyalBlue:'#4169E1',SaddleBrown:'#8B4513',Salmon:'#FA8072',SandyBrown:'#F4A460',SeaGreen:'#2E8B57',Sienna:'#A0522D',Silver:'#C0C0C0',SkyBlue:'#87CEEB',SlateBlue:'#6A5ACD',SlateGray:'#708090',SpringGreen:'#00FF7F',SteelBlue:'#4682B4',Tan:'#D2B48C',Teal:'#008080',Tomato:'#FF6347',Turquoise:'#40E0D0',Violet:'#EE82EE',Yellow:'#FFFF00',YellowGreen:'#9ACD32'};var root=HTML.div("colorPicker");var table=HTML.table();table.className='colorSwatch';table.cellSpacing=1;root.appendChild(table);var tbody=HTML.tableBody();for(var name in colors){var row=HTML.tableRow();var swatchCell=HTML.tableHeadCell();var nameCell=HTML.tableCell();tbody.appendChild(row);row.appendChild(swatchCell);row.appendChild(nameCell);swatchCell.colorHex=colors[name];swatchCell.eventId="setCalendarColor";swatchCell.onmouseover=showColor;swatchCell.onmouseout=revertColor;swatchCell.style.background=colors[name];swatchCell.title=colors[name];nameCell.colorHex=colors[name];nameCell.eventId="setCalendarColor";nameCell.innerHTML=name.replace(/([a-z])([A-Z])/g,"$1 $2");nameCell.onmouseover=showColor;nameCell.onmouseout=revertColor;nameCell.title=colors[name];}
table.appendChild(tbody);return root;}
function showColor(e){var input=lensRef("colorPicker");input.style.backgroundColor=this.colorHex;}
function revertColor(e){var input=lensRef("colorPicker");input.style.backgroundColor=input.originalColor;}
applyTo(ActiveTable.prototype,{grabScrollSlider:function(scrollOrigin){activateLens("dragScroll",this);var virtualHeight=this.scrollGutter.offsetHeight-this.scrollSlider.offsetHeight;this.perRow=virtualHeight/this.dbdata.body.length;this.slideLimit=virtualHeight;this.sliderOffset=scrollOrigin-this.scrollSlider.offsetTop;this.scrollOrigin=scrollOrigin-this.sliderOffset;this.scrollInitRow=this.startRow;this.incrementalMode=true;this.initHeight=this.topPad.offsetHeight;this.scrollGutter.appendChild(this.liveSlider);if(this.displayFormat=="inline"){this.initFormat="inline";this.displayFormat="autoPopup";}},dragScrollSlider:function(evtRef){var coords=JSGI.getCoordinates(evtRef);var pagePosition=coords.top-this.sliderOffset;var deltaY=pagePosition-this.scrollOrigin;var proposedHeight=this.initHeight+deltaY;if(proposedHeight<this.slideLimit&&proposedHeight>-1){jQuery(this.topPad).height(proposedHeight);}
var rowsDragged=parseInt(deltaY/this.perRow);this.startRow=this.scrollInitRow+rowsDragged;if(this.startRow<0){this.startRow=0;}
this.fillTable();},releaseScrollSlider:function(){deactivateLens("dragScroll");if(this.initFormat){this.displayFormat=dataSet.initFormat;}
this.incrementalMode=false;this.fillTable();this.updateNavigation();this.initFormat=null;},fillIncrementally:function(){var deleteRows=true;var ignoreRows=false;var addRows=false;var newCurrentRows=[];this.visibleRows={};for(var i=0,len=this.getLength();i<len;i++){newCurrentRows.push(this.getPaginationPool()[this.startRow+i]);}
var changes=this.extractChanges(this.currentRows,newCurrentRows);if(changes){if(typeof this.incrementalQueue=="undefined"){this.incrementalQueue=[];}
this.incrementalQueue.push(changes);this.intervalId=window.setInterval("try { JSGI.pageElements['"+this.tableId+"'].applyIncrementalChanges() } catch(e){ window.clearInterval("+this.intervalId+") }",100);this.currentRows=newCurrentRows;}},applyIncrementalChanges:function(){if(this.incrementalQueue.length<1){window.clearInterval(this.intervalId);return;}
var changes=this.incrementalQueue.shift();if(changes.direction=="up"){this.setRowNum(this.currentRows[0]);var first=this.tbody.firstChild;while(changes.add.length>0||changes.remove.length>0){this.setRowNum(changes.add.pop());var row=this.getRow();this.tbody.insertBefore(row,first);first=row;this.setRowNum(changes.remove.pop());this.removeRow();}}
else if(changes.direction=="down"){while(changes.add.length>0||changes.remove.length>0){this.setRowNum(changes.add.shift());this.tbody.appendChild(this.getRow());this.setRowNum(changes.remove.shift());this.removeRow();}}
return;},extractChanges:function(oldSet,newSet){var results={};results.add=[];results.remove=[];results.direction=this.determineDragDirection(oldSet,newSet);switch(results.direction){case"up":for(var i=0,len=newSet.length;i<len;i++){if(newSet[i]==oldSet[0]){break;}
else{results.add.push(newSet[i]);}}
results.remove=oldSet.slice(-results.add.length);break;case"down":for(var i=0,len=oldSet.length;i<len;i++){if(oldSet[i]==newSet[0]){break;}
else{results.remove.push(oldSet[i])}}
results.add=newSet.slice(-results.remove.length);break;default:return null;}
return results;},determineDragDirection:function(oldSet,newSet){var oldStart=this.paginationLookup[oldSet[0]];var newStart=this.paginationLookup[newSet[0]];var shift=oldStart-newStart;if(shift>0){return"up";}
else if(shift<0){return"down";}
else{return"steady";}}});applyTo(ActiveTable.prototype,{previewRow:function(rowNum,e){this.rowNum=rowNum;this.clearPreview();this.preview=HTML.div('preview');this.preview.style.position='absolute';this.previewRef=new ActiveTablePreview(rowNum,this);this.previewRef.position(e);HTML.addToBody(this.preview);},positionPreview:function(rowNum,e){this.rowNum=rowNum;if(e.shiftKey&&!this.preview){this.previewRow(rowNum,e);}
this.previewRef.position(e)},clearPreview:function(){try{if(this.preview.parentNode){HTML.remove(this.preview);}}
catch(e){}}});function ActiveTablePreview(rowNum,dataSet){this.rowNum=rowNum;this.table=dataSet;this.build();}
applyTo(ActiveTablePreview.prototype,{build:function(){this.formTable=HTML.table('previewGrid');this.formBody=HTML.tableBody();this.formTable.appendChild(this.formBody);for(var colNum=0,len=this.table.numColumns();colNum<len;colNum++){var column=this.table.column(colNum);if(!this.table.column(colNum).isMeta()){this.formBody.appendChild(this.buildRow(colNum));}}
return this.formTable;},buildRow:function(colNum){this.colNum=colNum;var row=HTML.tableRow();var head=HTML.tableHeadCell();var cell=HTML.tableCell();head.innerHTML=this.table.column(colNum).get('label');var pattern=this.selectPattern(colNum);if(pattern=='_NEW_'){pattern='';}
cell.innerHTML=pattern;addToDOM(row,[head,cell]);return row;},selectPattern:function(colNum){var column=this.table.column(colNum);var pattern=column.get('filterPattern');pattern=this.table.dbdata.resolveExceptions(this.rowNum,column.get('exception'),pattern);pattern=this.table.dbdata.renderPattern(this.rowNum,pattern);return pattern;},position:function(e){var coords=JSGI.getCoordinates(e);var left=coords.left+15;var top=coords.top+8;var viewSize=getViewSize().height;var previewHeight=this.table.preview.offsetHeight;var fromTop=coords.top-getScrollOffset().top;var overFlow=(fromTop+previewHeight)-viewSize;this.table.preview.style.top=(overFlow>0)?(top-overFlow-8):top;this.table.preview.style.left=left;}});var Mouse={map:{},mouseDownStatus:0,dragStatus:0,clickGuard:-1,dragHolder:null,set:function(eventType,eventId,functionObj){if(typeof this.map[eventType]=='undefined'){this.map[eventType]={};}
if(typeof this.map[eventType][eventId]=='undefined'){this.map[eventType][eventId]=[];}
this.map[eventType][eventId].push(functionObj);},click:function(eventId,functionObj){this.set('click',eventId,functionObj);},down:function(eventId,functionObj){this.set('mousedown',eventId,functionObj);},up:function(eventId,functionObj){this.set('mouseup',eventId,functionObj);},dblclick:function(eventId,functionObj){this.set('dblclick',eventId,functionObj);},over:function(eventId,functionObj){this.set('mouseover',eventId,functionObj);},out:function(eventId,functionObj){this.set('mouseout',eventId,functionObj);},move:function(eventId,functionObj){this.set('mousemove',eventId,functionObj);},lookup:function(eventType,eventId){try{var registeredFunctions=this.map[eventType][eventId];}
catch(e){}
if(typeof registeredFunctions=='undefined'||!registeredFunctions||registeredFunctions.length==0){return(JSGI[eventType][eventId])?[JSGI[eventType][eventId]]:[];}
else{return registeredFunctions;}}};var KeyMap={map:{},key:null,set:function(keyName,modifiers,functionObj){var mod=this.setModifiers(modifiers);var shiftKey=mod.SHIFT_KEY;var ctrlKey=mod.CTRL_KEY;if(typeof this.map[keyName]=='undefined'){this.map[keyName]={};}
if(typeof this.map[keyName][shiftKey]=='undefined'){this.map[keyName][shiftKey]={};}
if(typeof this.map[keyName][shiftKey][ctrlKey]=='undefined'){this.map[keyName][shiftKey][ctrlKey]=[];}
this.map[keyName][shiftKey][ctrlKey].push(functionObj);},setModifiers:function(modifiers){var shiftKey=false;var ctrlKey=false;for(var i=0,len=modifiers.length;i<len;i++){var modifier=modifiers[i];if(modifier=='shift'){shiftKey=true;}
else if(modifier=='ctrl'){ctrlKey=true;}
else if(modifier=='*'){shiftKey='*';ctrlKey='*';}}
return{"SHIFT_KEY":shiftKey,"CTRL_KEY":ctrlKey}},lookupEvents:function(eventId){return JSGI['keyup'][eventId];},lookup:function(keyName,shiftKey,ctrlKey){try{return this.map[keyName][shiftKey][ctrlKey];}
catch(e){}}};var ValidationMap={map:{},register:function(table,field,func){if(typeof this.map[table]=='undefined'){this.map[table]={};}
if(typeof this.map[table][field]=='undefined'){this.map[table][field]=[];}
this.map[table][field].push(func);},lookup:function(table,field){try{return this.map[table][field];}
catch(e){}}};function checkValidationMap(dbtable,dbfield,fn){return!ValidationMap.lookup(dbtable,dbfield)||(ValidationMap.lookup(dbtable,dbfield)&&!ValidationMap.lookup(dbtable,dbfield).inArray(fn));}
JSGI.keyup.lookup_users=function(){var args=this.target.value.split(',');var current_lookup=args.last();req=JSGI.ajaxRequest('users');};var doNotValidate=[37,38,39,40];JSGI.validateField=function(Key,target){if(isDropdown(target)||isCheckbox(target)||(isTextEntry(target)&&!doNotValidate.inArray(Key))){var dbField=target.getAttribute("dbfield");var dbTable=target.getAttribute("dbtable");if(!dbTable||!dbField){return;}
var validationFuncs=ValidationMap.lookup(dbTable,dbField);if(validationFuncs){for(var i=0,len=validationFuncs.length;i<len;i++){var validationFunc=validationFuncs[i];var validationName=parseFunctionName(validationFunc);var result=validationFunc(target);if(result.status>2){JSGI.ValidationErrors.add(target,validationName,result.message);}
else{JSGI.ValidationErrors.clear(target,validationName);}}}
if(JSGI.ValidationErrors.invalidField(target)){markInvalid(target);}
else{markValid(target);}}};function getCursorPos(el){var cursorPos=-1;if(document.selection&&document.selection.createRange){var range=document.selection.createRange().duplicate();if(range.parentElement()==el){range.moveStart('textedit',-1);cursorPos=range.text.length;}}
else if(el.selectionEnd){cursorPos=el.selectionEnd;}
return cursorPos;}
function setCursorPos(el,pos){if(el.createTextRange){var range=el.createTextRange();range.collapse(true);range.moveEnd('character',pos);range.moveStart('character',pos);range.select();}
else if(el.selectionEnd){el.selectionEnd=pos;}}
function markInvalid(els,msg,useIcon){if(typeof els=='object'&&typeOf(els)!='array'){els=[els];}
for(var i=0,len=els.length;i<len;i++){var el=els[i];if(jQuery.browser.msie&&isDropdown(el)){var elSpan=el.parentNode;elSpan.style.border='3px solid red';}
else{el.style.border='3px solid red';}
if(msg){if(useIcon){var errorID=el.getAttribute('id')+'_error';var error=ID(errorID);if(!error){error=createElement('span',{id:errorID,cls:'field_error',message:msg});var errorImg=createElement('img',{src:'../jsgi/artwork/error.png'});error.appendChild(errorImg);insertAfter(el,error);addEvent(error,'click',function(){var m=error.getAttribute('message');if(typeof m=='string'){postErrorMessage(m);}
else if(typeof m=='object'&&!isArray(m)){var msgClass=m.cls||'errorMessage';var message=m.message||'Field is invalid.';var timeout=m.timeout||5000;var dismiss=m.dismiss||false;postUserMessage(msgClass,message,timeout,dismiss);}});}
else{error.setAttribute('message',(typeof msg=='string'?msg:msg.message));$(error).show();}}
else{if(typeof msg=='string'){postErrorMessage(msg);}
else if(typeof msg=='object'&&!isArray(msg)){var msgClass=msg.cls||'errorMessage';var message=msg.message||'Field is invalid.';var timeout=msg.timeout||5000;var dismiss=msg.dismiss||false;postUserMessage(msgClass,message,timeout,dismiss);}}}}}
function markValid(els){if(typeof els=='object'&&typeOf(els)!='array'){els=[els];}
for(var i=0,len=els.length;i<len;i++){var el=els[i];if(!jQuery.browser.msie){el.style.border='';}
else{if(isDropdown(el)){var elSpan=el.parentNode;elSpan.style.border='';}
else{el.style.border='1px solid gray';el.style.borderRightColor='silver';el.style.borderBottomColor='silver';el.style.borderLeftColor='gray';}}
var error=ID(el.getAttribute('id')+'_error');if(error){$(error).hide();}}}
function isValid(el){var jsgiErrors=JSGI.ValidationErrors.invalidField(el);var el=(jQuery.browser.msie&&isDropdown(el))?el.parentNode:el;return(el.style.border.match('red')||jsgiErrors)?false:true;}
function checkRequiredElement(el){return(el.getAttribute('required')=='1'&&el.value=='')?false:true;}
function validateForm(formid){var form=document.getElementById(formid);var formElements=form.elements;var allowSubmit=true;var submitForms=true;var checkBoxes=[];disableSubmit(form);for(var i=0,len=formElements.length;i<len;i++){var item=formElements[i];if(item.disabled){continue;}
if(isDatebox(item)&&item.value){JSGI.validateField(null,item);}
if(isCheckbox(item)&&!isChecked(item)){checkBoxes.push(item);}
if(!checkRequiredElement(item)){markInvalid(item);allowSubmit=false;}
if(JSGI.ValidationErrors.invalidField(item)||!isValid(item)){submitForms=false;}}
if(!allowSubmit){postValidationMessage("Please fill in all required fields.");enableSubmit(form);return false;}
if(!submitForms){postValidationMessage("Make sure all fields contain valid data. Invalid fields are marked in red.");enableSubmit(form);return false;}
for(var i=0,len=checkBoxes.length;i<len;i++){setFalseValue(checkBoxes[i]);}}
function setFalseValue(checkBox)
{var hidCheck=document.createElement('input');hidCheck.setAttribute('type','hidden');for(var x in checkBox.attributes){var att=(checkBox.attributes[x]&&checkBox.attributes[x].nodeName)?checkBox.attributes[x].nodeName:null;if(!att||att=='type'||att=='id'){continue;}
var attVal=checkBox.attributes[x].nodeValue;hidCheck.setAttribute(att,(att=='value'||att=='initvalue')?checkBox.getAttribute('falsevalue'):attVal);}
checkBox.parentNode.appendChild(hidCheck);checkBox.setAttribute('name',checkBox.getAttribute('name')+'_check');}
function allowSubmit(){error("Use of Global Function allowSubmit!");submitForms=true;}
function blockSubmit(){error("Use of Global Function blockSubmit!");submitForms=false;}
JSGI.ValidationErrors=function(){return{tree:{},guardedFields:{},getErrorKey:function(itemRef){var table=itemRef.getAttribute("dbtable");var field=itemRef.getAttribute("dbfield");return table+"|"+field;},invalidField:function(itemRef){var errorKey=this.getErrorKey(itemRef);for(var vFunc in this.tree[errorKey]){return true;}
return false;},invalidRecord:function(table,key){var messages=[];for(var errorKey in this.tree){var parts=errorKey.split('|');var dbtable=parts[0];var dbkey=parts[1];var dbfield=parts[2];var messageSet=this.tree[errorKey];if(!messageSet){continue;}
debug(dbtable+":"+table+"; "+dbkey+":"+key);if(dbtable==table&&dbkey==key){info("Found invalidity: "+dbfield);for(var vFunc in messageSet){messages.push(messageSet[vFunc]);}}}
return messages;},add:function(itemRef,validationName,message){var errorKey=this.getErrorKey(itemRef);if(!this.tree[errorKey]){this.tree[errorKey]={};}
this.tree[errorKey][validationName]=message;},clear:function(itemRef,validationName){var errorKey=this.getErrorKey(itemRef);if(this.tree[errorKey]){delete this.tree[errorKey][validationName];}},getMessages:function(itemRef){var msgs=[],msg="";var errorKey=this.getErrorKey(itemRef);if(this.tree[errorKey]){for(var i in this.tree[errorKey]){msgs.push(this.tree[errorKey][i]);}
if(msgs.length>0){for(var i=0,len=msgs.length;i<len;i++){msg+=(msgs[i+1])?msgs[i]+"<br>":msgs[i];}
return msg;}
else{return"At least one field on this page is invalid.";}}},errorCount:function(){var errors=0;for(var errorKey in this.tree){var stack=this.tree[errorKey];for(var validationName in stack){errors++;}}
return errors;},guard:function(key){this.guardedFields[key]=1;},markChecked:function(key){this.guardedFields[key]=2;},clearGuards:function(){this.guardedFields={};},isGuarded:function(key){return this.guardedFields[key]==1;},isGuardedAndChecked:function(key){return this.guardedFields[key]==2;},allGuardsChecked:function(key){for(var i in this.guardedFields){if(this.guardedFields[i]<2){return false;}}
return true;}};}();function validationError(resultStatus,errMessage){return{status:resultStatus,message:errMessage};}
function criticalValidationError(errMessage){return{status:3,message:errMessage};}
function validationClear(){return{status:0,message:''};}
function tagType(target){if(target.nodeName!="INPUT"){return;}
var key=EventDispatcher.Key;if(key>48&&key<58){var real=parseInt(String.fromCharCode(key));var req=JSGI.serverRequest("/tags/add");req.add("baseid",tagRoot);req.add("table",tagTable);req.add("id",tagData[real].id);var newTagId=req.execute();currentTagInput.value=tagData[real].name;cleanupNewTag(newTagId);}
else if(key==188){var req=JSGI.serverRequest("/tags/new");req.add("baseid",tagRoot);req.add("table",tagTable);req.add("value",target.value.replace(",",""));var newTagId=req.execute();currentTagInput.value=currentTagInput.value.replace(",","");cleanupNewTag(newTagId);}
else{var result=quickRequest("/tags/search",{name:target.value});var resultDiv=jQuery('#fetch_results');if(!resultDiv){resultDiv=HTML.div("fetch_results","fetch_results");HTML.addToBody(resultDiv);resultDiv.style.top=getAbsPos(target,"Top")+target.offsetHeight+5;resultDiv.style.left=getAbsPos(target,"Left");}
result=result.split("|||");resultDiv.innerHTML=result[0];JSGI.parseJSON(result[1]);}}
function selectManualTagValue(target){if(tagData&&tagData[1]){var real=parseInt(String.fromCharCode(key));var req=JSGI.serverRequest("/tags/add");req.add("baseid",tagRoot);req.add("table",tagTable);req.add("id",tagData[1].id);var newTagId=req.execute();currentTagInput.value=tagData[real].name;cleanupNewTag(newTagId);}
else{var req=JSGI.serverRequest("/tags/new");req.add("baseid",tagRoot);req.add("table",tagTable);req.add("value",target.value);var newTagId=req.execute();cleanupNewTag(newTagId);}}
function cleanupNewTag(){var next=currentTagInput.parentNode.nextSibling.firstChild;HTML.remove("fetch_results");currentTagInput.parentNode.className="";currentTagInput.parentNode.innerHTML="<div tagid='"+arguments[0]+"' eventid='tagDelete'>"+currentTagInput.value+"</div>";newTag(null,next);return"KILL_EVENTS";}
function tagBlur(e){var target=JSGI.getEventTarget(e);jQuery("#fetch_results").remove();target.parentNode.className="";target.parentNode.innerHTML="<div eventid='tagDelete'>"+target.value+"</div>";}
function setupTagInput(parent,value){var input=HTML.textBox();input.value=value;input.size=12;input.fetch=true;input.url=parent.getAttribute("url")
input.original=value;currentTagInput=input;return input;}
function cancelTag(target){info("cancel this one");jQuery("#fetch_results").remove();var oldValue=target.original;HTML.remove(target.parentNode);return"KILL_EVENTS";}
function selectTagOption(tagName){}
applyTo(JSGI.click,{tagRemove:function(){var tagids=[];for(var i=0,len=tagDeleteQueue.length;i<len;i++){var deletableItem=tagDeleteQueue[i];tagids.push(deletableItem.getAttribute("tagid"));HTML.remove(deletableItem.parentNode);}
var req=JSGI.serverRequest("/tags/delete");req.add("ids",tagids.join(","));req.add("baseid",tagRoot);req.add("table",tagTable);var result=req.execute();},tagadd:function(){var row=this.target.parentNode.parentNode;var newTag=HTML.tag('TD');newTag.className="add";newTag.setAttribute('url',this.target.getAttribute('url'));newTag.eventId="tagDelete";row.insertBefore(newTag,this.target.parentNode);var input=setupTagInput(this.target,"");newTag.appendChild(input);input.focus();},tagDelete:function(){if(this.target.className=="selected"){var newQueue=[];for(var i=0,len=tagDeleteQueue.length;i<len;i++){var item=tagDeleteQueue[i];if(item!=this.target){newQueue.push(item);}}
tagDeleteQueue=newQueue;this.target.className="";this.target.parentNode.className="";}
else{if(typeof tagDeleteQueue=="undefined"){tagDeleteQueue=[];}
tagDeleteQueue.push(target);this.target.className="selected";this.target.parentNode.className="selected";}}});JSGI.Events=function(){var that={},evtRef=null,target=null,eventId=null,eventType=null,eventFunction=null,valid=false,Key=null,shift=false,ctrl=false,KILL=false;that.loadEvent=function(evt){init(evt);}
that.getTarget=function(){return target;}
that.loadKey=function(){if(!valid)
return;Key=document.layers?evtRef.which:document.all?event.keyCode:evtRef.keyCode;shift=evtRef.shiftKey;ctrl=evtRef.ctrlKey;}
that.dispatchKey=function(){try{if(eventId){var tied=KeyMap.lookupEvents(eventId);this.eventFunction=tied;this.evtRef=evtRef;this.target=target;var res=this.eventFunction();}
var filters=KeyMap.lookup(Key,shift,ctrl);for(var i=0,len=filters.length;i<len;i++){if(filters[i](evtRef,target)=="KILL_EVENTS"){KILL=true;break;}}}catch(e){}}
that.dispatchGlobal=function(){if(KILL){KILL=false;return;}
try{var globals=KeyMap.lookup("*","*","*");for(var i=0,len=globals.length;i<len;i++)
globals[i](Key,target);}catch(e){error(e)}}
that.checkLocks=function(){switch(eventType){case"mouseup":if(lensActive("resize"))
AppLens.dataSet.releaseResize(evtRef);if(lensActive("dragScroll"))
AppLens.dataSet.releaseScrollSlider();if(lensActive("colResize"))
AppLens.dataSet.releaseColResize();break;case"mouseover":if(lensActive("pouch")){if(lensRef("pouch").validTarget(target))
target.style.backgroundColor="#FAFF8A";if(target.pouchtype)
lensRef("pouch").highlightValid(target);if(target.eventId=="editCalendarName")
target.style.cursor="pointer";}
if(lensActive("infoPalette")&&target.eventId=="calendarEvent")
lensRef("monthcalendar").getDetailPalette(target.data);break;case"mouseout":if(lensRef("pouch")&&lensRef("pouch").validTarget(target))
target.style.backgroundColor="";if(lensActive("infoPalette")&&target.eventId=="calendarEvent")
lensRef("monthcalendar").getDetailPalette();break;case"mousemove":if(lensActive("resize"))
AppLens.dataSet.dragResize(evtRef);if(lensActive("dragScroll"))
AppLens.dataSet.dragScrollSlider(evtRef);if(lensActive("colResize"))
AppLens.dataSet.dragColResize(evtRef);if(lensActive("pouch")){lensRef("pouch").position(evtRef);}
if(evtRef.shiftKey&&evtRef.ctrlKey&&!lensActive("pouch")){var pouch=new Pouch();pouch.position(this.evtRef);}
break;}}
that.forwardEvent=function(newEventId){eventId=newEventId;this.dispatchMouse();}
that.dispatchMouse=function(){try{if(isDropdown(target)&&target.getAttribute("dbfield")&&!target.onchange){target.onchange=JSGI.markDirty;}
if(typeof eventId!="undefined"||!eventId){if(lensActive("eventdebug"))
lensRef("eventdebug").innerHTML="EventId = "+eventId;var events=parseEvents();for(var i=0,len=events.length;i<len;i++){var eventToProcess=events[i];var filters=Mouse.lookup(eventType,eventToProcess);for(var i=0,len=filters.length;i<len;i++){this.eventFunction=filters[i];this.evtRef=evtRef;this.target=target;var res=this.eventFunction();if(!res)
break;}}}}catch(e){}}
function init(evt){try{evtRef=(evt)?evt:((event)?event:null);target=(evtRef.target)?evtRef.target:((evtRef.srcElement)?evtRef.srcElement:null);eventId=(target.eventId)?target.eventId:target.getAttribute("eventid");eventType=evtRef.type;valid=true;}catch(e){warn(e);valid=false}}
function parseEvents(){var events=eventId.split(",");var validEvents=[];for(var i=0,len=events.length;i<len;i++){var eventStr=events[i];if(eventStr.match(/\+/)){var eventParts=eventStr.split("+");var guard=eventParts[1];var realEvent=eventParts[0];if(lensActive(guard))
validEvents.push(realEvent);}else if(eventStr.match(/\-/)){var eventParts=eventStr.split("-");var guard=eventParts[1];var realEvent=eventParts[0];if(!lensActive(guard))
validEvents.push(realEvent);}else
validEvents.push(eventStr);}
return validEvents;}
return that;}();JSGI.handleMouseEvents=function(evt){JSGI.Events.loadEvent(evt);if(isDropdown(JSGI.Events.getTarget())&&JSGI.Events.getTarget().getAttribute("dbtable")&&!JSGI.Events.getTarget().onchange){JSGI.Events.getTarget().onchange=JSGI.markDirty;}
JSGI.Events.checkLocks();JSGI.Events.dispatchMouse();}
JSGI.handleKeyEvents=function(keyStroke){JSGI.Events.loadEvent(keyStroke);JSGI.Events.loadKey();JSGI.Events.dispatchKey();JSGI.Events.dispatchGlobal();}
document.onclick=JSGI.handleMouseEvents;document.ondblclick=JSGI.handleMouseEvents;document.onmouseover=JSGI.handleMouseEvents;document.onmouseout=JSGI.handleMouseEvents;document.onmousedown=JSGI.handleMouseEvents;document.onmousemove=JSGI.handleMouseEvents;document.onmouseup=JSGI.handleMouseEvents;document.onkeyup=JSGI.handleKeyEvents;JSGI.applyWheel=function(delta){JSGI.hoveredTable.rowNum=JSGI.hoveredTable.startRow;if(delta<0){var nextRow=JSGI.hoveredTable.startRow+1;if(!isNaN(nextRow)&&nextRow>-1){JSGI.hoveredTable.startRow=nextRow;JSGI.hoveredTable.fillTable();JSGI.hoveredTable.updateNavigation();}}
else{var prevRow=JSGI.hoveredTable.startRow-1;if(!isNaN(prevRow)&&prevRow>-1){JSGI.hoveredTable.startRow=prevRow;JSGI.hoveredTable.fillTable();JSGI.hoveredTable.updateNavigation();}}}
JSGI.wheel=function(event){var delta=0;if(!event){event=window.event;}
if(event.wheelDelta){delta=event.wheelDelta/120;if(window.opera){delta=-delta;}}
else if(event.detail){delta=-event.detail/3;}
if(delta&&JSGI.hoveredTable){JSGI.applyWheel(delta);}
if(event.preventDefault&&JSGI.hoveredTable){event.preventDefault();}
event.returnValue=false;}
if(window.addEventListener){window.addEventListener('DOMMouseScroll',JSGI.wheel,false);}
window.onmousewheel=document.onmousewheel=JSGI.wheel;function lensActive(name){return AppLens.isLocked(name);}
function activateLens(name,dataSet){AppLens.lock(name,dataSet);}
function deactivateLens(name){AppLens.unlock(name);}
function lensRef(name){return AppLens.ref(name);}
var AppLens={locks:{"resize":false,"scroll":false,"scrollDown":false,"scrollUp":false,"colResize":false,"weekcalendar":false,"daycalendar":false,"eventdetail":false,"draggedEvent":false},dataSet:null,refs:{},ref:function(lockName){return this.refs[lockName];},lock:function(lockName,dataSet){this.locks[lockName]=true;this.dataSet=dataSet;this.refs[lockName]=dataSet;},unlock:function(lockName){this.locks[lockName]=false;this.dataSet=null;},isLocked:function(lockName){return this.locks[lockName];}};ProblemAnalysis={issues:{},displayMenu:function(){for(name in JSGI.pageElements){this.checkJSGI(name);if(this.isTable(name)){this.checkSort(name);}
if(this.isTable(name)){this.checkFilter(name);}
this.checkPaternFields(name);this.checkKeys(name);}
this.showReport();},checkJSGI:function(name){var displayPatterns=this.getDisplayPatterns(name);for(var i=0,len=displayPatterns.length;i<len;i++){var pattern=this._renderPattern(displayPatterns[i]);var items=this._extractFormItems(pattern);var label=this.getColumnLabels(name)[i];for(var j=0,len2=items.length;j<len2;j++){var item=items[j];if(item.type&&(item.type=="image"||item.type=="submit"||item.type=="button"||item.type=="hidden")){continue;}
if(!this.validateDbTable(item)){this.addIssue("JSGI",name,"An item in column '"+label+"' is missing the dbtable attribute");}
if(!this.validateDbField(item)){this.addIssue("JSGI",name,"An item in cloumn '"+label+"' is missing the dbfield attribute");}}}},checkAJAX:function(name){var ajaxItems={};var displayPatterns=this.getDisplayPatterns(name);for(var i=0,len=displayPatterns.length;i<len;i++){var pattern=this._renderPattern(displayPatterns[i]);var items=this._extractFormItems(pattern);var label=this.getColumnLabels(name)[i];for(var j=0,len2=items.length;j<len2;j++){var item=items[j];if(!this.validateDbTable(item)){this.addIssue("AJAX",name,"An item in column '"+label+"' is missing the dbtable attribute");}
if(!this.validateDbField(item)){this.addIssue("AJAX",name,"An item in cloumn '"+label+"' is missing the dbfield attribute");}}}},checkSort:function(name){var sortPatterns=this.getSortPatterns(name);for(var i=0,len=sortPatterns.length;i<len;i++){var sortTypes=this.getSorts(name);if(sortTypes[i]=='nosort'){continue;}
var pattern=this._renderPattern(sortPatterns[i]);var items=this._extractFormItems(pattern);var label=this.getColumnLabels(name)[i];if(items.length>0){this.addIssue("Sort",name,"The sort pattern in column '"+label+"' contains form items, which may cause sorts to fail.");}}},checkFilter:function(name){var filterPatterns=this.getFilterPatterns(name);for(var i=0,len=filterPatterns.length;i<len;i++){var pattern=this._renderPattern(filterPatterns[i]);var items=this._extractFormItems(pattern);var label=this.getColumnLabels(name)[i];if(items.length>0){this.addIssue("Filter",name,"The filter pattern in column '"+label+"' contains form items, which may cause irregularities.");}}},checkPaternFields:function(name){var patterns=this.getDisplayPatterns(name);var summarizePossibleData=false;for(var i=0,len=patterns.length;i<len;i++){var label=this.getColumnLabels(name)[i];var pattern=patterns[i];var foundFields=this._scanPatternForFields(pattern);var availableFields=this.getHeaderHash(name);for(fieldName in foundFields){if(!availableFields[fieldName]){summarizePossibleData=true;this.addIssue("Pattern Field",name,"The pattern for column '"+label+"' requests the database field '"+fieldName+"', which is not provided by the data query.");}}}
if(summarizePossibleData){var headerList=JSGI.pageElements[name].dbdata.header.join(", ");this.addIssue("Pattern Field",name,"Possible data values include:"+headerList);}},checkKeys:function(name){if(!this.isTable(name)&&JSGI.pageElements[name].hasButtons){return;}
var keys=this.getKeys(name);var foundValues={};for(var i=0,len=keys.length;i<len;i++){var key=keys[i];if(key==""){this.addIssue("Database Keys",name,"The database key field in row "+i+" is blank. That's probably not a good thing.");}
if(!foundValues[key]){foundValues[key]=0;}
foundValues[key]++;}
for(var value in foundValues){var count=foundValues[value];if(count>1&&value!="_NEW_"){this.addIssue("Database Key",name,"The database key field has multiple rows with the value '"+value+"', which will cause issues when saving.");}}
var keyPattern=keyFieldPattern.replace("|tableName|",name);var fieldNum=JSGI.pageElements[name].dbdata.headerLookup[keyPattern];if(typeof fieldNum=="undefined"){this.addIssue("Database Key",name,"Check your query. The database table is called '"+name+"', but there is no field called '"+keyPattern+"' You may have a typo in either the keyfield or the table's name. This may be intentional.");}},showReport:function(){if(!this.issues){return;}
if(document.getElementById("analysisMenu")){return;}
var box=HTML.div("analysisMenu","analysisMenu");var menu=HTML.tag("dl");var jsgiHeader=HTML.tag("DT");var close=Images.get('close');close.setAttribute("eventid","closeAnalysis");jsgiHeader.appendChild(close);jsgiHeader.innerHTML+=" Potential Problems on this Page";box.appendChild(menu);menu.appendChild(jsgiHeader);for(var category in this.issues){var categoryHeader=HTML.tag("DT");categoryHeader.innerHTML=category+" Issues";menu.appendChild(categoryHeader);for(var setName in this.issues[category]){var setHeader=HTML.tag("dd");setHeader.innerHTML="<em>"+this.getSetType(setName)+" : "+this.getLabel(setName)+"</em>";menu.appendChild(setHeader);var issues=this.issues[category][setName];for(var i=0,len=issues.length;i<len;i++){var issue=issues[i];var item=HTML.tag("dd");item.innerHTML=(i+1)+". "+issue;menu.appendChild(item);}}}
box.style.backgroundColor="white";box.style.border="1px solid black";box.style.position="absolute";box.style.top="100px";box.style.width="500px";box.style.height="400px";box.style.overflow="auto";box.style.left="100px";box.style.zIndex="1000";box.style.cursor="default";HTML.addToBody(box);Drag.init(box);},removeReport:function(){jQuery("#analysisMenu").remove();this.issues={};},addIssue:function(category,set,issue){if(typeof this.issues[category]=="undefined"){this.issues[category]={};}
if(typeof this.issues[category][set]=="undefined"){this.issues[category][set]=[];}
this.issues[category][set].push(issue);},validateDbTable:function(item){if(item.type&&(item.type=="button"||item.type=="submit"||item.type=="reset")){return true;}
return(item.getAttribute("dbtable")!=null);},validateDbField:function(item){if(item.type&&(item.type=="button"||item.type=="submit"||item.type=="reset")){return true;}
return(item.getAttribute("dbfield")!=null);},validateAjaxId:function(item){return(item.getAttribute("ajaxid")!=null);},validateAjaxRequestId:function(item){return(item.getAttribute("requestid")!=null);},validatePatternFieldsPresent:function(pattern){return(item.getAttribute("responseid")!=null);},isTable:function(name){return(JSGI.pageElements[name].setType=="table");},getSetType:function(name){return this.isTable(name)?"Table":"Form";},getDisplayPatterns:function(name){var set=JSGI.pageElements[name];return(set.setType=="table")?set.columnValues("columnPattern"):set.fields;},getSorts:function(name){var set=JSGI.pageElements[name];if(set.setType=='table'){return set.columnValues("sortType");}},getSortPatterns:function(name){var set=JSGI.pageElements[name];if(set.setType=='table'){return set.columnValues("sortPattern");}},getFilterPatterns:function(name){var set=JSGI.pageElements[name];if(set.setType=='table'){return set.columnValues("filterPattern");}},getHeaders:function(name){var set=JSGI.pageElements[name];return set.dbdata.header;},getHeaderHash:function(name){var headers=this.getHeaders(name);var headerHash={};for(var i=0,len=headers.length;i<len;i++){headerHash[headers[i]]=1;}
return headerHash;},getColumnLabels:function(name){var set=JSGI.pageElements[name];return(set.setType=="table")?set.labels:set.titles;},getLabel:function(name){var set=JSGI.pageElements[name];return set.label;},getKeys:function(name){var set=JSGI.pageElements[name];var keys=[];for(var i=0,len=set.dbdata.body.length;i<len;i++){keys.push(set.dbdata.getKey(null,i));}
return keys;},_renderPattern:function(pattern){var re=/\|(\w+)\|/g;var newPattern=pattern;while(result=re.exec(pattern)){newPattern=newPattern.replace(result[0],"dummy-text");}
return newPattern;},_scanPatternForFields:function(pattern){var re=/\|(\w+)\|/g;var foundFields={};while(result=re.exec(pattern)){foundFields[result[1]]=1;}
return foundFields;},_extractFormItems:function(pattern){var div=HTML.div();div.style.visiblity="hidden";div.innerHTML=pattern;HTML.addToBody(div);var inputs=div.getElementsByTagName("INPUT");var drops=div.getElementsByTagName("SELECT");HTML.remove(div);return(inputs||drops)?[].merge(inputs,drops):[];}};JSGI.fieldConfig=function(table,field){var req=JSGI.serverRequest(fieldConfigService);req.add('table',table);req.add('field',field);req.getJSON(function(json){info("Field Config!");info(json);JSGI.jsonData=json;});return JSGI.jsonData;};function retrieveEvents(start,end){var req=JSGI.serverRequest(eventQueryLocation);req.add('start',start);if(end){req.add('end',end);}
return req.getDbData();}
function eventBox(data){var box=HTML.div('calendarEventBox');box.data=data;box.dbid=data.id;var list=new DefinitionList();var grab=Images.get('grabLight');box.pouchtype='event';grab.eventId='pouch';grab.pouchRef=box;var remove=HTML.div();remove.innerHTML='X';remove.eventId='deleteEvent';remove.dbid=data.event_calendar_id;remove.eventNode=box;remove.style.color='white';remove.style.float='right';remove.style.textAlign='right';remove.style.marginTop='-1.3em';remove.style.cursor='pointer';if(data.duration>30||!arguments[1]){var title=list.addTitle();var body=list.addItem();if(data.read_only!=1){title.appendChild(grab);}
title.appendChild(HTML.textNode(formatTimeString(data.starttime,data.duration)));title.appendChild(remove);title.style.backgroundColor=data.color;body.innerHTML=data.name;body.eventId='calendarEvent';body.dbid=data.id;body.data=data;box.appendChild(list.markup());}
else{var title=list.addTitle();if(data.read_only!=1){title.appendChild(grab);}
title.appendChild(HTML.textNode(formatTimeString(data.starttime,data.duration)));title.appendChild(remove);title.style.backgroundColor=data.color;box.appendChild(list.markup());}
box.switchCalendar=function(calId,newColor){var req=JSGI.ajaxRequest();req.setTable('event_calendars');req.add('event_id',this.dbid);var data=req.getDbData();var row=data.getRowHash(0);var id=row.id
JSGI.CRUD.update('event_calendars','calendar_id',row.id,calId);var updated=JSGI.ajaxRequest('calendars');updated.add('id',calId);var data=updated.getDbData();var row=data.getRowHash(0);newColor=row.color;this.recolor(newColor);this.sendHome();};box.recolor=function(newColor){var dt=this.getElementsByTagName('DT')[0];dt.style.backgroundColor=newColor;};box.sendHome=function(){var dt=parseDate(this.data.startdate);var cell=this.cal.cells[dt.month+'-'+dt.day];cell.appendChild(box);};return box;}
function shiftHex(hexNum){nums=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','F','F','F','F','F','F','F','F','F','F','F','F','F','F'];var newHex='';for(var i=0,len=hexNum.length;i<len;i++){var chr=hexNum[i];if(chr=='#'||chr=='F'){newHex+=chr;}
else{for(var j=0,len2=nums.length;j<len2;j++){if(chr==nums[j]){newHex+=nums[j+12];break;}}}}
return newHex;}
function formatDateString(dateStr){parts=dateStr.split('-');var month=parseInt(parts[1],10);var day=parseInt(parts[2],10);var year=parts[0];return month+' / '+day+' / '+year;}
function parseDate(dateStr){parts=dateStr.split('-');var month=parseInt(parts[1],10);var day=parseInt(parts[2],10);var year=parts[0];var date=new Date(month,day,year);return{month:month,day:day,year:year};}
function formatTimeString(time,duration){var parts=time.split(':');var hour=parts[0]||'00';var minute=parts[1]||'00';var meridian='am';if(hour>=12){meridian='pm';hour-=12;if(hour==0){hour=12;}}
if(minute.toString().length==1){minute='0'+minute;}
var endHour=parseInt(hour);var endMinute=parseInt(minute);var endMeridian=meridian;var hourShift=parseInt(duration/60);var minuteShift=duration%60;endHour+=hourShift;endMinute+=minuteShift;if(endMinute==0){endMinute='00';}
if(endHour>=12){endMeridian='pm';endHour-=12;if(endHour==0){endHour=12;}}
return hour+':'+minute+' '+meridian;}
function checkTime(target){var value=getFormItemValue(target);var re=/^(0?[0-9]|1[0-9]|2[0-3]):?([0-5][0-9])?:?([0-5][0-9])?\s?(a|am|p|pm)?$/i;if(value.match(re)){return validationClear();}
else{return criticalValidationError('Time is not properly formatted.');}}
function formatTime(time){if(time==''){return'';}
var re=/^(0?[0-9]|1[0-9]|2[0-3]):?([0-5][0-9])?:?([0-5][0-9])?\s?(a|am|p|pm)?$/i;var result=time.match(re);if(result){var hours=result[1];var minutes=result[2]||'00';var seconds=result[3]||'00';var meridian=result[4]||'AM';if(meridian){meridian=meridian.replace(/a$|am/i,'AM').replace(/p$|pm/i,'PM');}
var intHours=parseInt(hours,10);if(intHours<12&&intHours>0&&meridian=='PM'){hours=''+(intHours+12);}
return hours+':'+minutes+':'+seconds;}}
function EventEditor(dbid,originalText){var editor=JSGI.EventEditor(dbid);if(arguments[2]){editor.loadDate(arguments[2],arguments[3],arguments[4],arguments[5]);}
if(dbid=='_NEW_'){var ajaxReq=JSGI.ajaxRequest('events');ajaxReq.setJob('spoof');editor.setData(ajaxReq.getDbData());editor.addButton('Save','saveEventAdd');JSGI.incrementCounter('New Events');}
else{var ajaxReq=JSGI.ajaxRequest('events');ajaxReq.add('id',dbid);info(ajaxReq.getDbData());editor.setData(ajaxReq.getDbData());editor.addButton('Save','saveEventEdit');}
editor.addFieldConfig('events','name');editor.addFieldConfig('events','startdate');editor.addFieldConfig('events','starttime');editor.addFieldConfig('events','duration');editor.addFieldConfig('events','description');editor.setOriginalText(originalText);return editor.build();}
JSGI.EventEditor=function(id){var that={},buttons={},pairs={},url,args={},root,dbdata,originalText,hiddens={},recordId=id,defaultMonth,defaultDay,defaultYear,defaultTime,dateField;function build(){var grid,heading,tbody;root=HTML.div('sheet');grid=HTML.table();tbody=HTML.tableBody();grid.appendChild(tbody);for(var label in pairs){tbody.appendChild(buildHeadRow(label));tbody.appendChild(buildBodyRow(pairs[label]));}
root.appendChild(grid);root.appendChild(buildButtons());JSGI.incrementCounter(counterName());root.dateField=dateField;return root;}
function buildRow(label,content){var row=HTML.tableRow();var cell=HTML.tableCell();var head=HTML.tableHeadCell();head.innerHTML=label;var swapped=dbdata.renderPattern(0,content);cell.appendChild(nodify(swapped));row.appendChild(head);row.appendChild(cell);return row;}
function buildHeadRow(label){var row=HTML.tableRow();var head=HTML.tableHeadCell();head.innerHTML=label;row.appendChild(head);return row;}
function buildBodyRow(content){var row=HTML.tableRow();var cell=HTML.tableCell();var swapped=dbdata.renderPattern(0,content);if(dbdata.getRowHash(0).read_only!='1'){var node=nodify(swapped);node.stackName=(recordId=='_NEW_')?'newevent-'+JSGI.currentCount('New Events'):'event-'+recordId;node.rowNum=0;cell.appendChild(node);row.appendChild(cell);if(node.getAttribute('dbfield')=='startdate'){if(defaultYear){var dateString=getDate();node.value=dateString;processChange(node);}}
else if(node.getAttribute('dbfield')=='starttime'){if(defaultTime){node.value=defaultTime;processChange(node);}
activateTimebox(node);}
if(node.value&&node.value=='_NEW_'){node.value='';}}
else{cell.innerHTML=swapped;row.appendChild(cell);}
return row;}
function getDate(){var dateString=defaultYear+'-';if((defaultMonth+1).toString().length==1){dateString+='0'+(defaultMonth+1);}
else{dateString+=(defaultMonth+1).toString();}
dateString+='-';if(defaultDay.toString().length==1){dateString+='0'+defaultDay;}
else{dateString+=defaultDay.toString();}
return dateString;}
function buildButtons(){var buttonsBox=HTML.div('bottom_buttons');var cancelLabel=(dbdata.getRowHash(0).read_only!='1')?'Cancel':'Close';var cancel=HTML.button(cancelLabel);cancel.eventId='cancelEventEdit';cancel.sheet=that;buttonsBox.appendChild(cancel);if(dbdata.getRowHash(0).read_only!='1'){for(var label in buttons){var button=HTML.button(label);button.eventId=buttons[label];button.sheet=that;buttonsBox.appendChild(button);}}
return buttonsBox;}
function nodify(txt){var div=HTML.div();div.innerHTML=txt;return div.firstChild;}
that.addFieldConfig=function(table,field){var fc;fc=JSGI.fieldConfig(table,field);if(dbdata.getRowHash(0).read_only=='1'){pairs[fc.label]=dbdata.getRowHash(0)[field];}
else{pairs[fc.label]=fc.item;}};that.setData=function(data){dbdata=data;};that.addItem=function(label,item){if(typeof item.nodeType=='undefined'){item=HTML.textNode(item);}
pairs[label]=item;};that.addButton=function(label,eventid){buttons[label]=eventid;};that.addHidden=function(name,value){hiddens[name]=value;};that.build=function(){return build();};that.getKey=function(){return(recordId=='_NEW_')?'newevent-'+JSGI.currentCount('New Events'):'event-'+recordId;};that.getRoot=function(){return root;};that.setOriginalText=function(txt){originalText=txt;};that.loadDate=function(month,day,year,time){defaultMonth=month;defaultDay=day;defaultYear=year;if(time){defaultTime=time;}};that.openEditors=function(){return JSGI.currentCount(counterName())>0;};that.cleanUpSave=function(){JSGI.decrementCounter(counterName());if(this.openEditors()){var inputs=root.getElementsByTagName('input');for(var i=0,len=inputs.length;i<len;i++){if(inputs[i].getAttribute('dbfield')=='name'){root.parent.innerHTML=inputs[i].value;return;}}}
else{redrawCalendar();}};that.cleanUpAdd=function(){destroyAddForm();redrawCalendar();};function destroyAddForm(){jQuery(root).hide('fast');}
function redrawCalendar(){if(lensActive('daycalendar')){lensRef('daycalendar').build();}
if(lensActive('monthcalendar')){lensRef('monthcalendar').build();}}
function counterName(){if(lensActive('daycalendar')){return'dayeditor';}
else if(lensActive('monthcalendar')){return'montheditor';}}
that.cleanUpCancel=function(){JSGI.decrementCounter(counterName());this.openEditors()?root.parent.innerHTML=originalText:redrawCalendar();};return that;};function MonthCalendar(anchorId,dataSourcePath){this.months=["Jan","Feb","March","April","May","June","July","Aug","Sept","Oct","Nov","Dec"];this.weekdays=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];this.anchor=document.getElementById(anchorId);this.today=new Date();if(dataSourcePath.length>0){eventQueryLocation=dataSourcePath;}
this.build();this.getPalette();}
MonthCalendar.prototype.build=function(){this.determineDays();this.daysGrid=this.makeGrid();this.anchor.innerHTML="";this.getNavigation(this.today.getMonth(),this.today.getFullYear());this.anchor.appendChild(this.daysGrid);this.loadEvents();activateLens("monthcalendar",this);}
MonthCalendar.prototype.loadEvents=function(){var result=retrieveEvents(this.getFormattedDate(0),this.getFormattedDate(this.days.length-1));if(!result.header)
return;var events=result;var dataSet=new DbData(events);this.eventData=dataSet;this.eventBoxes={};this.allEvents=[];for(var i=0,len=dataSet.numRows();i<len;i++){var row=dataSet.getRowHash(i);var box=new eventBox(row);this.eventBoxes[row.id]=box;this.allEvents.push(box);box.cal=this;var dt=parseDate(row.startdate);var cell=this.cells[dt.month+'-'+dt.day];cell.appendChild(box);}}
MonthCalendar.prototype.getFormattedDate=function(dayNumber){var date=this.days[dayNumber];year=date.year;month=(date.month+1).toString().length==1?"0"+(date.month+1):(date.month+1)+"";day=(date.day).toString().length==1?"0"+date.day:date.day+"";return year+'-'+month+'-'+day;}
MonthCalendar.prototype.determineDays=function(){this.days=[];var newCal=new Date((this.today.getMonth()+1)+'/01/'+this.today.getFullYear());var startDay=newCal.getDay();var intDaysInMonth=this.getDays(newCal.getMonth(),newCal.getFullYear());var dayOfMonthOfFirstSunday=(7-startDay+1);var month=this.today.getMonth();var year=this.today.getFullYear();var dayOfMonth=0;for(var intWeek=0;intWeek<6;intWeek++){for(var intDay=0;intDay<7;intDay++){dayOfMonth=(intWeek*7)+intDay+dayOfMonthOfFirstSunday-7;if(dayOfMonth<=0){if(month==0){subMonth=11;subYear--;}else{var subMonth=month-1;var subYear=year;}
var subDay=this.getDays(subMonth,year)+dayOfMonth;var type="off";}else if(dayOfMonth>this.getDays(month,year)){var subDay=dayOfMonth-this.getDays(month,year)-7;var subMonth=month+1;var subYear=year;if(month==11){subMonth=0;subYear++;}
var type="off";}else{var subDay=dayOfMonth;var subMonth=month;var subYear=year;if(dayOfMonth==intDaysInMonth)
intWeek++;var type="on";}
this.days.push({month:subMonth,day:subDay,year:subYear,type:type});}}}
MonthCalendar.prototype.makeGrid=function(){var daysGrid=HTML.table();daysGrid.cellSpacing=0;var month=this.today.getMonth();var year=this.today.getFullYear();daysGrid.appendChild(this.header(this.today.getMonth(),this.today.getFullYear()));var body=HTML.tableBody();this.cells={};var i=0;while(i<this.days.length){var entry=this.days[i];var bodyRow=HTML.tableRow();bodyRow.vAlign="top";for(var j=0;j<7;j++){entry=this.days[i];if(entry.type=="on")
var cell=this.getMonthCell(entry.month,entry.day,entry.year);else
var cell=this.getOffMonthCell(entry.month,entry.day,entry.year);this.cells[(entry.month+1)+'-'+entry.day]=cell;bodyRow.appendChild(cell);i++;}
body.appendChild(bodyRow);}
daysGrid.appendChild(body);return daysGrid;}
MonthCalendar.prototype.getDays=function(month,year){daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];if(1==month)
return((0==year%4)&&(0!=(year%100)))||(0==year%400)?29:28;else
return daysInMonth[month];}
MonthCalendar.prototype.incMonth=function(delta){var currMonth=this.today.getMonth();debug("curr month:"+currMonth);currMonth+=delta;debug("now: "+currMonth);if(currMonth>=12){currMonth=0;this.incYear(1);}else if(currMonth==-1){currMonth=11;this.incYear(-1);}
var daysInNewMonth=this.getDays(currMonth,this.today.getYear());debug("Days in new Month:"+daysInNewMonth);debug("Curr Date:"+this.today.getDate());if(this.today.getDate()>daysInNewMonth)
this.today.setDate(daysInNewMonth);this.today.setMonth(currMonth);debug("Curr Date:"+this.today.getDate());this.build();}
MonthCalendar.prototype.incYear=function(delta){var currYear=this.today.getFullYear();currYear+=delta;this.today.setYear(currYear);this.build();}
MonthCalendar.prototype.getNavigation=function(month,year){if(this.navigation){HTML.remove(this.navigation);}
this.navigation=HTML.table();var tbody=HTML.tableBody();this.anchor.parentNode.appendChild(this.navigation);this.navigation.cellSpacing="0";var row=HTML.tableRow();row.vAlign="bottom";this.navigation.className="month_controls";var monthCell=HTML.tableCell();var yearCell=HTML.tableCell();var filterCell=HTML.tableCell();filterCell.style.textAlign="right";var filterCloseCell=HTML.tableCell();monthCell.appendChild(this.decreaseMonthControl());monthCell.appendChild(this.monthLabel(month));monthCell.appendChild(this.increaseMonthControl());yearCell.appendChild(this.decreaseYearControl());yearCell.appendChild(this.yearLabel(year));yearCell.appendChild(this.increaseYearControl());filterCell.appendChild(this.getFilter());filterCloseCell.appendChild(this.getFilterClose());filterCloseCell.style.width="20px";filterCloseCell.style.paddingTop="10px";filterCloseCell.style.paddingLeft="5px";row.appendChild(monthCell);row.appendChild(yearCell);row.appendChild(filterCell);row.appendChild(filterCloseCell);tbody.appendChild(row);this.navigation.appendChild(tbody);}
MonthCalendar.prototype.header=function(month,year){var head=HTML.tableHead();var weekRow=HTML.tableRow();weekRow.className="weekdays";for(var i=0,len=this.weekdays.length;i<len;i++){var weekdayCell=HTML.tableHeadCell();weekdayCell.innerHTML=this.weekdays[i];weekRow.appendChild(weekdayCell);}
head.appendChild(weekRow);return head;}
MonthCalendar.prototype.controlsSpacer=function(){var cell=HTML.tableHeadCell();cell.innerHTML="&nbsp;";return cell;}
MonthCalendar.prototype.monthLabel=function(month){var cell=HTML.tableHeadCell();cell.style.textAlign='center';var monthLabel=HTML.tag("STRONG");monthLabel.innerHTML=this.months[month];return monthLabel}
MonthCalendar.prototype.decreaseMonthControl=function(){var cell=HTML.tableHeadCell();cell.style.textAlign="right"
cell.colSpan=2
var decreaseMonth=HTML.blankButton(this.months[this.today.getMonth()-1]);decreaseMonth.eventId="decreaseMonth";decreaseMonth.cal=this;return decreaseMonth;}
MonthCalendar.prototype.increaseMonthControl=function(){var cell=HTML.tableHeadCell();cell.style.textAlign="left";var advanceMonth=HTML.blankButton(this.months[this.today.getMonth()+1]);advanceMonth.eventId="advanceMonth";advanceMonth.cal=this;return advanceMonth;}
MonthCalendar.prototype.yearLabel=function(year){var cell=HTML.tableHeadCell();cell.style.textAlign="center";var yearLabel=HTML.tag("STRONG");yearLabel.innerHTML=year;return yearLabel;}
MonthCalendar.prototype.decreaseYearControl=function(){var decreaseYear=HTML.blankButton(this.today.getFullYear()-1);decreaseYear.eventId="decreaseYear";decreaseYear.cal=this;return decreaseYear;}
MonthCalendar.prototype.increaseYearControl=function(){var advanceYear=HTML.blankButton(this.today.getFullYear()+1);advanceYear.eventId="advanceYear";advanceYear.cal=this;return advanceYear;}
function calendarFilterType(evtRef,target){if(target.calFilter)
target.cal.applyFilter();}
MonthCalendar.prototype.getFilter=function(){this.filter=HTML.textBox();this.filter.value="Filter Events";this.filter.className="calendarFilter";this.filter.cal=this;this.filter.calFilter=true;this.filter.onfocus=function(e){var target=JSGI.getEventTarget(e);if(target.value=="Filter Events"){target.value="";target.style.color="#000";target.cal.filterClose.style.display="";}}
this.filter.onblur=function(e){var target=JSGI.getEventTarget(e);if(target.value==""){target.cal.clearFilter();}}
return this.filter;}
MonthCalendar.prototype.getFilterClose=function(){this.filterClose=Images.get("clearButton");this.filterClose.eventId="clearCalFilter";this.filterClose.className="calendarFilterClose";this.filterClose.style.display="none";this.filterClose.cal=this;return this.filterClose;}
MonthCalendar.prototype.applyFilter=function(){for(var i=0,len=this.eventData.body.length;i<len;i++){var text=this.eventData.body[i].join(" ").toLowerCase();var row=this.eventData.getRowHash(i);var text=row.name.toLowerCase()+" "+row.starttime;var box=this.eventBoxes[row.id];info("Filter Box:"+text+" vs. "+this.filter.value);if(text.match(this.filter.value)||this.filter.value==""){info("Box Matches.")
jQuery(box).fadeTo("fast",1.0);}else if(jQuery(box).css("opacity")!="0.3"){info("Hide");jQuery(box).fadeTo("fast",0.3);}}}
MonthCalendar.prototype.clearFilter=function(){this.filter.value="";this.filter.style.color="";this.applyFilter();this.filter.value="Filter Events";this.filterClose.style.display="none";}
MonthCalendar.prototype.getMonthCell=function(month,day,year){var widget=this.getDayWidget(month,day,year);var cell=HTML.tableCell();cell.pouchtype="event";cell.appendChild(widget);cell.month=month;cell.day=day;cell.year=year;cell.eventId="setEventDate+pouch";var addButton=Images.get("addEvent");addButton.className="addEvent"
addButton.month=month;addButton.day=day;addButton.year=year;addButton.eventId="addCalendarEvent";cell.appendChild(addButton);cell.addWidget=addButton;return cell;}
MonthCalendar.prototype.getOffMonthCell=function(month,day,year){var widget=this.getDayWidget(month,day,year);var cell=HTML.tableCell();cell.appendChild(widget);cell.pouchtype="event";cell.className="blank";cell.month=month;cell.day=day;cell.year=year;cell.eventId="setEventDate+pouch";var addButton=Images.get("addEvent");addButton.className="addEvent"
addButton.month=month;addButton.day=day;addButton.year=year;addButton.eventId="addCalendarEvent";cell.appendChild(addButton);cell.addWidget=addButton;return cell;}
MonthCalendar.prototype.getDayWidget=function(month,day,year){var date=new Date((month+1)+"/"+day+"/"+year);var div=HTML.div("daylabel");div.eventId="monthday";div.cal=this;div.date=date;div.innerHTML=day;div.style.cursor="pointer"
div.title=date.toString();return div;}
MonthCalendar.prototype.redraw=function(){}
function getAbsPos(elt,which){iPos=0;while(elt!=null){if(which=="Top")
iPos+=elt.offsetTop;else
iPos+=elt.offsetLeft;elt=elt.offsetParent;}
return iPos;}
MonthCalendar.prototype.getPalette=function(){this.palette=HTML.div();this.palette.id="month_palette";this.palette.pouchtype="none";HTML.addToBody(this.palette);this.getPaletteToolbar();this.getPaletteContent();this.getCalendarPalette();}
MonthCalendar.prototype.getPaletteToolbar=function(){var toolbar=HTML.div("paletteToolbar");this.calendarsToggle=Images.get("calendar");this.calendarsToggle.cal=this;this.calendarsToggle.eventId="toggleCalendars"
toolbar.appendChild(this.calendarsToggle);this.shareToggle=Images.get("share");this.shareToggle.cal=this;this.shareToggle.eventId="toggleEventShare";toolbar.appendChild(this.shareToggle);this.trashToggle=Images.get("trashcan");this.trashToggle.cal=this;this.trashToggle.eventId="toggleEventTrash";toolbar.appendChild(this.trashToggle);this.palette.appendChild(toolbar);}
MonthCalendar.prototype.markPaletteActive=function(toggle){this.calendarsToggle.style.background="#ccc";this.trashToggle.style.background="#ccc";this.shareToggle.style.background="#ccc";deactivateLens("infoPalette");if(toggle=="detail"){activateLens("infoPalette");var active=this.zoomToggle;}else if(toggle=="trash")
var active=this.trashToggle;else if(toggle=="calendars")
var active=this.calendarsToggle;else if(toggle=="share")
var active=this.shareToggle;active.style.background="#eee";}
MonthCalendar.prototype.getPaletteContent=function(){this.paletteContent=HTML.div("calendar_palette_content");this.palette.appendChild(this.paletteContent);}
MonthCalendar.prototype.getTrashPalette=function(){this.markPaletteActive("trash");jQuery(this.paletteContent).empty();var dbdata=JSGI.ajaxJob("eventTrash").getDbData();for(var i=0,len=dbdata.numRows();i<len;i++){jQuery(this.paletteContent).append(eventBox(dbdata.getRowHash(i)));}}
MonthCalendar.prototype.getDetailPalette=function(){this.markPaletteActive("detail");this.paletteContent.innerHTML="Event Details";if(arguments[0]){var data=arguments[0];var list=new DefinitionList();list.addTitle("Name");list.addItem(data.name);list.addTitle("Date");list.addItem(formatDateString(data.startdate));list.addTitle("Time");list.addItem(formatTimeString(data.starttime,data.duration));list.addTitle("Duration");list.addItem(data.duration+' Minutes');list.addTitle("Notes");list.addItem(data.description);this.paletteContent.appendChild(list.markup());}else{this.paletteContent.innerHTML="Mouse over an event's name to view its details";}}
MonthCalendar.prototype.getCalendarPalette=function(){info("build calendar palettes.");this.markPaletteActive("calendars");this.paletteContent.innerHTML="";var req=JSGI.ajaxRequest("calendars");req.addUser();var dbdata=req.getDbData();info("Got some data.")
var list=new DefinitionList();this.calendarList=list;this.paletteContent.appendChild(list.markup());var title=list.addTitle("My Calendars");var grid=new Grid(dbdata.numRows(),4);var item=list.addItem();item.appendChild(grid.ref);for(var i=0,len=dbdata.numRows();i<len;i++){var data=dbdata.getRowHash(i);info(data);var visCheck=HTML.tag("input");visCheck.type="checkbox";visCheck.defaultChecked=(data.visible==1);visCheck.eventId="toggleCalendar";visCheck.dbid=data.id;grid.setContents(i+1,1,visCheck);var nameHolder=HTML.div();nameHolder.appendChild(HTML.textNode(data.name));nameHolder.eventId="editCalendarName";nameHolder.dbid=data.id;nameHolder.pouchtype="event";nameHolder.hexColor=data.color;grid.setContents(i+1,2,nameHolder);var colorMark=HTML.div("colorMark");colorMark.style.backgroundColor=data.color;colorMark.eventId="calendarColor";colorMark.dbid=data.id;grid.setContents(i+1,3,colorMark);grid.getCell(i+1,3).style.width="15px";var deleteCalendar=Images.get("clearButton");deleteCalendar.style.cursor="pointer";deleteCalendar.eventId="deleteCalendar";deleteCalendar.dbid=data.id;grid.setContents(i+1,4,deleteCalendar);grid.getCell(i+1,4).style.width="15px";}
var item=list.addItem();var newCalendarButton=HTML.blankButton("+");newCalendarButton.style.cursor="pointer";newCalendarButton.eventId="addCalendar";item.appendChild(newCalendarButton);}
MonthCalendar.prototype.getSharePalette=function(){this.markPaletteActive("share");this.paletteContent.innerHTML="";}
function WeekCalendar(month,day,year){this.months=["Jan","Feb","March","April","May","June","July","Aug","Sept","Oct","Nov","Dec"];this.weekdays=["Sun","Mon","Tues","Wed","Thurs","Fri","Sat"];this.today=new Date((month+1)+'/'+day+'/'+year);this.month=month;this.day=day;this.year=year;this.build();}
WeekCalendar.prototype.build=function(){if(this.weekHolder)
HTML.remove(this.weekHolder);this.weekHolder=HTML.div("weekholder");HTML.addToBody(this.weekHolder);this.generateScreen();this.determineDays();this.generateGrid();AppLens.lock("weekcalendar",this);}
WeekCalendar.prototype.loadEvents=function(){info("We're trying");var results=retrieveEvents(this.getFormattedDate(0),this.getFormattedDate(this.days.length-1));JSGI.parseJSON(results);if(!result)
return;var events=result;var dataSet=new DbData("eventQuery");dataSet.setHeader(events.header);dataSet.setBody(events.body);for(var i=0,len=dataSet.body.length;i<len;i++){var row=dataSet.getRowHash(i);var box=new eventBox(row);var cell=this.cells[row.month+'-'+row.day];cell.appendChild(box);}}
WeekCalendar.prototype.getFormattedDate=function(dayNumber){var date=this.days[dayNumber];return date.year+'-'+(date.month+1)+'-'+date.date;}
WeekCalendar.prototype.determineDays=function(){info(this.today.toString());var lastDay=this.getDays(this.today.getMonth(),this.today.getFullYear());var sunday=this.today.getDate();info(sunday);info(lastDay);var month=this.today.getMonth();var year=this.today.getFullYear();this.days=[];for(i=0;i<7;i++){var date=sunday+i;if(date>lastDay){subDate=date-lastDay;subMonth=month+1;subYear=year;}else{subDate=date;subMonth=month;subYear=year;}
if(month==12){subMonth=0;subYear=year+1;}
info("Build Week Day For:"+subMonth+"/"+subDate+"/"+subYear);this.days.push({month:subMonth,date:subDate,year:subYear});}}
WeekCalendar.prototype.generateScreen=function(){HTML.drawScreen("weekscreen",200);}
WeekCalendar.prototype.generateGrid=function(){this.table=HTML.table();var head=HTML.tableHead();head.appendChild(this.getLabel());head.appendChild(this.getHeader());this.table.appendChild(head);this.getBody();this.weekHolder.appendChild(this.table);}
WeekCalendar.prototype.getBody=function(){var body=HTML.tableBody();this.table.appendChild(body);var bodyRow=HTML.tableRow();var dayOfMonth=this.today.getDate();this.cells={};for(var i=0,len=this.days.length;i<len;i++){var day=this.days[i];var cell=HTML.tableCell();var dayView=new DayCalendar(day.month,day.date,day.year);cell.appendChild(dayView.dayHolder);dayView.loadEvents();bodyRow.appendChild(cell);}
body.appendChild(bodyRow);}
WeekCalendar.prototype.getLabel=function(){var label=HTML.tableRow();var cell=HTML.tableHeadCell();cell.className='weeklabel';cell.colSpan=7;var closeButton=Images.get("close");closeButton.eventId="closeWeek";closeButton.cal=this;closeButton.style.cursor='pointer';cell.appendChild(closeButton);var labelText=document.createTextNode("Events for the Week Of "+this.months[this.today.getMonth()]+" "+this.today.getDate()+", "+this.today.getFullYear());cell.appendChild(labelText);label.appendChild(cell);return label;}
WeekCalendar.prototype.getHeader=function(){var weekRow=HTML.tableRow();weekRow.className="weekdays";for(var i=0,len=this.weekdays.length;i<len;i++){var weekdayCell=HTML.tableHeadCell();weekdayCell.innerHTML=this.weekdays[i];weekRow.appendChild(weekdayCell);}
return weekRow;}
WeekCalendar.prototype.getDayWidget=function(month,day,year){var date=new Date((month+1)+"/"+day+"/"+year);var div=HTML.div("daylabel");div.eventId="monthday";div.cal=this;div.date=date;div.innerHTML=this.months[month]+' '+day;div.style.cursor="pointer"
div.title=date.toString();return div;}
WeekCalendar.prototype.getDays=function(month,year){daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];if(1==month)
return((0==year%4)&&(0!=(year%100)))||(0==year%400)?29:28;else
return daysInMonth[month];}
WeekCalendar.prototype.close=function(){HTML.remove(this.weekHolder);HTML.closeScreen("weekscreen");}
function DayCalendar(month,day,year){if(arguments[3]){this.calendarId=arguments[3];}else{this.calendarId="defaultAgenda";}
this.months=["January","February","March","April","May","June","July","August","September","October","November","December"];this.weekdays=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];info((month+1)+'/'+day+'/'+year);this.today=new Date((month+1)+'/'+day+'/'+year);info(this.today);this.month=month;this.day=day;this.year=year;this.events=[];activateLens("daycalendar",this);this.build();}
DayCalendar.prototype.build=function(){if(document.getElementById(this.calendarId)){this.dayHolder=document.getElementById(this.calendarId);this.selfContained=true;}else{this.dayHolder=HTML.div("dayholder",this.calendarId);HTML.addToBody(this.dayHolder);this.generateScreen();this.selfContained=false;}
this.getLayout();this.loadEvents();}
DayCalendar.prototype.loadEvents=function(){jQuery(this.events).remove();year=this.year;month=(this.month+1).toString().length==1?"0"+(this.month+1):(this.month+1)+"";day=(this.day).toString().length==1?"0"+this.day:this.day+"";info("Events for:"+month+"/"+day);var result=retrieveEvents(year+'-'+month+'-'+day,null);if(!result){return;}
this.events=[];for(var i=0,len=result.numRows();i<len;i++){var row=result.getRowHash(i);var box=eventBox(row,true);var timeParts=row.starttime.split(":");var minutes=timeParts[1];var hour=(minutes=='00'||minutes=='15')?timeParts[0]:timeParts[0]+'.5';var blocks=row.duration/30;var startCell=this.cells[hour];var endHour=parseFloat(hour)+(blocks*.5);var bottomCell=this.cells[endHour.toString()];var start=parseInt(getAbsPos(startCell,"Top"),10);var end=parseInt(getAbsPos(bottomCell,"Top"),10);var width=startCell.offsetWidth/result.numRows();var left=getAbsPos(startCell,"Left")+(i*width);HTML.addToBody(box);box.style.zIndex=303+i;box.style.position="absolute";box.style.top=start+"px";box.style.left=left+"px";box.style.height=(end-start)+"px";box.style.width=(startCell.offsetWidth/result.numRows()-10)+"px";box.cal=this;this.events.push(box);}}
DayCalendar.prototype.generateScreen=function(){HTML.drawScreen("dayscreen",300);}
DayCalendar.prototype.getLayout=function(){var table=HTML.table();var tbody=HTML.tableBody();table.appendChild(tbody);tbody.appendChild(this.getLabel());var hours=[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23];this.cells={};for(var i=0,len=hours.length;i<len;i++){var hour=hours[i];var row=HTML.tableRow();var label=HTML.tableHeadCell();var entries=HTML.tableCell();entries.innerHTML="&nbsp;";entries.eventId="addAgendaEvent-pouch,setEventTime+pouch";entries.time=hour+":00:00";entries.month=this.month;entries.day=this.day;entries.year=this.year;entries.pouchtype="event";this.cells[hour]=entries;var oldHour=hour;if(hour>12)
hour-=12;label.innerHTML=(hour==12)?'Noon':hour+":00";entries.innerHTML="&nbsp";row.appendChild(label);row.appendChild(entries);tbody.appendChild(row);var hRow=HTML.tableRow();var hLabel=HTML.tableHeadCell();var hEntries=HTML.tableCell();hLabel.innerHTML="&nbsp;";hEntries.innerHTML="&nbsp;";hEntries.eventId="addAgendaEvent-pouch,setEventTime+pouch";hEntries.time=hour+":30:00";hEntries.month=this.month;hEntries.day=this.day;hEntries.year=this.year;hEntries.pouchtype="event";this.cells[oldHour+'.5']=hEntries;hRow.appendChild(hLabel);hRow.appendChild(hEntries);tbody.appendChild(hRow);}
this.dayHolder.appendChild(table);jQuery(this.dayHolder).show("fast");}
DayCalendar.prototype.getLabel=function(){var label=HTML.tableRow();var cell=HTML.tableCell();cell.className="dayviewlabel";cell.colSpan=2;var close=Images.get('close');close.eventId='closeday';close.cal=this;close.style.cursor='pointer';if(!this.selfContained)
cell.appendChild(close);var text=HTML.textNode(this.months[this.today.getMonth()]+' '+this.today.getDate());cell.appendChild(text);label.appendChild(cell);return label;}
DayCalendar.prototype.close=function(){info("close agenda");info(this.dayHolder);jQuery(this.dayHolder).hide().remove();HTML.closeScreen("dayscreen");jQuery(this.events).remove();deactivateLens("daycalendar");}
DayCalendar.prototype.clearEvents=function(){jQuery(this.events).hide("fast");};applyTo(JSGI.click,{deleteEvent:function(){JSGI.CRUD.update("event_calendars","active",this.target.dbid,0);lensRef("monthcalendar").getTrashPalette();jQuery(this.target.eventNode).hide("fast");lensRef("monthcalendar").build();if(lensActive("daycalendar")){lensRef("daycalendar").build();}},calendarColor:function(){if(lensActive("colorPicker")){HTML.remove(this.target.menu);deactivateLens("colorPicker");}
else{activateLens("colorPicker",this.target);this.target.originalColor=this.target.style.backgroundColor;info(this.target.originalColor);var menu=buildColorMenu(8);HTML.addToBody(menu);menu.style.position="absolute";menu.style.zIndex="400";menu.style.backgroundColor="white";menu.style.border="1px solid gray";menu.style.top=(getAbsPos(this.target,"Top")+this.target.offsetHeight+5)+"px";menu.style.left=(document.body.offsetWidth-menu.offsetWidth)+"px";this.target.menu=menu;}},setCalendarColor:function(){var input=lensRef("colorPicker");JSGI.CRUD.update("calendars","color",input.dbid,this.target.colorHex);lensRef("monthcalendar").build();HTML.remove(lensRef("colorPicker").menu);deactivateLens("colorPicker");lensRef("monthcalendar").getCalendarPalette();},addCalendar:function(){info("Add Calendar!");var req=JSGI.ajaxRequest();info(req);req.setTable("calendars");req.setJob("add");info("blah");req.addUser();req.add("name","Calendar");info("about to send.");req.execute();info("sent");lensRef("monthcalendar").getCalendarPalette();info("built");},editCalendarName:function(){if(lensActive("pouch")){var pouch=lensRef("pouch");var len=this.evtRef.shiftKey?pouch.itemCount("event"):1;for(var i=0;i<len;i++){pouch.grabFirst("event").switchCalendar(this.target.dbid,this.target.hexColor);}}},deleteCalendar:function(){JSGI.CRUD.destroy("calendars",this.target.dbid);lensRef("monthcalendar").getCalendarPalette();lensRef("monthcalendar").build();},setEventDate:function(){var pouch=lensRef("pouch");var len=this.evtRef.shiftKey?pouch.itemCount("event"):1;for(var i=0;i<len;i++){var event=pouch.grabFirst("event");var id=event.dbid;JSGI.CRUD.update("events","startdate",id,this.target.year+'-'+(this.target.month+1)+'-'+this.target.day);JSGI.ajaxJob("restoreEvent").add("id",id).execute();HTML.remove(event);this.target.appendChild(event);if(pouch.isEmpty()){lensRef("monthcalendar").build();}}},addCalendarEvent:function(){var ed=new EventEditor("_NEW_","",this.target.month,this.target.day,this.target.year);ed.parent=this.target.parentNode;this.target.parentNode.appendChild(ed);ed.style.display="none";jQuery(ed).show("fast");},advanceMonth:function(){this.target.cal.incMonth(1);},decreaseMonth:function(){this.target.cal.incMonth(-1);},advanceYear:function(){this.target.cal.incYear(1);},decreaseYear:function(){this.target.cal.incYear(-1);},weekzoom:function(){var cal=new WeekCalendar(this.target.month,this.target.day,this.target.year);},closeWeek:function(){this.target.cal.close();},monthday:function(){var cal=new DayCalendar(this.target.date.getMonth(),this.target.date.getDate(),this.target.date.getFullYear());},closeday:function(){this.target.cal.close();},calendarEvent:function(){var editor=new EventEditor(this.target.dbid,this.target.innerHTML);editor.parent=this.target;if(lensActive("daycalendar")){var oldHeight=this.target.offsetHeight;}
this.target.innerHTML="";if(lensActive("daycalendar")){this.target.parentNode.parentNode.style.height="";}
this.target.appendChild(editor);editor.style.display="none";jQuery(editor).show("fast");},addAgendaEvent:function(){info("Make an editor.");var editor=new EventEditor("_NEW_","",this.target.month,this.target.day,this.target.year,this.target.time);info("Append Editor.");lensRef("daycalendar").clearEvents();this.target.appendChild(editor);},clearCalFilter:function(){this.target.cal.clearFilter();},toggleCalendars:function(){this.target.cal.getCalendarPalette();},toggleEventZoom:function(){this.target.cal.getDetailPalette();},toggleEventTrash:function(){this.target.cal.getTrashPalette();},toggleEventShare:function(){this.target.cal.getSharePalette();},setEventTime:function(){var pouch=lensRef("pouch");var len=this.evtRef.shiftKey?pouch.itemCount("event"):1;for(var i=0;i<len;i++){var event=pouch.grabFirst("event");var id=event.dbid;JSGI.CRUD.update("events","startdate",id,this.target.year+'-'+(this.target.month+1)+'-'+this.target.day);JSGI.CRUD.update("events","starttime",id,this.target.time);JSGI.ajaxJob("restoreEvent").add("id",event.dbid).execute();lensRef("daycalendar").build();lensRef("monthcalendar").build();}},saveEventEdit:function(){info("Save: "+this.target.sheet.getKey());pluckForm(this.target.sheet.getKey());this.target.sheet.cleanUpSave();},cancelEventEdit:function(){this.target.sheet.cleanUpCancel();},saveEventAdd:function(){info("Saving: "+this.target.sheet.getKey());pluckForm(this.target.sheet.getKey());this.target.sheet.cleanUpAdd();},toggleCalendar:function(){info("Toggling Calendar");var state=this.target.checked?"1":"0";JSGI.CRUD.update("calendars","visible",this.target.dbid,state);lensRef("monthcalendar").build();lensRef("monthcalendar").getCalendarPalette();}});JSGI.dblclick.editCalendarName=function(){var input=HTML.textBox();input.size=10;input.value=this.target.innerHTML;input.originalValue=input.value;input.onblur=function(e){cancelEditCalendarName(this);};this.target.innerHTML="";this.target.appendChild(input);input.focus();};function deletePouchEvents(){if(lensActive("pouch")){var pouch=lensRef("pouch");for(var i=0,len=pouch.itemCount("event");i<len;i++){var item=pouch.grabFirst("event");var id=item.dbid;JSGI.CRUD.destroy("events",id);lensRef("monthcalendar").getTrashPalette();jQuery(item).hide("fast");if(pouch.isEmpty()){lensRef("monthcalendar").build();if(lensActive("daycalendar")){lensRef("daycalendar").build();}}}}}
function cancelEditCalendarName(target){var value=target.originalValue;target.parentNode.innerHTML=value;}
function saveCalendarName(target){var value=target.value;JSGI.CRUD.update("calendars","name",target.parentNode.dbid,value);lensRef("monthcalendar").getCalendarPalette();}
KeyMap.set(JSGI.KEY_RETURN,[],function(evtRef,target){if(target.fetch)return selectManualTagValue(target)});KeyMap.set(JSGI.KEY_ESC,[],function(evtRef,target){if(target.fetch)return cancelTag(target)});KeyMap.set(JSGI.KEY_DOWN,[],function(evtRef,target){Picker.focus()});KeyMap.set(JSGI.KEY_UP,[],function(evtRef,target){Picker.focus()});KeyMap.set(JSGI.KEY_ESC,["shift"],function(evtRef,target){Picker.show()});KeyMap.set(JSGI.KEY_ESC,[],function(evtRef,target){Picker.hide();return true;});KeyMap.set(JSGI.KEY_RETURN,[],function(evtRef,target){Picker.select()});KeyMap.set(JSGI.KEY_TAB,[],function(evtRef,target){Picker.focus()});KeyMap.set(JSGI.KEY_RETURN,[],function(evtRef,target){if(target.popupId&&!isTextArea(target))target.popupSet.save()});KeyMap.set(JSGI.KEY_RETURN,["shift"],function(evtRef,target){if(!target.popup)pluckForm()});KeyMap.set(JSGI.KEY_ESC,[],function(evtRef,target){if(target.popup)target.popupSet.rollback();return true});KeyMap.set(JSGI.KEY_DOWN,[],function(evtRef,target){if(target.dataSet&&!isDropdown(target)&&!isTextArea(target))target.dataSet.moveDownOneRow(target.id)});KeyMap.set(JSGI.KEY_UP,[],function(evtRef,target){if(!isTextArea(terget))target.dataSet.moveUpOneRow(target.id)});KeyMap.set(JSGI.KEY_DOWN,["ctrl"],function(evtRef,target){target.dataSet.addRow()});KeyMap.set(JSGI.KEY_LEFT,["shift","ctrl"],function(evtRef,target){target.dataSet.keyboardFirstPage()});KeyMap.set(JSGI.KEY_RIGHT,["shift","ctrl"],function(evtRef,target){target.dataSet.keyboardLastPage()});KeyMap.set(JSGI.KEY_LEFT,["ctrl"],function(evtRef,target){target.dataSet.prevPage()});KeyMap.set(JSGI.KEY_LEFT,["ctrl","shift"],function(evtRef,target){target.dataSet.firstPage()});KeyMap.set(JSGI.KEY_RIGHT,["ctrl"],function(evtRef,target){target.dataSet.nextPage()});KeyMap.set(JSGI.KEY_RIGHT,["ctrl","shift"],function(evtRef,target){target.dataSet.lastPage()});KeyMap.set(JSGI.KEY_DELETE,[],function(evtRef,target){deletePouchEvents()});KeyMap.set(JSGI.KEY_ESC,[],function(evtRef,target){if(lensActive("pouch")){lensRef("pouch").cleanUp();lensRef("monthcalendar").build();if(lensActive("daycalendar"))
lensRef("daycalendar").build();}
if(lensActive("modalsheet")){lensRef("modalsheet").close();deactivateLens("modalsheet");}});KeyMap.set(JSGI.KEY_ESC,[],function(evtRef,target){if(target.parentNode.eventId=="editCalendarName"){cancelEditCalendarName(target);}});KeyMap.set(JSGI.KEY_RETURN,[],function(evtRef,target){if(target.parentNode.eventId=="editCalendarName"){saveCalendarName(target);}});KeyMap.set(JSGI.KEY_RETURN,[],function(evtRef,target){if(lensActive("modalsheet")){pluckForm();lensRef("modalsheet").close();lensRef("monthcalendar").build();}});KeyMap.set(JSGI.KEY_LEFT,[],function(evtRef,target){if(lensActive("monthcalendar")&&!lensActive("modalsheet")){lensRef("monthcalendar").incMonth(-1);}});KeyMap.set(JSGI.KEY_RIGHT,[],function(evtRef,target){if(lensActive("monthcalendar")&&!lensActive("modalsheet")){lensRef("monthcalendar").incMonth(1);}});KeyMap.set("*",["*","*"],pickModeLetters);KeyMap.set("*",["*","*"],JSGI.validateField);KeyMap.set("*",["*","*"],updateData);KeyMap.set("*",["*","*"],applyAdjustments);KeyMap.set("*",["*","*"],autoFocusAdvance);KeyMap.set("*",["*","*"],calendarFilterType);KeyMap.set("*",["*","*"],function(evtRef,target){if(target.fetch)tagType(target)});Images.load(imageMap);(function($){$.fn.property=function(propName,propValue){return this.each(function(){this[propName]=propValue;});};$.fn.properties=function(hash){return this.each(function(){for(propName in hash){this[propName]=hash[propName];}});};$.fn.noMatches=function(){return this.length<1;};$.fn.moveTo=function(){var top=0,left=0,hash;if(arguments[3]){top=arguments[0];left=arguments[1];if(arguments[2]){top+=arguments[2];}
if(arguments[3]){left+=arguments[3];}}else if(arguments[2]){hash=arguments[0];top=hash.top;left=hash.left;if(arguments[1]){top+=arguments[1];}
if(arguments[2]){left+=arguments[2];}}
info([top,left]);return this.each(function(){info([top,left]);$(this).css("top",top).css("left",left);});};$.fn.activateSavedFlippyPanels=function(){return this.each(function(){$(this).css("cursor","pointer").prepend("<span class='flippy'></span>").restoreFlippyStatus().setFlippyTriangle().filter(".closed").next().toggle().end().end().click(function(event){info(event.target);$(event.target).toggleClass("closed").setFlippyTriangle().rememberFlippyStatus().next().toggle("fast").find("textarea, :text:eq(0)").focus();});});};$.fn.setFlippyTriangle=function(){return this.each(function(){var RIGHT_TRIANGLE="&#x25B8;&nbsp;",DOWN_TRIANGLE="&#x25BE;&nbsp;",heading=$(this),flippy=heading.find(".flippy");heading.is(".closed")?flippy.html(RIGHT_TRIANGLE):flippy.html(DOWN_TRIANGLE);});};$.fn.rememberFlippyStatus=function(){return this.each(function(){var key=$(this).attr("remember");if(key){$.cookie("remember-"+key,($(this).is(".closed")).toString());}});};$.fn.restoreFlippyStatus=function(){return this.each(function(){var rememberKey=$(this).attr("remember");if(rememberKey&&$.cookie("remember-"+rememberKey)=="true"){$(this).addClass("closed");}});};$.fn.activateNameEntry=function(){var parsedValues={first:"",last:"",middle:"",prefix:"",suffix:""},fieldName="",ref=null;function setValue(name,value){parsedValues[name]=value.replace(/\.|\,/,"");}
function clearValues(){parsedValues={first:"",last:"",middle:"",prefix:"",suffix:""};}
function parseEntry(){var parts=ref.value.split(" ");clearValues();switch(parts.length){case 1:setValue("first",parts[0]);break;case 2:setValue("first",parts[0]);setValue("last",parts[1]);break;case 3:setValue("first",parts[0]);setValue("middle",parts[1]);setValue("last",parts[2]);break;case 4:setValue("first",parts[0]);setValue("middle",parts[1]);setValue("last",parts[2]);setValue("suffix",parts[3]);break;}
info("Do: "+fieldName);info(parsedValues);}
function suggestParse(){var message="";if(parsedValues.first){message+="First Name: "+parsedValues.first+"<br/>";$("#"+fieldName+"-firstname").val(parsedValues.first);}
if(parsedValues.middle){message+="Middle Name: "+parsedValues.middle+"<br/>";$("#"+fieldName+"-middlename").val(parsedValues.middle);}
if(parsedValues.last){message+="Last Name: "+parsedValues.last+"<br/>";$("#"+fieldName+"-lastname").val(parsedValues.last);}
if(parsedValues.suffix){message+="Suffix: "+parsedValues.suffix+"<br/>";$("#"+fieldName+"-suffix").val(parsedValues.suffix);}
$("#name_parse-"+fieldName).html(message);info("fieldName:"+fieldName);}
function extractBase(fieldname){return fieldname.split("[")[0];}
function setField(field){info("Set Field");info(field);ref=field;fieldName=extractBase(field.name);}
return this.each(function(){var name=extractBase(this.name);$("#name_parse-"+name).hide();setField(this);parseEntry();suggestParse();$(this).attr("autocomplete","off").focus(function(event){setField(event.target);$("#name_parse-"+fieldName).show("fast");parseEntry();suggestParse();}).blur(function(event){$("#name_parse-"+extractBase(event.target.name)).hide("fast");}).keyup(function(event){setField(event.target);parseEntry();suggestParse();event.preventDefault();});});};})(jQuery);(function($){$(function(){$("form.rjs").livequery(function(){$(this).ajaxForm({dataType:'script'});});$("a.rjs").livequery('click',function(event){$.ajax({url:this.href,dataType:"script"});return false;});$(":text.autocomplete").livequery(function(){$(this).autocompletify();});$(":text.name_entry").activateNameEntry();$(".toggler").livequery(function(){$(this).activateSavedFlippyPanels();});$(".popout .data_table tr:even td").css("background-color","#eee");$(".popoutLink").livequery('click',function(event){var win=window.open(this.href,'popout-'+this.href,'resizable=1,scrollbars=1,status=0,height=580,width=320');win.focus();return false;});$("button.checkbox_list_select_all").click(function(event){var chidlers=$(this).parent().find(":checkbox").each(function(){this.defaultChecked=true;});return false;});$("button.checkbox_list_select_none").click(function(event){var chidlers=$(this).parent().find(":checkbox").each(function(){this.defaultChecked=false;});return false;});buildTablesAndForms();if(JSGI.menu_style=='side'){loadPersonalSlider();}else{loadPersonalMenu();}
$(document).trigger('pageloaded');});})(jQuery);function getSaveBar(){if(jQuery("#saveBar").noMatches()){jQuery("<div id='saveBar'></div>").prependTo("body:eq(0)").append(jQuery("<div class='leftButtons' id='leftButtons'></div>")).append(jQuery("<div class='pageButtons' id='pageButtons'></div>"));}}
function getSaveButton(){jQuery(Images.get("saveInactive")).appendTo("#pageButtons").attr({title:"Save All Changes",id:"saveButton"}).css("zIndex","4000").get(0).eventId="saveClick";}
function getHelpButton(lookupKey){jQuery(Images.get("systemHelp")).appendTo("#pageButtons").attr({title:"Read tips and hints for this page.",id:"helpButton",lookupkey:lookupKey}).click(lookupHelp).css("zIndex","4000");}
function getLogoutButton(){jQuery(Images.get("logout")).appendTo("#pageButtons").attr({title:"Log Out",id:"logoutButton"}).click(function(event){location.href=appName+"/Main/logout.do";}).css("zIndex","4000");}
function getPageInfoButton(ctlr,action){if(developing){jQuery(Images.get("pageInfo")).appendTo("#pageButtons").attr({title:"Edit Page Setup",id:"optionsButton"}).properties({ctlr:ctlr,act:action,eventId:"pageInfo"}).click(function(event){var dialogue=new ModalSheet('/admin/edit_roletasks_on_page',{ctlr:event.target.ctlr,act:event.target.act});});}}
function lookupHelp(evt){var target=JSGI.getEventTarget(evt);showhelp(target.getAttribute('lookupkey'));}
function getBackButton(backType){jQuery(Images.get("back")).appendTo("#leftButtons").attr({title:"Go Back",id:"backToListButton",action:backType}).click(backButtonClick).css("zIndex","4000");}
